Example #1
0
def __get_bubble_from_support_step(arg_uid_user: int, uid_system: int, db_user: User, lang: str) \
        -> Optional[List[list]]:
    """
    Creates bubbles for the support-keyword for an statement.

    :param arg_uid_user: User.uid
    :param uid_system: Argument.uid
    :param db_user: User
    :param lang: Language.ui_locales
    :return: [dict()]
    """
    db_arg_user = DBDiscussionSession.query(Argument).get(arg_uid_user)
    db_arg_system = DBDiscussionSession.query(Argument).get(uid_system)

    if not db_arg_user or not db_arg_system:
        return None

    user_text = get_text_for_argument_uid(arg_uid_user)
    bubble_user = create_speechbubble_dict(BubbleTypes.USER, content=user_text, omit_bubble_url=True,
                                           argument_uid=arg_uid_user, is_supportive=db_arg_user.is_supportive,
                                           db_user=db_user, lang=lang)

    argument_text = get_text_for_argument_uid(uid_system, colored_position=True, with_html_tag=True, attack_type='jump')
    offset = len('</' + tag_type + '>') if argument_text.endswith('</' + tag_type + '>') else 1

    while argument_text[:-offset].endswith(('.', '?', '!')):
        argument_text = argument_text[:-offset - 1] + argument_text[-offset:]

    text = get_text_for_support(db_arg_system, argument_text, db_user.nickname, Translator(lang))
    db_other_author = DBDiscussionSession.query(User).get(db_arg_system.author_uid)
    bubble_system = create_speechbubble_dict(BubbleTypes.SYSTEM, content=text, omit_bubble_url=True, lang=lang,
                                             other_author=db_other_author)

    return [bubble_user, bubble_system]
Example #2
0
    def get_dict_for_supporting_each_other(self, uid_system_arg, uid_user_arg,
                                           nickname) -> dict:
        """
        Returns the dictionary during the supporting step

        :param uid_system_arg: Argument.uid
        :param uid_user_arg: Argument.uid
        :param nickname: User.nickname
        :return: dict()
        """
        logger('DictionaryHelper', str(uid_system_arg))
        _tn = Translator(self.lang)
        bubbles_array = history_helper.create_bubbles_from_history(
            self.history, nickname, self.lang, self.slug)
        db_arg_system = DBDiscussionSession.query(Argument).get(uid_system_arg)
        db_arg_user = DBDiscussionSession.query(Argument).get(uid_user_arg)

        argument_text = get_text_for_argument_uid(uid_system_arg,
                                                  colored_position=True,
                                                  with_html_tag=True,
                                                  attack_type='jump')

        offset = len('</' + tag_type +
                     '>') if argument_text.endswith('</' + tag_type +
                                                    '>') else 1
        while argument_text[:-offset].endswith(('.', '?', '!')):
            argument_text = argument_text[:-offset -
                                          1] + argument_text[-offset:]

        sys_text = get_text_for_support(db_arg_system, argument_text, nickname,
                                        _tn)

        self.__append_now_bubble(bubbles_array)

        user_text = get_text_for_argument_uid(uid_user_arg, nickname=nickname)
        bubble_user = create_speechbubble_dict(
            BubbleTypes.USER,
            content=user_text,
            omit_bubble_url=True,
            argument_uid=uid_user_arg,
            is_supportive=db_arg_user.is_supportive,
            lang=self.lang,
            nickname=nickname)
        bubbles_array.append(bubble_user)

        bubble = create_speechbubble_dict(
            BubbleTypes.SYSTEM,
            uid='question-bubble-{}'.format(uid_system_arg),
            content=sys_text,
            omit_bubble_url=True,
            lang=self.lang)
        bubbles_array.append(bubble)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': '',
            'save_statement_url': '',
            'mode': '',
            'broke_limit': self.broke_limit
        }
Example #3
0
def get_user_with_same_opinion_for_argument(argument_uid, db_user, lang, main_page):
    """
    Returns nested dictionary with all kinds of information about the votes of the argument.

    :param argument_uid: Argument.uid
    :param db_user: User
    :param lang: language
    :param main_page: url
    :return: {'users':[{nickname1.avatar_url, nickname1.vote_timestamp}*]}
    """
    try:
        text = get_text_for_argument_uid(argument_uid, 'de')
        LOG.debug("Argument %s: %s", argument_uid, text)
        if not text:
            return {'uid': None, 'text': None, 'message': None, 'users': None, 'seen_by': None}
    except TypeError:
        return {'uid': None, 'text': None, 'message': None, 'users': None, 'seen_by': None}

    opinions = dict()
    all_users = []
    _t = Translator(lang)
    text = get_text_for_argument_uid(argument_uid, lang)
    title = _t.get(_.reactionFor) + ': ' + start_with_capital(text)

    db_argument = DBDiscussionSession.query(Argument).get(argument_uid)
    if not db_argument:
        opinions = {'uid': None, 'text': None, 'message': None, 'users': None, 'seen_by': None}

    opinions['uid'] = str(argument_uid)
    text = get_text_for_argument_uid(argument_uid, lang)
    opinions['text'] = start_with_capital(text)

    db_clicks = DBDiscussionSession.query(ClickedArgument).filter(ClickedArgument.argument_uid == argument_uid,
                                                                  ClickedArgument.is_up_vote == True,
                                                                  ClickedArgument.is_valid == True,
                                                                  ClickedArgument.author_uid != db_user.uid).all()

    for vote in db_clicks:
        voted_user = DBDiscussionSession.query(User).get(vote.author_uid)
        users_dict = create_users_dict(voted_user, vote.timestamp, main_page, lang)
        all_users.append(users_dict)
    opinions['users'] = all_users
    opinions['message'] = __get_text_for_clickcount(len(db_clicks), db_user.uid, _t)

    db_seen_by = DBDiscussionSession.query(SeenArgument).filter_by(argument_uid=int(argument_uid)).all()
    opinions['seen_by'] = len(db_seen_by) if db_seen_by else 0

    return {'opinions': opinions, 'title': start_with_capital(title)}
Example #4
0
def __get_base_subpage_dict(review_type, db_reviews, already_seen, first_time,
                            db_user, already_reviewed):
    extra_info = ''
    if not db_reviews:
        already_seen = list()
        extra_info = 'already_seen' if not first_time else ''
        db_reviews = DBDiscussionSession.query(review_type).filter(
            review_type.is_executed == False,
            review_type.detector_uid != db_user.uid)
        if len(already_reviewed) > 0:
            db_reviews = db_reviews.filter(
                ~review_type.uid.in_(already_reviewed))
        db_reviews = db_reviews.all()

    if not db_reviews:
        return None, None, None, None, None

    rnd_review = db_reviews[random.randint(0, len(db_reviews) - 1)]
    if rnd_review.statement_uid is None:
        db_argument = DBDiscussionSession.query(Argument).get(
            rnd_review.argument_uid)
        text = get_text_for_argument_uid(db_argument.uid)
        issue = DBDiscussionSession.query(Issue).get(
            db_argument.issue_uid).title
    else:
        db_statement = DBDiscussionSession.query(Statement).get(
            rnd_review.statement_uid)
        text = db_statement.get_text()
        issue = DBDiscussionSession.query(Issue).get(
            db_statement.issue_uid).title

    return rnd_review, already_seen, extra_info, text, issue
