示例#1
0
 def __init__(self):
     super().__init__(add_auth_header=True)
     self.BASE_URL = config.get(
         "service-persistence",
         "url",
         fallback="http://service-persistence-service:1555")
     self.id = config.get('skill',
                          'id',
                          fallback=config.get('skill', 'name'))
示例#2
0
    def wrapper(*args, **kwargs):  # NOSONAR
        response = callback(*args, **kwargs)

        http_requests_total.labels(job=config.get('skill', 'name'),
                                   version=config.get('skill', 'version'),
                                   method=request.method,
                                   uri=request.fullpath,
                                   status=response.status_code).inc()

        return response
示例#3
0
def get_service_name():
    """ Returns the service name, try to get from config or fallback to skill name.

    :return:
    """
    from skill_sdk.config import config
    return config.get('jaeger',
                      'service_name',
                      fallback=config.get('skill',
                                          'name',
                                          fallback='unnamed_service'))
示例#4
0
 def wrapper(*args, **kwargs):  # NOSONAR
     response = callback(*args, **kwargs)
     http_partner_request_count_total.labels(
         job=config.get('skill', 'name'),
         partner_name=partner_name,
         status=response.status_code).inc()
     return response
示例#5
0
def load_translations_from_server(translations: Dict[Union[bytes, str], l10n.Translations], reload: bool = False):
    """ Loads (or reloads) translations from the text services

    :param translations:
    :param reload:          reload flag, `False` - init call, `True` - reload call
    :return:
    """
    load = config.get("service-text", "load", fallback="startup")
    locale_class = MultiStringTranslation if load != 'delayed' else DelayedTranslation
    logger.debug("%s %s translations from text service.", 'Reloading' if reload else 'Loading', locale_class)

    service = TextService()

    # Get the list of supported locales
    locales = service.supported_locales()
    logger.debug("Available locales: %s", locales)

    for locale in locales:
        # Initialize translation object
        tr = locale_class(locale)

        # Load translations
        tr.reload()

        # Update the original
        translations.update({locale: tr})

    return translations
示例#6
0
def team_24_project_status_handler() -> Response:
    overdue_q = 'project = {project} AND assignee = "{user}" AND duedate < Now() and status in ("In Progress", "To Do")'
    jira_account = get_jira_account()
    users = get_project_users()
    overdue_msg = ""
    for user in users:
        overdue_q_user = overdue_q.format(project=config.get(
            'jira', 'project'),
                                          user=user)
        overdue_tasks = get_jira_tasks_with_due_dates(overdue_q_user,
                                                      jira_account)
        overdue_tasks_count = len(overdue_tasks)
        if overdue_tasks_count > 0:
            overdue_msg += user + _("ASSIGNED") + " "
            for idx, tpl in enumerate(overdue_tasks):
                overdue_msg += _("OVERDUE_TASK",
                                 task=tpl[0],
                                 days=(datetime.now() - parse(tpl[1])).days)
                overdue_msg += ", " if idx != overdue_tasks_count - 1 else "."

    if overdue_msg == "":
        overdue_msg = _("NO_OVERDUE_TASKS")

    response = Response(overdue_msg)
    return response
示例#7
0
def team_24_my_day_handler() -> Response:
    """ TEAM_24_MY_DAY handler

    :return:
    """
    meetings, meetings_count_msg = get_meetings()

    tasks, tasks_count_msg = get_in_progress_tasks()

    msg = _("MY_DAY",
            nickname=config.get('jira', 'nickname'),
            meetings_count=meetings_count_msg,
            tasks_count=tasks_count_msg)

    if meetings_count_msg != _("NONE"):
        msg += " " + _("MY_MEETINGS_INTRO")
        msg += " ".join(
            [m[1] + " " + _("AT") + " " + m[0] + "." for m in meetings])

    if tasks_count_msg != _("NONE"):
        msg += " " + _("MY_TASKS_INTRO")
        msg += format_enumeration(tasks)
        msg += "."

    response = Response(msg)
    return response
示例#8
0
def team_24_recommend_allocation_handler() -> Response:
    """ TEAM_24_RECOMMEND_ALLOCATION handler

    :return:
    """
    allocation_table = list()
    jira_account = get_jira_account()
    users = get_project_users_without_pm()

    q = "project = {project} AND assignee = '{user}' AND status IN ('To Do', 'In Progress') ORDER BY issuekey"
    total = 0
    for user in users:
        q_user = q.format(project=config.get('jira', 'project'), user=user)
        tasks, tasks_count_msg = get_jira_tasks(q_user, jira_account)
        allocation_table.append((user, len(tasks)))
        total += len(tasks)

    tasks, tasks_count_msg = get_backlog(jira_account)
    if tasks_count_msg == _("NONE"):
        return _("NO_BACKLOG")

    summary = allocate_backlog(tasks, allocation_table, total, users)
    msg = _("RECOMMENDER_INTRO")
    for usr, ts in summary.items():
        msg += _("RECOMMENDER_SG",
                 tasks=format_enumeration(ts)) if len(ts) == 1 else _(
                     "RECOMMENDER_PL",
                     tasks=format_enumeration(ts)) + _("TO") + " " + usr + ". "

    response = Response(msg)
    return response
