Skip to content
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

Axsuarez/corebot updates #249

Merged
merged 7 commits into from
Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
7 changes: 1 addition & 6 deletions libraries/botbuilder-ai/botbuilder/ai/luis/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from .intent_score import IntentScore
from .luis_application import LuisApplication
from .luis_prediction_options import LuisPredictionOptions
from .luis_telemetry_constants import LuisTelemetryConstants
from .recognizer_result import RecognizerResult, TopIntent
from .luis_recognizer import LuisRecognizer

__all__ = [
"IntentScore",
"LuisApplication",
"LuisPredictionOptions",
"LuisRecognizer",
"LuisTelemetryConstants",
"RecognizerResult",
"TopIntent",
"LuisTelemetryConstants"
]
14 changes: 0 additions & 14 deletions libraries/botbuilder-ai/botbuilder/ai/luis/intent_score.py

This file was deleted.

4 changes: 2 additions & 2 deletions libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@
from botbuilder.core import (
BotAssert,
BotTelemetryClient,
IntentScore,
NullTelemetryClient,
RecognizerResult,
TurnContext,
)
from botbuilder.schema import Activity, ActivityTypes, ChannelAccount

from . import (
IntentScore,
LuisApplication,
LuisPredictionOptions,
LuisTelemetryConstants,
RecognizerResult,
)
from .activity_util import ActivityUtil
from .luis_util import LuisUtil
Expand Down
2 changes: 1 addition & 1 deletion libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
EntityModel,
LuisResult,
)
from botbuilder.core import IntentScore, RecognizerResult
from msrest import Serializer

from .. import __title__, __version__
from . import IntentScore, RecognizerResult


class LuisUtil:
Expand Down
50 changes: 0 additions & 50 deletions libraries/botbuilder-ai/botbuilder/ai/luis/recognizer_result.py

This file was deleted.

5 changes: 1 addition & 4 deletions libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,12 @@
from requests.models import Response

from botbuilder.ai.luis import (
IntentScore,
LuisApplication,
LuisPredictionOptions,
LuisRecognizer,
RecognizerResult,
TopIntent,
)
from botbuilder.ai.luis.luis_util import LuisUtil
from botbuilder.core import BotAdapter, BotTelemetryClient, TurnContext
from botbuilder.core import BotAdapter, BotTelemetryClient, IntentScore, RecognizerResult, TopIntent, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import (
Activity,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from typing import Dict

from botbuilder.ai.luis import LuisRecognizer, LuisTelemetryConstants, RecognizerResult
from botbuilder.core import TurnContext
from botbuilder.ai.luis import LuisRecognizer, LuisTelemetryConstants
from botbuilder.core import RecognizerResult, TurnContext


class OverrideFillRecognizer(LuisRecognizer):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from typing import Dict

from botbuilder.ai.luis import LuisRecognizer, LuisTelemetryConstants, RecognizerResult
from botbuilder.core import TurnContext
from botbuilder.ai.luis import LuisRecognizer, LuisTelemetryConstants
from botbuilder.core import RecognizerResult, TurnContext


class TelemetryOverrideRecognizer(LuisRecognizer):
Expand Down
7 changes: 7 additions & 0 deletions libraries/botbuilder-core/botbuilder/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@
from .bot_telemetry_client import BotTelemetryClient
from .card_factory import CardFactory
from .conversation_state import ConversationState
from .intent_score import IntentScore
from .invoke_response import InvokeResponse
from .memory_storage import MemoryStorage
from .message_factory import MessageFactory
from .middleware_set import AnonymousReceiveMiddleware, Middleware, MiddlewareSet
from .null_telemetry_client import NullTelemetryClient
from .recognizer import Recognizer
from .recognizer_result import RecognizerResult, TopIntent
from .state_property_accessor import StatePropertyAccessor
from .state_property_info import StatePropertyInfo
from .storage import Storage, StoreItem, calculate_change_hash
Expand All @@ -39,16 +42,20 @@
'CardFactory',
'ConversationState',
'conversation_reference_extension',
'IntentScore',
'InvokeResponse',
'MemoryStorage',
'MessageFactory',
'Middleware',
'MiddlewareSet',
'NullTelemetryClient',
'Recognizer',
'RecognizerResult',
'StatePropertyAccessor',
'StatePropertyInfo',
'Storage',
'StoreItem',
'TopIntent',
'TurnContext',
'UserState',
'UserTokenProvider',
Expand Down
17 changes: 17 additions & 0 deletions libraries/botbuilder-core/botbuilder/core/intent_score.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from msrest.serialization import Model
from typing import Dict


class IntentScore(Model):
_attribute_map = {
'score': {'key': 'score', 'type': 'float'},
'properties': {'key': 'properties', 'type': '{object}'},
}

def __init__(self, score: float = None, properties: Dict[str, object] = {}, **kwargs):
super(IntentScore, self).__init__(**kwargs)
self.score = score
self.properties = properties
12 changes: 12 additions & 0 deletions libraries/botbuilder-core/botbuilder/core/recognizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from abc import ABC
from .turn_context import TurnContext
from .recognizer_result import RecognizerResult


class Recognizer(ABC):
@staticmethod
async def recognize(turn_context: TurnContext) -> RecognizerResult:
raise NotImplementedError()
60 changes: 60 additions & 0 deletions libraries/botbuilder-core/botbuilder/core/recognizer_result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from typing import Dict, NamedTuple

from msrest.serialization import Model
from botbuilder.core import IntentScore


class TopIntent(NamedTuple):
"""The top scoring intent and its score."""

intent: str
score: float


class RecognizerResult(Model):
"""Contains recognition results generated by a recognizer."""

_attribute_map = {
'text': {'key': 'text', 'type': 'str'},
'altered_text': {'key': 'alteredText', 'type': 'str'},
'intents': {'key': 'intents', 'type': '{IntentScore}'},
'entities': {'key': 'entities', 'type': '{object}'},
'properties': {'key': 'properties', 'type': '{object}'},
}

def __init__(self, *, text: str = None, altered_text: str = None, intents: Dict[str, IntentScore] = None,
entities: Dict[str, object] = None, properties: Dict[str, object] = None, **kwargs):
super(RecognizerResult, self).__init__(**kwargs)
self.text = text
self.altered_text = altered_text or kwargs.get('alteredText')
self.intents = intents
self.entities = entities
self.properties = properties or {}

def convert(self, result: object):
self.text = result.text
self.altered_text = result.altered_text
self.intents = result.intents
self.entities = result.entities
self.properties = result.properties

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
27 changes: 27 additions & 0 deletions samples/Core-Bot/adapter_with_error_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, ConversationState, MessageFactory,
TurnContext)
from botbuilder.schema import InputHints