Example #5
0
def __get_bubble_from_dont_know_step(step: str, db_user: User, lang: str) -> List[dict]:
    """
    Creates bubbles for the don't-know-reaction for a statement.

    :param step: String
    :param db_user: User
    :param lang: ui_locales
    :return: [dict()]
    """
    steps = step.split('/')
    uid = int(steps[1])

    text = get_text_for_argument_uid(uid, rearrange_intro=True, attack_type='dont_know', with_html_tag=False,
                                     start_with_intro=True)
    db_argument = DBDiscussionSession.query(Argument).get(uid)
    if not db_argument:
        text = ''

    from dbas.strings.text_generator import get_name_link_of_arguments_author
    _tn = Translator(lang)

    data = get_name_link_of_arguments_author(db_argument, db_user.nickname, False)
    if data['is_valid']:
        intro = data['link'] + ' ' + _tn.get(_.thinksThat)
    else:
        intro = _tn.get(_.otherParticipantsThinkThat)
    sys_text = intro + ' ' + start_with_small(text) + '. '
    sys_text += '<br><br>' + _tn.get(_.whatDoYouThinkAboutThat) + '?'
    sys_bubble = create_speechbubble_dict(BubbleTypes.SYSTEM, content=sys_text, db_user=db_user,
                                          other_author=data['user'])

    text = _tn.get(_.showMeAnArgumentFor) + (' ' if lang == 'de' else ': ') + get_text_for_conclusion(db_argument)
    user_bubble = create_speechbubble_dict(BubbleTypes.USER, content=text, db_user=db_user)

    return [user_bubble, sys_bubble]
Example #6
0
    def get_dict_for_dont_know_reaction(self, uid, nickname) -> dict:
        """
        Prepares the discussion dict with all bubbles for the third step,
        where an supportive argument will be presented.

        :param uid: Argument.uid
        :param nickname:
        :return: dict()
        """
        LOG.debug("Entering get_dict_for_dont_know_reaction")
        _tn = Translator(self.lang)
        bubbles_array = history_handler.create_bubbles(self.history,
                                                       self.nickname,
                                                       self.lang, self.slug)
        add_premise_text = ''
        save_statement_url = 'set_new_start_statement'
        gender = ''
        b = '<' + tag_type + '>'
        e = '</' + tag_type + '>'
        statement_list = list()

        if int(uid) != 0:
            text = get_text_for_argument_uid(uid,
                                             rearrange_intro=True,
                                             attack_type='dont_know',
                                             with_html_tag=True,
                                             start_with_intro=True)
            db_argument = DBDiscussionSession.query(Argument).get(uid)
            if not db_argument:
                text = ''
            data = get_name_link_of_arguments_author(db_argument, nickname)
            gender = data['gender']
            if data['is_valid']:
                intro = data['link'] + ' ' + b + _tn.get(_.thinksThat) + e
            else:
                intro = b + _tn.get(_.otherParticipantsThinkThat) + e
            sys_text = intro + ' ' + start_with_small(text) + '. '
            sys_text += '<br><br> ' + b + _tn.get(
                _.whatDoYouThinkAboutThat) + '?' + e
            bubble_sys = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                                  is_markable=True,
                                                  uid=uid,
                                                  content=sys_text,
                                                  other_author=data['user'])
            if not bubbles_already_last_in_list(bubbles_array, bubble_sys):
                bubbles_array.append(bubble_sys)

            # add statements of discussion to report them
            statement_list = self.__get_all_statement_texts_by_argument(
                db_argument)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': add_premise_text,
            'save_statement_url': save_statement_url,
            'mode': '',
            'extras': statement_list,
            'gender': gender,
            'broke_limit': self.broke_limit
        }
Example #7
0
    def __get_dict_for_argumentation_end(self, argument_uid: int,
                                         user_changed_opinion: bool,
                                         db_user: User) -> dict:
        """
        Returns a special dict() when the discussion ends during an argumentation

        :param argument_uid: Argument.uid
        :param user_changed_opinion:  Boolean
        :param db_user: User
        :return: String, String, String
        """
        nickname = db_user.nickname if db_user and db_user.nickname != nick_of_anonymous_user else None
        _tn = Translator(self.lang)
        text = get_text_for_argument_uid(
            argument_uid,
            user_changed_opinion=user_changed_opinion,
            minimize_on_undercut=True,
            nickname=nickname)
        user_text = start_with_capital(text)
        sys_text = _tn.get(_.otherParticipantsDontHaveCounterForThat) + '.'
        trophy = '<i class="fa fa-trophy" aria-hidden="true"></i>'
        mid_text = '{} {} {} <br>{}'.format(
            trophy, _tn.get(_.congratulation), trophy,
            _tn.get(_.discussionCongratulationEnd))

        if nickname is not None:
            mid_text += _tn.get(_.discussionEndLinkTextWithQueueLoggedIn)
        else:
            mid_text += _tn.get(_.discussionEndLinkTextWithQueueNotLoggedIn)

        return {'user': user_text, 'mid': mid_text, 'sys': sys_text}
Example #8
0
def get_marked_elements_of(db_user: User, is_argument: bool, lang: str):
    """
    Get all marked arguments/statements of the user

    :param db_user: User
    :param is_argument: Boolean
    :param lang: uid_locales
    :return: [{},...]
    """
    return_array = []

    if is_argument:
        db_votes = DBDiscussionSession.query(MarkedArgument).filter_by(author_uid=db_user.uid).all()
    else:
        db_votes = DBDiscussionSession.query(MarkedStatement).filter_by(author_uid=db_user.uid).all()

    for vote in db_votes:
        vote_dict = dict()
        vote_dict['uid'] = str(vote.uid)
        vote_dict['timestamp'] = sql_timestamp_pretty_print(vote.timestamp, lang)
        if is_argument:
            vote_dict['argument_uid'] = str(vote.argument_uid)
            vote_dict['content'] = get_text_for_argument_uid(vote.argument_uid, lang)
        else:
            vote_dict['statement_uid'] = str(vote.statement_uid)
            vote_dict['content'] = get_text_for_statement_uid(vote.statement_uid)
        return_array.append(vote_dict)

    return return_array