示例#9
0
def get_done_tasks():
    msg_done_tasks = _("NO_DONE_TASKS")
    today = date.today().strftime("%Y-%m-%d")
    tomorrow = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    done_q = 'project = {project} AND status changed during ({today}, {tomorrow}) to Done'. \
        format(project=config.get('jira', 'project'), today=today, tomorrow=tomorrow)
    done_tasks, done_tasks_count_msg = get_jira_tasks(done_q)
    return done_tasks, done_tasks_count_msg, msg_done_tasks
示例#10
0
def team_24_project_status_handler() -> Response:
    """ TEAM_24_PROJECT_STATUS handler

    :return:
    """

    urgent_q = 'project = {project} AND status IN ("To Do") and priority in (Highest)'.\
        format(project=config.get('jira', 'project'))

    overdue_q = 'project = {project} AND duedate < Now() and status in ("In Progress", "To Do")'.\
        format(project=config.get('jira', 'project'))

    jira_account = get_jira_account()
    todo_tasks, todo_tasks_count_msg = get_jira_tasks(get_board_query("To Do"),
                                                      jira_account)
    inprogress_tasks, inprogress_tasks_count_msg = get_jira_tasks(
        get_board_query("In Progress"), jira_account)
    done_tasks, done_tasks_count_msg = get_jira_tasks(get_board_query("Done"),
                                                      jira_account)
    urgent_tasks, urgent_tasks_count_msg = get_jira_tasks(
        urgent_q, jira_account)
    overdue_tasks, overdue_tasks_count_msg = get_jira_tasks(
        overdue_q, jira_account)
    idle_users = get_idle_users(jira_account)

    msg = _("SPRINT_STATUS",
            project=config.get('jira', 'project'),
            todos=todo_tasks_count_msg,
            inprogress=inprogress_tasks_count_msg,
            done=done_tasks_count_msg)

    msg += " " + _("PROJECT_STATUS_INTRO",
                   project=config.get('jira', 'project'),
                   urgent_tasks=urgent_tasks_count_msg,
                   overdue_tasks=overdue_tasks_count_msg)

    if len(idle_users) > 0:
        verb = _("ARE")
        if len(idle_users) == 1:
            verb = _("IS")
        user_str = format_enumeration(idle_users)
        msg_idle = " " + _("IDLE_USERS", users=user_str, verb=verb)
        msg += msg_idle

    response = Response(msg)
    return response
示例#11
0
def get_urgent_tasks():
    urgent_q = 'project = {project} AND status IN ("To Do") and priority in (Highest)'. \
        format(project=config.get('jira', 'project'))
    account = get_jira_account()
    q_res = account.jql(urgent_q)
    tasks = [(t['fields']['summary'], t['fields']['assignee']['displayName'])
             for t in q_res['issues']]
    return tasks
示例#12
0
def setup_service():
    """ Handle text services load/reload depending on a configuration value in `skill.conf`

        config.get("service-text", "load", fallback="auto"):

            "auto":     the translations are loaded at skill startup and reloaded at TEXT_SERVICE_UPDATE_INTERVAL
                        a skill will start without translations if text services are unavailable
                        (this is a default behaviour)

            "delayed":  the skill will start without translations and loads the catalog when requested by CVI
                        (i.e on a first invocation, if the translations are empty)

            "startup":  the translations are loaded at skill startup and reloaded at TEXT_SERVICE_UPDATE_INTERVAL
                        a skill will raise a l10n.TranslationError exception if text services are not available

            ""

    :return:
    """
    load = config.get("service-text", "load", fallback="auto")

    if load == 'auto':
        logger.info('Text services load=[auto], spawning translation workers...')
        # Load translations from text service
        threading.Thread(target=load_translations_from_server, args=(l10n.translations,), daemon=True).start()
        # Leave translations reload worker
        threading.Thread(target=translation_reload_worker, args=(l10n.translations,), daemon=True).start()

    if load == 'delayed':
        logger.info('Text services load=[delayed], waiting for request...')
        # Initialize with local translations or empty DelayedTranslations
        default_locales = [_.strip() for _ in config.get("service-text", "locales", fallback="de,fr").split(',')]

        locales = l10n.get_locales() or default_locales
        l10n.translations = {locale: DelayedTranslation(locale, l10n.get_translation(locale)) for locale in locales}

    if load == 'startup':
        logger.info('Text services load=[startup], loading translations...')
        # Load translations from text service and exit if not available
        if not load_translations_from_server(l10n.translations):
            logger.error('Text services not available. Exiting...')
            raise l10n.TranslationError('No translations found.')
        # Leave translations reload worker
        else:
            threading.Thread(target=translation_reload_worker, args=(l10n.translations, ), daemon=True).start()