class AdapterWithErrorHandler(BotFrameworkAdapter):

def __init__(self, settings: BotFrameworkAdapterSettings, conversation_state: ConversationState):
super().__init__(settings)
self._conversation_state = conversation_state

# Catch-all for errors.
async def on_error(self, context: TurnContext, error: Exception):
axelsrz marked this conversation as resolved.
Show resolved Hide resolved
# This check writes out errors to console log
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f'\n [on_turn_error]: {error}', file=sys.stderr)

# Send a message to the user
error_message_text = 'Sorry, it looks like something went wrong.'
error_message = MessageFactory.text(error_message_text, error_message_text, InputHints.expecting_input)
await context.send_activity(error_message)
# Clear out state
await self._conversation_state.delete(context)
9 changes: 7 additions & 2 deletions samples/Core-Bot/booking_details.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from typing import List


class BookingDetails:
def __init__(self, destination: str = None, origin: str = None, travel_date: str = None):
def __init__(self, destination: str = None, origin: str = None, travel_date: str = None,
unsupported_airports: List[str] = []):
self.destination = destination
self.origin = origin
self.travel_date = travel_date
self.travel_date = travel_date
self.unsupported_airports = unsupported_airports
17 changes: 7 additions & 10 deletions samples/Core-Bot/bots/dialog_and_welcome_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@

from typing import List
from botbuilder.core import CardFactory
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
from botbuilder.core import ActivityHandler, ConversationState, MessageFactory, UserState, TurnContext
from botbuilder.dialogs import Dialog
from botbuilder.schema import Activity, Attachment, ChannelAccount
from helpers.activity_helper import create_activity_reply
from helpers.dialog_helper import DialogHelper

from .dialog_bot import DialogBot


class DialogAndWelcomeBot(DialogBot):

def __init__(self, conversation_state: ConversationState, user_state: UserState, dialog: Dialog):
Expand All @@ -24,19 +25,15 @@ async def on_members_added_activity(self, members_added: List[ChannelAccount], t
# To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if member.id != turn_context.activity.recipient.id:
welcome_card = self.create_adaptive_card_attachment()
response = self.create_response(turn_context.activity, welcome_card)
response = MessageFactory.attachment(welcome_card)
await turn_context.send_activity(response)

# Create an attachment message response.
def create_response(self, activity: Activity, attachment: Attachment):
response = create_activity_reply(activity)
response.attachments = [attachment]
return response
await DialogHelper.run_dialog(self.dialog, turn_context,
self.conversation_state.create_property("DialogState"))

# Load attachment from file.
def create_adaptive_card_attachment(self):
relative_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(relative_path, "resources/welcomeCard.json")
path = os.path.join(relative_path, "../cards/welcomeCard.json")
with open(path) as f:
card = json.load(f)

Expand Down
3 changes: 2 additions & 1 deletion samples/Core-Bot/bots/dialog_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from botbuilder.dialogs import Dialog
from helpers.dialog_helper import DialogHelper


class DialogBot(ActivityHandler):

def __init__(self, conversation_state: ConversationState, user_state: UserState, dialog: Dialog):
Expand All @@ -24,7 +25,7 @@ def __init__(self, conversation_state: ConversationState, user_state: UserState,
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)

# Save any state changes that might have occured during the turn.
# Save any state changes that might have occurred during the turn.
await self.conversation_state.save_changes(turn_context, False)
await self.user_state.save_changes(turn_context, False)

Expand Down
Loading