Example #9
0
    def get_dict_for_jump(self, uid) -> dict:
        """
        Prepares the discussion dict with all bubbles for the jump step

        :param uid: Argument.uid
        :return: dict()
        """
        logger('DictionaryHelper', 'argument ' + str(uid))
        _tn = Translator(self.lang)
        argument_text = get_text_for_argument_uid(uid,
                                                  colored_position=True,
                                                  with_html_tag=True,
                                                  attack_type='jump')
        bubbles_array = history_helper.create_bubbles_from_history(
            self.history, self.nickname, self.lang, self.slug)

        coming_from_jump = False
        if self.history:
            splitted_history = self.history.split('-')
            coming_from_jump = '/jump' in self.history[:-1] if len(
                splitted_history) > 0 else False
        intro = (_tn.get(_.canYouBeMorePrecise) +
                 '<br><br>') if coming_from_jump else ''

        db_argument = DBDiscussionSession.query(Argument).get(uid)
        if db_argument.conclusion_uid is not None:
            intro += _tn.get(_.whatDoYouThinkArgument).strip() + ': '
        else:
            bind = ', ' if self.lang == 'de' else ' '
            intro += _tn.get(_.whatDoYouThinkAboutThat) + bind + _tn.get(
                _.that) + ' '

        offset = len('</' + tag_type +
                     '>') if argument_text.endswith('</' + tag_type +
                                                    '>') else 1
        while argument_text[:-offset].endswith(('.', '?', '!')):
            argument_text = argument_text[:-offset -
                                          1] + argument_text[-offset:]

        text = intro + argument_text + '?'
        bubble = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                          content=text,
                                          omit_bubble_url=True,
                                          lang=self.lang,
                                          uid='question-bubble-{}'.format(uid),
                                          is_markable=True)
        bubbles_array.append(bubble)

        # add statements of discussion to report them
        statement_list = self.__get_all_statement_texts_by_argument(
            db_argument)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': '',
            'save_statement_url': '',
            'mode': '',
            'extras': statement_list,
            'broke_limit': self.broke_limit
        }
Example #10
0
def get_clicked_elements_of(db_user: User, is_argument: bool, lang: str) -> list:
    """
    Returns array with all clicked elements by the user. Each element is a dict with information like the uid,
    timestamp, up_Vote, validity, the clicked uid and content of the clicked element.

    :param db_user: User
    :param is_argument: Boolean
    :param lang: ui_locales
    :return: [{},...]
    """
    return_array = []
    db_type = ClickedArgument if is_argument else ClickedStatement
    db_clicks = DBDiscussionSession.query(db_type).filter_by(author_uid=db_user.uid).all()

    for click in db_clicks:
        click_dict = dict()
        click_dict['uid'] = click.uid
        click_dict['timestamp'] = sql_timestamp_pretty_print(click.timestamp, lang)
        click_dict['is_up_vote'] = click.is_up_vote
        click_dict['is_valid'] = click.is_valid
        if is_argument:
            click_dict['argument_uid'] = click.argument_uid
            click_dict['content'] = get_text_for_argument_uid(click.argument_uid, lang)
        else:
            click_dict['statement_uid'] = click.statement_uid
            click_dict['content'] = get_text_for_statement_uid(click.statement_uid)
        return_array.append(click_dict)

    return return_array
Example #11
0
def get_text_for_argument(request):
    statement = int(request.matchdict["statement_uid"])
    args = get_all_arguments_by_statement(statement)
    return list(
        map(
            lambda arg: {
                "uid": arg.uid,
                "text": get_text_for_argument_uid(arg.uid)
            }, args))
Example #12
0
    def get_dict_for_choosing(self, uid, is_uid_argument,
                              is_supportive) -> dict:
        """
        Prepares the discussion dict with all bubbles for the choosing an premise,
        when the user inserted more than one new premise.

        :param uid: Argument.uid
        :param is_uid_argument: Boolean
        :param is_supportive: Boolean
        :return:
        """
        _tn = Translator(self.lang)
        bubbles_array = history_handler.create_bubbles(self.history,
                                                       self.nickname,
                                                       self.lang, self.slug)
        add_premise_text = ''
        save_statement_url = 'set_new_start_statement'

        LOG.debug("Choosing dictionary for bubbles.")
        a = _tn.get(_.soYouEnteredMultipleReasons)
        if is_uid_argument:
            c = get_text_for_argument_uid(uid)
        else:
            statement = DBDiscussionSession.query(Statement).get(uid)
            c = statement.get_text()

        if is_supportive:
            if is_uid_argument:
                b = _tn.get(_.whatIsYourMostImportantReasonForArgument)
            else:
                b = _tn.get(_.whatIsYourMostImportantReasonForStatement)
        else:
            if is_uid_argument:
                b = _tn.get(_.whatIsYourMostImportantReasonAgainstArgument)
            else:
                b = _tn.get(_.whatIsYourMostImportantReasonAgainstStatement)
        b = b.replace('{}', '')

        text = '{}. {}: {}?<br>{}...'.format(a, b, c, _tn.get(_.because))

        self.__append_now_bubble(bubbles_array)

        question_bubble = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                                   uid='question-bubble',
                                                   content=text,
                                                   omit_bubble_url=True,
                                                   lang=self.lang)
        if not bubbles_already_last_in_list(bubbles_array, question_bubble):
            bubbles_array.append(question_bubble)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': add_premise_text,
            'save_statement_url': save_statement_url,
            'mode': '',
            'broke_limit': self.broke_limit
        }
Example #13
0
def get_base_subpage_dict(review_type, db_reviews, already_seen, first_time,
                          db_user, already_reviewed):
    """

    :param review_type:
    :param db_reviews:
    :param already_seen:
    :param first_time:
    :param db_user:
    :param already_reviewed:
    :return:
    """
    extra_info = ''
    if not db_reviews:
        already_seen = list()
        extra_info = 'already_seen' if not first_time else ''
        db_reviews = DBDiscussionSession.query(review_type).filter(
            review_type.is_executed == False,
            review_type.detector_uid != db_user.uid)
        if len(already_reviewed) > 0:
            db_reviews = db_reviews.filter(
                ~review_type.uid.in_(already_reviewed))
        db_reviews = db_reviews.all()

    if not db_reviews:
        return {
            'rnd_review': None,
            'already_seen_reviews': None,
            'extra_info': None,
            'text': None,
            'issue_titles': None,
        }

    rnd_review = random.choice(db_reviews)
    if rnd_review.statement_uid is None:
        db_argument = DBDiscussionSession.query(Argument).get(
            rnd_review.argument_uid)
        text = get_text_for_argument_uid(db_argument.uid)
        issue_titles = [
            DBDiscussionSession.query(Issue).get(db_argument.issue_uid).title
        ]
    else:
        db_statement = DBDiscussionSession.query(Statement).get(
            rnd_review.statement_uid)
        text = db_statement.get_text()
        issue_titles = [
            issue.title for issue in get_issues_for_statement_uids(
                [rnd_review.statement_uid])
        ]

    return {
        'rnd_review': rnd_review,
        'already_seen_reviews': already_seen,
        'extra_info': extra_info,
        'text': text,
        'issue_titles': issue_titles
    }