示例#13
0
def get_summarizer_model():
    model = config.get('ml', 'summarization_model')
    custom_config = AutoConfig.from_pretrained(model)
    custom_config.output_hidden_states = True
    custom_tokenizer = AutoTokenizer.from_pretrained(model)
    custom_model = AutoModel.from_pretrained(model, config=custom_config)
    model = Summarizer(custom_model=custom_model,
                       custom_tokenizer=custom_tokenizer)
    return model
示例#14
0
def _pre_check():
    """
    Startup probe:
        check if Rasa is answering at `server_url` and return "OK"

    """
    server_url = config.get('rasa', 'server_url', fallback=DEFAULT_SERVER_URL)
    try:
        return CircuitBreakerSession().get(server_url).ok and 'ok'
    except RequestException:
        return skill.HTTPResponse('Not ready', 503)
示例#15
0
def get_day_meetings(calendar):
    berlin = gettz('Europe/Berlin')
    tz_infos = {'CET': berlin, 'CEST': berlin}
    day = parse(config.get('office365', 'day'),
                dayfirst=True,
                tzinfos=tz_infos)
    next_day = day + timedelta(days=1)
    q = calendar.new_query('start').greater_equal(day)
    q.chain('and').on_attribute('end').less(next_day)
    return [("{:d}:{:02d}".format(m.start.hour, m.start.minute), m.subject)
            for m in calendar.get_events(query=q, include_recurring=True)]
示例#16
0
def get_idle_users(jira_account):
    users = get_project_users()
    idle_q = "project = {project} AND assignee = '{user}' AND status IN ('In Progress') ORDER BY issuekey"
    idle_users = []
    for user in users:
        idle_q_user = idle_q.format(project=config.get('jira', 'project'),
                                    user=user)
        in_progress_tasks, in_progress_tasks_count_msg = get_jira_tasks(
            idle_q_user, jira_account)
        if in_progress_tasks_count_msg == _("NONE"):
            idle_users.append(user)
    return idle_users
示例#17
0
def setup_service():
    """ Initialize global Jaeger tracer

    :param config:          Optional tracer configuration
    :return:
    """
    service_config = config.get("jaeger",
                                "config",
                                fallback={'propagation':
                                          'b3'})  # Backward compat Zipkin's B3
    logger.debug("Initializing tracer with %s", service_config)
    tracer_config = Config(config=service_config,
                           service_name=get_service_name(),
                           validate=True)
    tracer_config.initialize_tracer()
示例#18
0
    def __init__(self,
                 prefix=None,
                 hashing=True,
                 type_safe=False,
                 protocol: int = pickle.DEFAULT_PROTOCOL):
        """ Constructor

        :param prefix:      skill name
        :param hashing:     if True, the key will be hashed with sha512
        :param type_safe:   if True, more verbose key generated (including __qualname__ and type)
        """
        if not prefix:
            prefix = config.get('skill', 'name', fallback='unnamed_service')
        logger.debug(
            'Initializing FunctionCallKeyGenerator with hashing=%s and type_safe=%s',
            hashing, type_safe)
        self.prefix = prefix
        self.hashing = hashing
        self.type_safe = type_safe
        self.protocol = protocol
示例#19
0
def handle_user_answer(stt: Text) -> Response:
    """
    Send user response to Rasa server and speak out the output

    :param stt:     STT response
    :param zipcode: Device ZIP code
    :return:
    """
    LOGGER.debug('STT text: %s, intent: %s, session: %s', stt,
                 context.intent_name, context.session.session_id)

    server_url = config.get('rasa', 'server_url', fallback=DEFAULT_SERVER_URL)
    response = send_message_receive_block(server_url,
                                          context.session.session_id, stt)
    LOGGER.debug('Response from Rasa: %s', repr(response))

    text, card = format_bot_output(response)
    LOGGER.debug('Formatted output: %s, with card: %s', repr(text), repr(card))

    return ask_freetext(text, card=card)
示例#20
0
def get_board_query(state):
    return 'project = {project} AND status IN ("{state}") AND Sprint = "{sprint}" '. \
        format(project=config.get('jira', 'project'), sprint=config.get('jira', 'sprint'), state=state)
示例#21
0
 def timeout(self):
     return config.get("service-notification",
                       "timeout",
                       fallback=DEFAULT_SERVICE_TIMEOUT)
