Skip to content

Commit

Permalink
Merge 1a50ebf into f7d5dfa
Browse files Browse the repository at this point in the history
  • Loading branch information
imLew committed Nov 16, 2019
2 parents f7d5dfa + 1a50ebf commit 1710d8a
Show file tree
Hide file tree
Showing 49 changed files with 330 additions and 351 deletions.
7 changes: 3 additions & 4 deletions rasa/cli/utils.py
@@ -1,4 +1,5 @@
import os
import warnings
import sys
import json
from typing import Any, Optional, Text, List, Dict, TYPE_CHECKING
Expand Down Expand Up @@ -40,10 +41,8 @@ def get_validated_path(
if current is None:
reason_str = f"Parameter '{parameter}' not set."
else:
logger.warning(
"'{}' does not exist. Using default value '{}' instead.".format(
current, default
)
warnings.warn(
f"'{current}' does not exist. Using default value '{default}' instead."
)

logger.debug(f"{reason_str} Using default location '{default}' instead.")
Expand Down
32 changes: 17 additions & 15 deletions rasa/core/agent.py
@@ -1,4 +1,5 @@
import logging
import warnings
import os
import shutil
import tempfile
Expand Down Expand Up @@ -272,7 +273,7 @@ async def load_agent(
)

else:
logger.warning("No valid configuration given to load agent.")
warnings.warn("No valid configuration given to load agent.")
return None

except Exception as e:
Expand Down Expand Up @@ -458,9 +459,10 @@ async def handle_message(
"""Handle a single message."""

if not isinstance(message, UserMessage):
logger.warning(
warnings.warn(
"Passing a text to `agent.handle_message(...)` is "
"deprecated. Rather use `agent.handle_text(...)`."
"deprecated. Rather use `agent.handle_text(...)`.",
DeprecationWarning,
)
# noinspection PyTypeChecker
return await self.handle_text(
Expand Down Expand Up @@ -624,14 +626,13 @@ async def load_data(
unique_last_num_states = max_history
elif unique_last_num_states < max_history:
# possibility of data loss
logger.warning(
"unique_last_num_states={} but "
"maximum max_history={}."
"Possibility of data loss. "
"It is recommended to set "
"unique_last_num_states to "
"at least maximum max_history."
"".format(unique_last_num_states, max_history)
warnings.warn(
f"unique_last_num_states={unique_last_num_states} but "
f"maximum max_history={max_history}. "
f"Possibility of data loss. "
f"It is recommended to set "
f"unique_last_num_states to "
f"at least maximum max_history."
)

return await training.load_data(
Expand Down Expand Up @@ -707,11 +708,12 @@ def handle_channels(

from rasa.core import run

logger.warning(
"DEPRECATION warning: Using `handle_channels` is deprecated. "
warnings.warn(
"Using `handle_channels` is deprecated. "
"Please use `rasa.run(...)` or see "
"`rasa.core.run.configure_app(...)` if you want to implement "
"this on a more detailed level."
"this on a more detailed level.",
DeprecationWarning,
)

app = run.configure_app(channels, cors, None, enable_api=False, route=route)
Expand Down Expand Up @@ -908,7 +910,7 @@ def load_local_model(
model_archive = get_latest_model(model_path)

if model_archive is None:
logger.warning(f"Could not load local model in '{model_path}'")
warnings.warn(f"Could not load local model in '{model_path}'.")
return Agent()

working_directory = tempfile.mkdtemp()
Expand Down
7 changes: 4 additions & 3 deletions rasa/core/brokers/utils.py
@@ -1,4 +1,5 @@
import logging
import warnings
import os
import typing
from typing import Optional, Text
Expand Down Expand Up @@ -49,9 +50,9 @@ def load_event_channel_from_module_string(
event_channel = rasa_utils.class_from_module_path(broker_config.type)
return event_channel.from_endpoint_config(broker_config)
except (AttributeError, ImportError) as e:
logger.warning(
"EventChannel type '{}' not found. "
"Not using any event channel. Error: {}".format(broker_config.type, e)
warnings.warn(
f"EventChannel type '{broker_config.type}' not found. "
f"Not using any event channel. Error: {e}"
)
return None

Expand Down
5 changes: 3 additions & 2 deletions rasa/core/channels/facebook.py
@@ -1,5 +1,6 @@
import hashlib
import hmac
import warnings
import logging
from fbmessenger import MessengerClient
from fbmessenger.attachments import Image
Expand Down Expand Up @@ -88,7 +89,7 @@ async def message(
else:
logger.warning(
"Received a message from facebook that we can not "
"handle. Message: {}".format(message)
f"handle. Message: {message}"
)
return

Expand Down Expand Up @@ -168,7 +169,7 @@ async def send_text_with_buttons(

# buttons is a list of tuples: [(option_name,payload)]
if len(buttons) > 3:
logger.warning(
warnings.warn(
"Facebook API currently allows only up to 3 buttons. "
"If you add more, all will be ignored."
)
Expand Down
13 changes: 6 additions & 7 deletions rasa/core/channels/slack.py
@@ -1,4 +1,5 @@
import json
import warnings
import logging
import re
from sanic import Blueprint, response
Expand Down Expand Up @@ -79,7 +80,7 @@ async def send_text_with_buttons(
text_block = {"type": "section", "text": {"type": "plain_text", "text": text}}

if len(buttons) > 5:
logger.warning(
warnings.warn(
"Slack API currently allows only up to 5 buttons. "
"If you add more, all will be ignored."
)
Expand Down Expand Up @@ -204,7 +205,7 @@ def _sanitize_user_message(text, uids_to_remove) -> Text:
# but is a good first approximation
for regex, replacement in [
(fr"<@{uid_to_remove}>\s", ""),
(fr"\s<@{uid_to_remove}>", "",), # a bit arbitrary but probably OK
(fr"\s<@{uid_to_remove}>", ""), # a bit arbitrary but probably OK
(fr"<@{uid_to_remove}>", " "),
]:
text = re.sub(regex, replacement, text)
Expand Down Expand Up @@ -244,9 +245,7 @@ def _is_interactive_message(payload: Dict) -> bool:
elif action_type:
logger.warning(
"Received input from a Slack interactive component of type "
+ "'{}', for which payload parsing is not yet supported.".format(
payload["actions"][0]["type"]
)
f"'{payload['actions'][0]['type']}', for which payload parsing is not yet supported."
)
return False

Expand Down Expand Up @@ -289,8 +288,8 @@ async def process_message(
retry_count = request.headers.get(self.retry_num_header)
if retry_count and retry_reason in self.errors_ignore_retry:
logger.warning(
"Received retry #{} request from slack"
" due to {}".format(retry_count, retry_reason)
f"Received retry #{retry_count} request from slack"
f" due to {retry_reason}."
)

return response.text(None, status=201, headers={"X-Slack-No-Retry": 1})
Expand Down
3 changes: 2 additions & 1 deletion rasa/core/channels/socketio.py
@@ -1,4 +1,5 @@
import logging
import warnings
import uuid
from sanic import Blueprint, response
from sanic.request import Request
Expand Down Expand Up @@ -175,7 +176,7 @@ async def handle_message(sid: Text, data: Dict) -> Any:

if self.session_persistence:
if not data.get("session_id"):
logger.warning(
warnings.warn(
"A message without a valid sender_id "
"was received. This message will be "
"ignored. Make sure to set a proper "
Expand Down
27 changes: 13 additions & 14 deletions rasa/core/domain.py
@@ -1,4 +1,5 @@
import collections
import warnings
import json
import logging
import os
Expand Down Expand Up @@ -249,12 +250,11 @@ def collect_templates(

# templates should be a dict with options
if isinstance(t, str):
logger.warning(
warnings.warn(
"Deprecated: Templates should not be strings anymore. "
"Utterance template '{}' should contain either '- text: ' or "
"'- custom: ' attribute to be a proper template.".format(
template_key
)
f"Utterance template '{template_key}' should contain either '- text: ' or "
"'- custom: ' attribute to be a proper template.",
DeprecationWarning,
)
validated_variations.append({"text": t})
elif "text" not in t and "custom" not in t:
Expand Down Expand Up @@ -536,11 +536,11 @@ def _get_featurized_entities(self, latest_message: UserUttered) -> Set[Text]:
explicitly_included = isinstance(include, list)
ambiguous_entities = included_entities.intersection(excluded_entities)
if explicitly_included and ambiguous_entities:
logger.warning(
"Entities: '{}' are explicitly included and excluded for intent '{}'. "
warnings.warn(
f"Entities: '{ambiguous_entities}' are explicitly included and"
f" excluded for intent '{intent_name}'."
"Excluding takes precedence in this case. "
"Please resolve that ambiguity."
"".format(ambiguous_entities, intent_name)
)

return entity_names.intersection(wanted_entities)
Expand All @@ -556,13 +556,12 @@ def get_prev_action_states(
if prev_action_name in self.input_state_map:
return {prev_action_name: 1.0}
else:
logger.warning(
"Failed to use action '{}' in history. "
warnings.warn(
f"Failed to use action '{latest_action}' in history. "
"Please make sure all actions are listed in the "
"domains action list. If you recently removed an "
"action, don't worry about this warning. It "
"should stop appearing after a while. "
"".format(latest_action)
)
return {}
else:
Expand Down Expand Up @@ -909,11 +908,11 @@ def check_missing_templates(self) -> None:

if missing_templates:
for template in missing_templates:
logger.warning(
"Utterance '{}' is listed as an "
warnings.warn(
f"Utterance '{template}' is listed as an "
"action in the domain file, but there is "
"no matching utterance template. Please "
"check your domain.".format(template)
"check your domain."
)

def is_empty(self) -> bool:
Expand Down
11 changes: 6 additions & 5 deletions rasa/core/events/__init__.py
Expand Up @@ -2,6 +2,7 @@
import typing

import json
import warnings
import jsonpickle
import logging
import uuid
Expand Down Expand Up @@ -32,7 +33,7 @@ def deserialise_events(serialized_events: List[Dict[Text, Any]]) -> List["Event"
deserialised.append(event)
else:
logger.warning(
"Ignoring event ({}) while deserialising "
f"Ignoring event ({event}) while deserialising "
"events. Couldn't parse it."
)

Expand Down Expand Up @@ -142,10 +143,10 @@ def _from_parameters(cls, parameters: Dict[Text, Any]) -> Optional["Event"]:
result = cls._from_story_string(parameters)
if len(result) > 1:
logger.warning(
"Event from parameters called with parameters "
"for multiple events. This is not supported, "
"only the first event will be returned. "
"Parameters: {}".format(parameters)
f"Event from parameters called with parameters "
f"for multiple events. This is not supported, "
f"only the first event will be returned. "
f"Parameters: {parameters}"
)
return result[0] if result else None

Expand Down
3 changes: 1 addition & 2 deletions rasa/core/featurizers.py
Expand Up @@ -238,8 +238,7 @@ def encode(self, state: Dict[Text, float]) -> np.ndarray:

else:
logger.warning(
"Feature '{}' could not be found in "
"feature map.".format(state_name)
f"Feature '{state_name}' could not be found in feature map."
)

if using_only_ints:
Expand Down
24 changes: 11 additions & 13 deletions rasa/core/interpreter.py
@@ -1,5 +1,6 @@
import aiohttp

import warnings
import json
import logging
import re
Expand Down Expand Up @@ -37,20 +38,17 @@ def create(

if not isinstance(obj, str):
if obj is not None:
logger.warning(
warnings.warn(
"Tried to create NLU interpreter "
"from '{}', which is not possible."
f"from '{obj}', which is not possible. "
"Using RegexInterpreter instead."
"".format(obj)
)
return RegexInterpreter()

if endpoint is None:
if not os.path.exists(obj):
logger.warning(
"No local NLU model '{}' found. Using RegexInterpreter instead.".format(
obj
)
f"No local NLU model '{obj}' found. Using RegexInterpreter instead."
)
return RegexInterpreter()
else:
Expand Down Expand Up @@ -102,12 +100,12 @@ def _parse_parameters(
".".format(type(parsed_entities))
)
except Exception as e:
logger.warning(
warnings.warn(
"Invalid to parse arguments in line "
"'{}'. Failed to decode parameters "
f"'{user_input}'. Failed to decode parameters "
"as a json object. Make sure the intent "
"is followed by a proper json object. "
"Error: {}".format(user_input, e)
f"Error: {e}"
)
return []

Expand All @@ -119,11 +117,11 @@ def _parse_confidence(confidence_str: Text) -> float:
try:
return float(confidence_str.strip()[1:])
except Exception as e:
logger.warning(
warnings.warn(
"Invalid to parse confidence value in line "
"'{}'. Make sure the intent confidence is an "
"'{confidence_str}'. Make sure the intent confidence is an "
"@ followed by a decimal number. "
"Error: {}".format(confidence_str, e)
f"Error: {e}"
)
return 0.0

Expand Down Expand Up @@ -151,7 +149,7 @@ def extract_intent_and_entities(

return event_name, confidence, entities
else:
logger.warning(f"Failed to parse intent end entities from '{user_input}'. ")
logger.warning(f"Failed to parse intent end entities from '{user_input}'.")
return None, 0.0, []

async def parse(
Expand Down
3 changes: 2 additions & 1 deletion rasa/core/jobs.py
@@ -1,4 +1,5 @@
import asyncio
import warnings
import logging

from apscheduler.schedulers.asyncio import AsyncIOScheduler
Expand All @@ -22,7 +23,7 @@ async def scheduler() -> AsyncIOScheduler:
__scheduler.start()
return __scheduler
except UnknownTimeZoneError:
logger.warning(
warnings.warn(
"apscheduler could not find a timezone and is "
"defaulting to utc. This is probably because "
"your system timezone is not set. "
Expand Down

0 comments on commit 1710d8a

Please sign in to comment.