Example #14
0
    def get_text_of_element(self, db_review: ReviewDelete) -> str:
        """
        Returns full text of the given element

        :param db_review: current review element
        :return:
        """
        if db_review.statement_uid is None:
            return get_text_for_argument_uid(db_review.argument_uid)
        else:
            return DBDiscussionSession.query(Statement).get(db_review.statement_uid).get_text()
Example #15
0
def get_all_infos_about_argument(db_argument: Argument, main_page, db_user,
                                 lang) -> dict:
    """
    Returns bunch of information about the given argument

    :param db_argument: The argument
    :param main_page: url of the application
    :param db_user: User
    :param lang: Language
    :rtype: dict
    :return: dictionary with many information or an error
    """
    _t = Translator(lang.ui_locales)

    return_dict = dict()
    db_votes = DBDiscussionSession.query(ClickedArgument).filter(
        ClickedArgument.argument_uid == db_argument.uid,
        ClickedArgument.is_valid == True,
        ClickedStatement.is_up_vote == True).all()

    db_author = DBDiscussionSession.query(User).get(db_argument.author_uid)
    return_dict['vote_count'] = str(len(db_votes))
    return_dict['author'] = db_author.global_nickname
    return_dict['author_url'] = main_page + '/user/' + str(db_author.uid)
    return_dict['gravatar'] = get_profile_picture(db_author)
    return_dict['timestamp'] = sql_timestamp_pretty_print(
        db_argument.timestamp, db_argument.lang)
    text = get_text_for_argument_uid(db_argument.uid)
    return_dict['text'] = start_with_capital(text)

    supporters = []
    gravatars = dict()
    public_page = dict()
    for vote in db_votes:
        db_author = DBDiscussionSession.query(User).get(vote.author_uid)
        name = db_author.global_nickname
        if db_user.nickname == db_author.nickname:
            name += ' (' + _t.get(_.itsYou) + ')'
        supporters.append(name)
        gravatars[name] = get_profile_picture(db_author)
        public_page[name] = main_page + '/user/' + str(db_author.uid)

    return_dict['supporter'] = supporters
    return_dict['gravatars'] = gravatars
    return_dict['public_page'] = public_page

    return return_dict
Example #16
0
def _marked_element_to_dict(marked_object: Union[MarkedArgument,
                                                 MarkedStatement],
                            lang: str) -> Dict[str, Any]:
    """
    Transform a given MarkedArgument or MarkedStatement object into a dictionary representation.

    :param marked_object: The MarkedArgument or MarkedStatement which shall be transformed.
    :param lang: The language in which the answer shall be returned.
    :return: A dictionary representing a MarkedArgument / MarkedStatement.
    """
    dict_representation = marked_object.to_dict()
    if type(marked_object) is MarkedArgument:
        return dict_representation.update({
            'content':
            get_text_for_argument_uid(marked_object.argument_uid, lang)
        })
    else:
        return dict_representation.update(
            {'content': marked_object.statement.get_text()})
Example #17
0
def __create_argument_by_raw_input(db_user: User, premisegroup: [str], db_conclusion: Statement, is_supportive,
                                   db_issue: Issue) \
        -> Tuple[Union[Argument, None], List[int]]:
    """
    Consumes the input to create a new argument

    :param db_user: User
    :param premisegroup: String
    :param db_conclusion: Statement
    :param is_supportive: Boolean
    :param db_issue: Issue
    :return:
    """
    logger('StatementsHelper',
           'main with premisegroup {} as premisegroup, conclusion {} in issue {}'.format(premisegroup,
                                                                                         db_conclusion.uid,
                                                                                         db_issue.uid))

    new_statements = []

    for text in premisegroup:
        statement = insert_as_statement(text, db_user, db_issue)
        new_statements.append(statement)

    # second, set the new statements as premisegroup
    new_premisegroup = set_statements_as_new_premisegroup(new_statements, db_user, db_issue)
    logger('StatementsHelper', 'new pgroup ' + str(new_premisegroup.uid))

    # third, insert the argument
    new_argument = __create_argument_by_uids(db_user, new_premisegroup.uid, db_conclusion.uid, None, is_supportive,
                                             db_issue)
    transaction.commit()

    if new_argument:
        _tn = Translator(db_issue.lang)
        _um = UrlManager(db_issue.slug)
        append_action_to_issue_rss(db_issue=db_issue, db_author=db_user, title=_tn.get(_.argumentAdded),
                                   description='...' + get_text_for_argument_uid(new_argument.uid,
                                                                                 anonymous_style=True) + '...',
                                   url=_um.get_url_for_justifying_statement(new_argument.uid, Attitudes.DONT_KNOW))

    return new_argument, [s.uid for s in new_statements]
Example #18
0
def _clicked_argument_to_dict(clicked_argument: ClickedArgument,
                              lang: str) -> Dict[str, Any]:
    """
    Transforms a single ClickedArgument object into a dictionary representation of itself.

    :param clicked_argument: The object that shall be transformed.
    :param lang: Language that the answer shall be delivered in.
    :return: A dictionary representing `clicked_argument`.
    """

    return {
        'uid': clicked_argument.uid,
        'timestamp': sql_timestamp_pretty_print(clicked_argument.timestamp,
                                                lang),
        'is_up_vote': clicked_argument.is_up_vote,
        'is_valid': clicked_argument.is_valid,
        'argument_uid': clicked_argument.argument_uid,
        'content': get_text_for_argument_uid(clicked_argument.argument_uid,
                                             lang)
    }
Example #19
0
    def test_get_text_for_argument_uid(self):
        s47 = 'we should close public swimming pools because our swimming pools are very old and it would take a major investment to repair them'
        s48 = 'Other participants said that we should close public swimming pools because our swimming pools are very old and it would take a major investment to repair them. You did not agree with this because schools need the swimming pools for their sports lessons.'
        s49 = 'we should close public swimming pools does not hold, because the rate of non-swimmers is too high'

        self.assertTrue(lib.get_text_for_argument_uid(47), s47)
        self.assertTrue(lib.get_text_for_argument_uid(48), s48)
        self.assertTrue(lib.get_text_for_argument_uid(49), s49)

        for attack in ['', None, 'jump']:
            self.assertTrue(
                lib.get_text_for_argument_uid(47, attack_type=attack), s47)
            self.assertTrue(
                lib.get_text_for_argument_uid(48, attack_type=attack), s48)
            self.assertTrue(
                lib.get_text_for_argument_uid(49, attack_type=attack), s49)

        self.assertTrue(lib.get_text_for_argument_uid(47, with_html_tag=True),
                        s47)
        self.assertTrue(lib.get_text_for_argument_uid(48, with_html_tag=True),
                        s48)
        self.assertTrue(lib.get_text_for_argument_uid(49, with_html_tag=True),
                        s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, start_with_intro=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, start_with_intro=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, start_with_intro=True), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, first_arg_by_user=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, first_arg_by_user=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, first_arg_by_user=True), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, is_users_opinion=False), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, is_users_opinion=False), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, is_users_opinion=False), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, rearrange_intro=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, rearrange_intro=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, rearrange_intro=True), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, support_counter_argument=True),
            s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, support_counter_argument=True),
            s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, support_counter_argument=True),
            s49)

        self.assertTrue(lib.get_text_for_argument_uid(47, nickname='Dieter'),
                        s47)
        self.assertTrue(lib.get_text_for_argument_uid(48, nickname='Dieter'),
                        s48)
        self.assertTrue(lib.get_text_for_argument_uid(49, nickname='Dieter'),
                        s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, minimize_on_undercut=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, minimize_on_undercut=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, minimize_on_undercut=True), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, colored_position=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, colored_position=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, colored_position=True), s49)

        self.assertTrue(
            lib.get_text_for_argument_uid(47, user_changed_opinion=True), s47)
        self.assertTrue(
            lib.get_text_for_argument_uid(48, user_changed_opinion=True), s48)
        self.assertTrue(
            lib.get_text_for_argument_uid(49, user_changed_opinion=True), s49)