示例#22
0
def get_current_project(jira_account):
    my_project = next((prj for prj in jira_account.get_all_projects()
                       if prj['name'] == config.get('jira', 'project')), None)
    return my_project
示例#23
0
def get_project_users_without_pm():
    users = get_project_users()
    users.remove(config.get('jira', 'fullname'))
    return users
示例#24
0
 def decorated(*args, **kwargs):  # NOSONAR
     with http_requests_latency_seconds.labels(
             job=config.get('skill', 'name'),
             version=config.get('skill', 'version'),
             operation=self.operation_name).time():
         return func(*args, **kwargs)
示例#25
0
def get_backlog(jira_account):
    backlog_tasks_q = 'project = {project} AND sprint IS EMPTY OR sprint IN closedSprints()  AND sprint NOT IN (' \
                      'openSprints(), futureSprints()) AND status != Done '.format(project=config.get('jira',
                                                                                                      'project'))
    return get_jira_tasks(backlog_tasks_q, jira_account)
示例#26
0
 def timeout(self):
     return config.get("service-persistence",
                       "timeout",
                       fallback=DEFAULT_SERVICE_TIMEOUT)
示例#27
0
 def __init__(self):
     super().__init__(add_auth_header=True)
     self.BASE_URL = config.get(
         "service-notification",
         "url",
         fallback="http://service-notification-service:1555")
示例#28
0
 def provider(self):
     return config.get("service-notification",
                       "provider",
                       fallback=config.get('skill',
                                           'name',
                                           fallback='unnamed-skill'))
示例#29
0
def get_user_board_query(state, username):
    return 'project = {project} AND assignee = "{username}" AND status IN ("{state}") AND Sprint = "{sprint}" '. \
        format(project=config.get('jira', 'project'), username=username, sprint=config.get('jira', 'sprint'),
               state=state)
示例#30
0
def team_24_call_handler(username: str) -> Response:
    """ TEAM_24_COWORKER_STATUS handler

    :param username: str
    :return:
    """

    user = clarify_user(username)

    jira_account = get_jira_account()
    todo_tasks, todo_tasks_count_msg = get_jira_tasks(
        get_user_board_query("To Do", user), jira_account)
    inprogress_tasks, inprogress_tasks_count_msg = get_jira_tasks(
        get_user_board_query("In Progress", user), jira_account)
    done_tasks, done_tasks_count_msg = get_jira_tasks(
        get_user_board_query("Done", user), jira_account)

    msg = _("COWORKER_STATUS",
            username=username,
            todos=todo_tasks_count_msg,
            inprogress=inprogress_tasks_count_msg,
            done=done_tasks_count_msg)

    if inprogress_tasks_count_msg != _("NONE"):
        msg += " " + _("COWORKER_INPROGRESS",
                       username=user,
                       tasks=format_enumeration(inprogress_tasks))

    urgent_q = 'project = {project} AND assignee = "{username}" AND status IN ("To Do") and priority in (Highest)'. \
        format(project=config.get('jira', 'project'), username=user)

    overdue_q = 'project = {project} AND assignee = "{username}" AND duedate < Now() and status in ("In Progress", ' \
                '"To Do")'. \
        format(project=config.get('jira', 'project'), username=user)

    urgent_tasks, urgent_tasks_count_msg = get_jira_tasks(
        urgent_q, jira_account)
    if urgent_tasks_count_msg != _("NONE"):
        msg += _("COWORKER_URGENT",
                 username=user,
                 tasks=format_enumeration(urgent_tasks)) + "."

    overdue_tasks = get_jira_tasks_with_due_dates(overdue_q, jira_account)
    overdue_tasks_count = len(overdue_tasks)
    if overdue_tasks_count > 0:
        msg += _("COWORKER_OVERDUE", username=user)
        for idx, tpl in enumerate(overdue_tasks):
            msg += _("OVERDUE_TASK",
                     task=tpl[0],
                     days=(datetime.now() - parse(tpl[1])).days)
            msg += ", " if idx != overdue_tasks_count - 1 else "."

    no_tasks_q = "project = {project} AND assignee = '{user}' AND status IN ('In Progress', 'To Do') ORDER BY issuekey".format(
        project=config.get('jira', 'project'), user=user)
    tasks, tasks_count_msg = get_jira_tasks(no_tasks_q, jira_account)
    if len(tasks) == 0:
        msg += " " + _("COWORKER_EMPTY")
    else:
        idle_tasks_q = "project = {project} AND assignee = '{user}' AND status IN ('In Progress') ORDER BY " \
                       "issuekey".format(project=config.get('jira', 'project'), user=user)
        idle_tasks, idle_tasks_count_msg = get_jira_tasks(
            idle_tasks_q, jira_account)
        if len(idle_tasks) == 0:
            msg += " " + _("COWORKER_IDLE")

    response = Response(msg)
    return response