Example #20
0
def get_bubble_from_reaction_step(step, db_user, lang, splitted_history, url, color_steps=False):
    """
    Creates bubbles for the reaction-keyword.

    :param step: String
    :param db_user: User
    :param lang: ui_locales
    :param splitted_history: [String].uid
    :param url: String
    :param color_steps: Boolean
    :return: [dict()]
    """
    logger('history_handler', 'def: {}, {}'.format(step, splitted_history))
    steps = step.split('/')
    uid = int(steps[1])

    attack = Relations.SUPPORT
    if 'reaction' in step:
        additional_uid = int(steps[3])
        attack = relation_mapper[steps[2]]
    else:
        additional_uid = int(steps[2])

    if not check_reaction(uid, additional_uid, attack):
        logger('history_handler', 'wrong reaction')
        return None

    is_supportive = DBDiscussionSession.query(Argument).get(uid).is_supportive
    last_relation = splitted_history[-1].split('/')[2] if len(splitted_history) > 1 else ''

    user_changed_opinion = len(splitted_history) > 1 and '/undercut/' in splitted_history[-2]
    support_counter_argument = False

    if step in splitted_history:
        index = splitted_history.index(step)
        try:
            support_counter_argument = 'reaction' in splitted_history[index - 1]
        except IndexError:
            support_counter_argument = False

    color_steps = color_steps and attack != Relations.SUPPORT  # special case for the support round
    current_arg = get_text_for_argument_uid(uid, user_changed_opinion=user_changed_opinion,
                                            support_counter_argument=support_counter_argument,
                                            colored_position=color_steps, nickname=db_user.nickname,
                                            with_html_tag=color_steps)

    db_argument = DBDiscussionSession.query(Argument).get(uid)
    db_confrontation = DBDiscussionSession.query(Argument).get(additional_uid)
    reply_for_argument = True
    if db_argument.conclusion_uid is not None:
        db_statement = DBDiscussionSession.query(Statement).get(db_argument.conclusion_uid)
        reply_for_argument = not (db_statement and db_statement.is_position)

    premise = db_argument.get_premisegroup_text()
    conclusion = get_text_for_conclusion(db_argument)
    sys_conclusion = get_text_for_conclusion(db_confrontation)
    confr = db_confrontation.get_premisegroup_text()
    user_is_attacking = not db_argument.is_supportive

    if lang != 'de':
        current_arg = current_arg[0:1].upper() + current_arg[1:]
        if current_arg.startswith('<'):
            pos = current_arg.index('>')
            current_arg = current_arg[0:pos] + current_arg[pos:pos + 1].upper() + current_arg[pos + 1:]

    premise = premise[0:1].lower() + premise[1:]

    _tn = Translator(lang)
    user_text = (_tn.get(_.otherParticipantsConvincedYouThat) + ': ') if last_relation == Relations.SUPPORT else ''
    user_text += '<{}>{}</{}>'.format(tag_type, current_arg if current_arg != '' else premise, tag_type)

    sys_text, tmp = get_text_for_confrontation(lang, db_user.nickname, premise, conclusion, sys_conclusion,
                                               is_supportive, attack, confr, reply_for_argument, user_is_attacking,
                                               db_argument, db_confrontation, color_html=False)

    bubble_user = create_speechbubble_dict(BubbleTypes.USER, content=user_text, omit_bubble_url=False, argument_uid=uid,
                                           is_supportive=is_supportive, nickname=db_user.nickname, lang=lang, bubble_url=url)
    db_tmp = DBDiscussionSession.query(User).get(db_confrontation.author_uid)
    if not attack:
        bubble_syst = create_speechbubble_dict(BubbleTypes.SYSTEM, content=sys_text, omit_bubble_url=True,
                                               nickname=db_user.nickname, lang=lang, other_author=db_tmp)
    else:
        bubble_syst = create_speechbubble_dict(BubbleTypes.SYSTEM, uid='question-bubble-' + str(additional_uid),
                                               content=sys_text, omit_bubble_url=True, nickname=db_user.nickname,
                                               lang=lang, other_author=db_tmp)
    return [bubble_user, bubble_syst]
Example #21
0
def __get_executed_review_element_of(table, main_page, review, last_review_type, translator, is_executed):
    """

    :param table: Shortcut for the table
    :param main_page: Main page of D-BAS
    :param review: Element
    :param last_review_type: Type of the last reviewer of the table
    :param translator: current ui_locales
    :param is_executed
    :return: Element
    """

    length = 35
    # getting text
    if table == 'duplicates':
        full_text = get_text_for_statement_uid(review.duplicate_statement_uid)
    elif table in ['splits', 'merges']:
        full_text = get_text_for_premisegroup_uid(review.premisegroup_uid)
    elif review.statement_uid is None:
        full_text = get_text_for_argument_uid(review.argument_uid)
    else:
        full_text = get_text_for_statement_uid(review.statement_uid)

    # pretty print
    intro = translator.get(_.otherUsersSaidThat) + ' '
    if full_text.startswith(intro):
        short_text = full_text[len(intro):len(intro) + 1].upper() + full_text[len(intro) + 1:len(intro) + length]
    else:
        short_text = full_text[0:length]

    short_text += '...' if len(full_text) > length else '.'
    short_text = '<span class="text-primary">' + short_text + '</span>'

    all_votes = DBDiscussionSession.query(last_review_type).filter_by(review_uid=review.uid)
    is_okay = False if table == 'optimizations' else True
    if table is 'merges':
        pro_votes = all_votes.filter_by(should_merge=is_okay).all()
        con_votes = all_votes.filter(last_review_type.should_merge != is_okay).all()
    elif table is 'splits':
        pro_votes = all_votes.filter_by(should_split=is_okay).all()
        con_votes = all_votes.filter(last_review_type.should_split != is_okay).all()
    else:
        pro_votes = all_votes.filter_by(is_okay=is_okay).all()
        con_votes = all_votes.filter(last_review_type.is_okay != is_okay).all()

    # getting the users which have voted
    pro_list = [__get_user_dict_for_review(pro.reviewer_uid, main_page) for pro in pro_votes]
    con_list = [__get_user_dict_for_review(con.reviewer_uid, main_page) for con in con_votes]

    if table == 'duplicates':
        # switch it, because contra is: it should not be there!
        tmp_list = pro_list
        pro_list = con_list
        con_list = tmp_list

    # and build up some dict
    entry = dict()
    entry['entry_id'] = review.uid
    tmp = __handle_table_of_review_element(table, entry, review, short_text, full_text, length, is_executed)
    if not tmp:
        entry = None
    else:
        entry.update(tmp)
        entry['pro'] = pro_list
        entry['con'] = con_list
        entry['timestamp'] = sql_timestamp_pretty_print(review.timestamp, translator.get_lang())
        entry['votes_pro'] = pro_list
        entry['votes_con'] = con_list
        entry['reporter'] = __get_user_dict_for_review(review.detector_uid, main_page)

    return entry
Example #22
0
    def get_queue_information(self, db_user: User, session: Session,
                              application_url: str, translator: Translator):
        """
        Setup the subpage for the optimization queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Setting up the sub-page for the optimization-queue")
        all_rev_dict = get_all_allowed_reviews_for_user(
            session, f'already_seen_{self.key}', db_user, ReviewOptimization,
            LastReviewerOptimization)

        extra_info = ''
        # if we have no reviews, try again with fewer restrictions
        if not all_rev_dict['reviews']:
            all_rev_dict['already_seen_reviews'] = list()
            extra_info = 'already_seen' if not all_rev_dict[
                'first_time'] else ''
            db_reviews = DBDiscussionSession.query(ReviewOptimization).filter(
                ReviewOptimization.is_executed == False,
                ReviewOptimization.detector_uid != db_user.uid)
            if len(all_rev_dict['already_voted_reviews']) > 0:
                db_reviews = db_reviews.filter(~ReviewOptimization.uid.in_(
                    all_rev_dict['already_voted_reviews']))
            all_rev_dict['reviews'] = db_reviews.all()

        if not all_rev_dict['reviews']:
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': None,
                'context': [],
                'extra_info': None,
                'session': session
            }

        rnd_review = random.choice(all_rev_dict['reviews'])
        if rnd_review.statement_uid is None:
            db_argument = DBDiscussionSession.query(Argument).get(
                rnd_review.argument_uid)
            text = get_text_for_argument_uid(db_argument.uid)
            issue_titles = [
                DBDiscussionSession.query(Issue).get(
                    db_argument.issue_uid).title
            ]
            parts = self.__get_text_parts_of_argument(db_argument)
            context = [text]
        else:
            db_statement = DBDiscussionSession.query(Statement).get(
                rnd_review.statement_uid)
            text = db_statement.get_text()
            issue_titles = [
                issue.title for issue in get_issues_for_statement_uids(
                    [rnd_review.statement_uid])
            ]
            parts = [
                self.__get_part_dict('statement', text, 0,
                                     rnd_review.statement_uid)
            ]
            context = []
            args = get_all_arguments_by_statement(rnd_review.statement_uid)
            if args:
                html_wrap = '<span class="text-info"><strong>{}</strong></span>'
                context = [
                    get_text_for_argument_uid(arg.uid).replace(
                        text, html_wrap.format(text)) for arg in args
                ]

        reason = translator.get(_.argumentFlaggedBecauseOptimization)

        stats = get_reporter_stats_for_review(rnd_review,
                                              translator.get_lang(),
                                              application_url)

        all_rev_dict['already_seen_reviews'].append(rnd_review.uid)
        session[f'already_seen_{self.key}'] = all_rev_dict[
            'already_seen_reviews']

        return {
            'stats': stats,
            'text': text,
            'reason': reason,
            'issue_titles': issue_titles,
            'extra_info': extra_info,
            'context': context,
            'parts': parts,
            'session': session
        }
Example #23
0
    def __get_dict_for_argumentation(self, user_arg: Argument,
                                     confrontation_arg_uid: int, history: str,
                                     attack: Relations, nickname: str,
                                     is_supportive: bool) -> dict:
        """
        Returns dict() for the reaction step

        :param user_arg: Argument
        :param confrontation_arg_uid:  Argument.uid
        :param history: String
        :param attack: String
        :param nickname: User.nickname
        :param is_supportive: Boolean
        :return: dict()
        """
        premise = user_arg.get_premisegroup_text()
        conclusion = get_text_for_conclusion(user_arg)
        db_confrontation = DBDiscussionSession.query(Argument).get(
            confrontation_arg_uid)
        confr = db_confrontation.get_premisegroup_text()
        sys_conclusion = (db_confrontation.get_conclusion_text())
        if attack == Relations.UNDERMINE:
            if db_confrontation.conclusion_uid != 0:
                premise = db_confrontation.get_conclusion_text()
            else:
                premise = get_text_for_argument_uid(
                    db_confrontation.argument_uid,
                    True,
                    colored_position=True,
                    attack_type=attack)

        # did the user changed his opinion?
        history = history_handler.split(history)
        user_changed_opinion = len(history) > 1 and '/undercut/' in history[-2]

        # argumentation is a reply for an argument, if the arguments conclusion of the user is no position
        conclusion_uid = user_arg.conclusion_uid
        tmp_arg = user_arg
        while not conclusion_uid:
            tmp_arg = DBDiscussionSession.query(Argument).get(
                tmp_arg.argument_uid)
            conclusion_uid = tmp_arg.conclusion_uid

        db_statement = DBDiscussionSession.query(Statement).get(conclusion_uid)
        reply_for_argument = not (db_statement and db_statement.is_position)
        support_counter_argument = 'reaction' in self.history.split('-')[-1]

        current_argument = get_text_for_argument_uid(
            user_arg.uid,
            nickname=nickname,
            with_html_tag=True,
            colored_position=True,
            user_changed_opinion=user_changed_opinion,
            attack_type=attack,
            minimize_on_undercut=True,
            support_counter_argument=support_counter_argument)

        current_argument = start_with_capital(current_argument)
        if self.lang != 'de':
            premise = start_with_small(premise)

        # check for support and build text
        _tn = Translator(self.lang)
        user_text = (_tn.get(_.otherParticipantsConvincedYouThat) +
                     ': ') if user_changed_opinion else ''
        user_text += current_argument if current_argument != '' else premise

        sys_text, gender = get_text_for_confrontation(
            self.lang, nickname, premise, conclusion, sys_conclusion,
            is_supportive, attack, confr, reply_for_argument,
            not user_arg.is_supportive, user_arg, db_confrontation)
        gender_of_counter_arg = gender

        return {
            'user': user_text,
            'sys': sys_text,
            'gender': gender_of_counter_arg,
            'confrontation': db_confrontation
        }
Example #24
0
    def get_dict_for_justify_argument(self, uid, is_supportive, attack):
        """
        Prepares the discussion dict with all bubbles for a step in discussion,
        where the user justifies his attack she has done.

        :param uid: Argument.uid
        :param is_supportive: Boolean
        :param attack: String (undermine, support, undercut, rebut, ...)
        :return: dict()
        """
        LOG.debug("Entering get_dict_for_justify_argument")
        _tn = Translator(self.lang)
        bubbles_array = history_handler.create_bubbles(self.history,
                                                       self.nickname,
                                                       self.lang, self.slug)
        add_premise_text = ''
        save_statement_url = 'set_new_premises_for_argument'

        db_argument = DBDiscussionSession.query(Argument).get(uid)
        if not db_argument:
            return {
                'bubbles': bubbles_array,
                'add_premise_text': add_premise_text,
                'save_statement_url': save_statement_url,
                'mode': '',
                'broke_limit': self.broke_limit
            }

        confrontation = get_text_for_argument_uid(uid)
        premise = db_argument.get_premisegroup_text()
        conclusion = get_text_for_conclusion(db_argument,
                                             is_users_opinion=False)

        if db_argument.conclusion_uid is None:
            conclusion = start_with_small(conclusion)

        while premise.endswith(('.', '?', '!')):
            premise = premise[:-1]
        while conclusion.endswith(('.', '?', '!')):
            conclusion = premise[:-1]

        redirect_from_jump = 'jump/' in self.history.split('-')[-1]
        user_msg, sys_msg = get_header_for_users_confrontation_response(
            db_argument,
            self.lang,
            premise,
            attack,
            conclusion,
            False,
            is_supportive,
            self.nickname,
            redirect_from_jump=redirect_from_jump)

        add_premise_text = self.__get_add_premise_text_for_justify_argument(
            confrontation, premise, attack, conclusion, db_argument,
            is_supportive, user_msg)
        start = '<{} data-argumentation-type="position">'.format(tag_type)
        end = '</{}>'.format(tag_type)
        user_msg = user_msg.format(start, end)

        pro_tag = '<{} class="text-success">'.format(tag_type)
        con_tag = '<{} class="text-danger">'.format(tag_type)
        end_tag = '</{}>'.format(tag_type)

        if attack == Relations.UNDERCUT:
            sys_msg = _tn.get(
                _.whatIsYourMostImportantReasonForArgument).rstrip().format(
                    pro_tag, end_tag) + ': '
            dot = '.'
        else:
            dot = '?'
            if attack == Relations.UNDERMINE:
                sys_msg = _tn.get(
                    _.whatIsYourMostImportantReasonAgainstStatement).rstrip(
                    ).format(con_tag, end_tag)
                sys_msg += ', ' if self.lang == 'de' else ' '
            else:
                sys_msg = _tn.get(_.whatIsYourMostImportantReasonForStatement
                                  ).rstrip().format(pro_tag, end_tag) + ': '

        sys_msg += user_msg + dot + '<br>' + _tn.get(_.because) + '...'

        self.__append_now_bubble(bubbles_array)
        sys_bubble = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                              content=sys_msg,
                                              omit_bubble_url=True,
                                              lang=self.lang)
        if not bubbles_already_last_in_list(bubbles_array, sys_bubble):
            bubbles_array.append(sys_bubble)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': add_premise_text,
            'save_statement_url': save_statement_url,
            'mode': '',
            'attack_type': attack,
            'arg_uid': uid,
            'broke_limit': self.broke_limit
        }
Example #25
0
def __create_reaction_history_bubbles(step: str, db_user: User, lang: str,
                                      split_history: list, url: str,
                                      color_steps: bool, uid: int,
                                      additional_uid: int, attack) -> list:
    is_supportive = DBDiscussionSession.query(Argument).get(uid).is_supportive
    last_relation = get_last_relation(split_history)

    user_changed_opinion = len(
        split_history) > 1 and '/undercut/' in split_history[-2]
    support_counter_argument = False

    if step in split_history:
        index = split_history.index(step)
        try:
            support_counter_argument = 'reaction' in split_history[index - 1]
        except IndexError:
            support_counter_argument = False

    color_steps = color_steps and attack != Relations.SUPPORT  # special case for the support round
    current_arg = get_text_for_argument_uid(
        uid,
        user_changed_opinion=user_changed_opinion,
        support_counter_argument=support_counter_argument,
        colored_position=color_steps,
        nickname=db_user.nickname,
        with_html_tag=color_steps)

    db_argument = DBDiscussionSession.query(Argument).get(uid)
    db_confrontation = DBDiscussionSession.query(Argument).get(additional_uid)
    reply_for_argument = True
    if db_argument.conclusion_uid is not None:
        db_statement = DBDiscussionSession.query(Statement).get(
            db_argument.conclusion_uid)
        reply_for_argument = not (db_statement and db_statement.is_position)

    premise = db_argument.get_premisegroup_text()
    conclusion = get_text_for_conclusion(db_argument)
    sys_conclusion = get_text_for_conclusion(db_confrontation)
    confr = db_confrontation.get_premisegroup_text()
    user_is_attacking = not db_argument.is_supportive

    if lang != 'de':
        current_arg = start_with_capital(current_arg)
        if current_arg.startswith('<'):
            pos = current_arg.index('>')
            current_arg = current_arg[0:pos] + current_arg[pos:pos + 1].upper(
            ) + current_arg[pos + 1:]

    premise = start_with_small(premise)

    _tn = Translator(lang)
    user_text = ''
    if last_relation == Relations.SUPPORT:
        user_text = _tn.get(_.otherParticipantsConvincedYouThat) + ': '

    user_text += '<{}>{}</{}>'.format(
        tag_type, current_arg if current_arg != '' else premise, tag_type)

    sys_text, tmp = get_text_for_confrontation(lang,
                                               db_user.nickname,
                                               premise,
                                               conclusion,
                                               sys_conclusion,
                                               is_supportive,
                                               attack,
                                               confr,
                                               reply_for_argument,
                                               user_is_attacking,
                                               db_argument,
                                               db_confrontation,
                                               color_html=False)

    bubble_user = create_speechbubble_dict(BubbleTypes.USER,
                                           bubble_url=url,
                                           content=user_text,
                                           omit_bubble_url=False,
                                           argument_uid=uid,
                                           is_supportive=is_supportive,
                                           db_user=db_user,
                                           lang=lang)
    db_tmp = DBDiscussionSession.query(User).get(db_confrontation.author_uid)
    if not attack:
        bubble_syst = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                               content=sys_text,
                                               omit_bubble_url=True,
                                               db_user=db_user,
                                               lang=lang,
                                               other_author=db_tmp)
    else:
        bubble_syst = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                               uid='question-bubble-' +
                                               str(additional_uid),
                                               content=sys_text,
                                               omit_bubble_url=True,
                                               db_user=db_user,
                                               lang=lang,
                                               other_author=db_tmp)
    return [bubble_user, bubble_syst]
Example #26
0
def __resolve_argument_attribute(attribute, main_page, db_languages, db_users, tmp):
    text = get_text_for_argument_uid(attribute) if attribute is not None else 'None'
    tmp.append('{} - {}'.format(attribute, text))
Example #27
0
    def test_get_text_for_argument_uid(self):
        s47 = 'we should close public swimming pools because our swimming pools are very old and it would take a ' \
              'major investment to repair them'
        s48 = 'Other participants said that we should close public swimming pools because our swimming pools are ' \
              'very old and it would take a major investment to repair them. You did not agree with this because ' \
              'schools need the swimming pools for their sports lessons.'
        s49 = 'we should close public swimming pools does not hold, because the rate of non-swimmers is too high'

        self.assertEqual(lib.get_text_for_argument_uid(47), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, attack_type='doesnt-matter-parameter-should-be-a-boolean'),
                         s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, attack_type='doesnt-matter-parameter-should-be-a-boolean'),
                         s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, attack_type='doesnt-matter-parameter-should-be-a-boolean'),
                         s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, attack_type='jump'), '{}.'.format(s47))
        self.assertEqual(lib.get_text_for_argument_uid(48, attack_type='jump'),
                         'our swimming pools are very old and it would take a major investment to repair them is not '
                         'a good reason for we should close public swimming pools. Because schools need the swimming '
                         'pools for their sports lessons.')
        self.assertEqual(lib.get_text_for_argument_uid(49, attack_type='jump'),
                         'we should close public swimming pools does not hold because the rate of non-swimmers is too '
                         'high.')

        self.assertEqual(lib.get_text_for_argument_uid(47, with_html_tag=True),
                         '<span>we should close public swimming pools</span> because our swimming pools are very old '
                         'and it would take a major investment to repair them')
        self.assertEqual(lib.get_text_for_argument_uid(48, with_html_tag=True),
                         'Other participants said that we should close public swimming pools because our swimming '
                         'pools are very old and it would take a major investment to repair them. You did not agree '
                         'with this because<span data-argumentation-type="position"> schools need the swimming pools '
                         'for their sports lessons.')
        self.assertEqual(lib.get_text_for_argument_uid(49, with_html_tag=True),
                         '<span>we should close public swimming pools</span> <span> does not hold</span>, because the '
                         'rate of non-swimmers is too high')

        self.assertEqual(lib.get_text_for_argument_uid(47, start_with_intro=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, start_with_intro=True), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, start_with_intro=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, first_arg_by_user=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, first_arg_by_user=True),
                         'We should close public swimming pools because our swimming pools are very old and it would '
                         'take a major investment to repair them. Now you agree that schools need the swimming pools '
                         'for their sports lessons.')
        self.assertEqual(lib.get_text_for_argument_uid(49, first_arg_by_user=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, is_users_opinion=False), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, is_users_opinion=False), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, is_users_opinion=False), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, rearrange_intro=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, rearrange_intro=True), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, rearrange_intro=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, support_counter_argument=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, support_counter_argument=True), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, support_counter_argument=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, nickname='Dieter'), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, nickname='Dieter'), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, nickname='Dieter'), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, minimize_on_undercut=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, minimize_on_undercut=True), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, minimize_on_undercut=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, colored_position=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, colored_position=True), s48)
        self.assertEqual(lib.get_text_for_argument_uid(49, colored_position=True), s49)

        self.assertEqual(lib.get_text_for_argument_uid(47, user_changed_opinion=True), s47)
        self.assertEqual(lib.get_text_for_argument_uid(48, user_changed_opinion=True),
                         'Earlier you argued that we should close public swimming pools because our swimming pools '
                         'are very old and it would take a major investment to repair them. Other participants '
                         'convinced you that schools need the swimming pools for their sports lessons.')
        self.assertEqual(lib.get_text_for_argument_uid(49, user_changed_opinion=True), s49)
Example #28
0
def __get_subpage_dict_for_optimization(session, application_url, db_user,
                                        translator):
    """
    Setup the subpage for the optimization queue

    :param session: session of current webserver request
    :param application_url: current url of the app
    :param db_user: User
    :param translator: Translator
    :return: dict()
    """
    logger('ReviewSubpagerHelper', 'main')
    db_reviews, already_seen, already_reviewed, first_time = __get_all_allowed_reviews_for_user(
        session, 'already_seen_optimization', db_user, ReviewOptimization,
        LastReviewerOptimization)

    extra_info = ''
    # if we have no reviews, try again with fewer restrictions
    if not db_reviews:
        already_seen = list()
        extra_info = 'already_seen' if not first_time else ''
        db_reviews = DBDiscussionSession.query(ReviewOptimization).filter(
            ReviewOptimization.is_executed == False,
            ReviewOptimization.detector_uid != db_user.uid)
        if len(already_reviewed) > 0:
            db_reviews = db_reviews.filter(
                ~ReviewOptimization.uid.in_(already_reviewed))
        db_reviews = db_reviews.all()

    if not db_reviews:
        return {
            'stats': None,
            'text': None,
            'reason': None,
            'issue': None,
            'context': [],
            'extra_info': None,
            'session': session
        }

    rnd_review = db_reviews[random.randint(0, len(db_reviews) - 1)]
    if rnd_review.statement_uid is None:
        db_argument = DBDiscussionSession.query(Argument).get(
            rnd_review.argument_uid)
        text = get_text_for_argument_uid(db_argument.uid)
        issue = DBDiscussionSession.query(Issue).get(
            db_argument.issue_uid).title
        parts = __get_text_parts_of_argument(db_argument)
        context = [text]
    else:
        db_statement = DBDiscussionSession.query(Statement).get(
            rnd_review.statement_uid)
        text = db_statement.get_text()
        issue = DBDiscussionSession.query(Issue).get(
            db_statement.issue_uid).title
        parts = [
            __get_part_dict('statement', text, 0, rnd_review.statement_uid)
        ]
        context = []
        args = get_all_arguments_by_statement(rnd_review.statement_uid)
        if args:
            context = [
                get_text_for_argument_uid(arg.uid).replace(
                    text, '<span class="text-info"><strong>{}</strong></span>'.
                    format(text)) for arg in args
            ]

    reason = translator.get(_.argumentFlaggedBecauseOptimization)

    stats = __get_stats_for_review(rnd_review, translator.get_lang(),
                                   application_url)

    already_seen.append(rnd_review.uid)
    session['already_seen_optimization'] = already_seen

    return {
        'stats': stats,
        'text': text,
        'reason': reason,
        'issue': issue,
        'extra_info': extra_info,
        'context': context,
        'parts': parts,
        'session': session
    }