Ejemplo n.º 1
0
def user(db):
    user = User.objects.create_user('*****@*****.**', 'password')
    create_conversation(text='test',
                        title='title',
                        author=user,
                        is_promoted=True)
    return user
Ejemplo n.º 2
0
def make_conversation_with_clusters_en():
    conversation = create_conversation(
        "How should our society organize the production of goods and services?",
        "Economy",
        is_promoted=True,
        author=User.objects.filter(is_staff=True).first(),
    )
    set_clusters_from_comments(
        conversation,
        {
            "Liberal": [
                "Free market should regulate how enterprises invest money and hire " "employees.",
                "State should provide a stable judicial system and refrain from " "regulating the economy.",
            ],
            "Socialist": [
                "Government and the society as a whole must regulate business "
                "decisions to favor the common good rather than private interests.",
                "State leadership is necessary to drive a strong economy.",
            ],
            "Fascist": [
                "Government should eliminate opposition in order to ensure " "governability.",
                "Military should occupy high ranks in government.",
            ],
        },
    )
    return conversation
Ejemplo n.º 3
0
def make_clusters(verbose=True):
    conversation = create_conversation(
        'How should our society organize the production of goods and services?',
        'Economy',
        is_promoted=True,
        author=User.objects.filter(is_staff=True).first(),
    )
    set_clusters_from_comments(conversation, {
        'Liberal': [
            'Free market should regulate how enterprises invest money and hire '
            'employees.',
            'State should provide a stable judicial system and refrain from '
            'regulating the economy.',
        ],
        'Socialist': [
            'Government and the society as a whole must regulate business '
            'decisions to favor the common good rather than private interests.',
            'State leadership is necessary to drive a strong economy.',
        ],
        'Facist': [
            'Government should elliminate opposition in order to ensure '
            'governability.',
            'Military should occupy high ranks in government.',
        ]
    })
Ejemplo n.º 4
0
def create_clusters(k=3, n_users=20, n_comments=50, missing=0.0, fraction=0.5):
    """
    Create clusters that have ideally placed stereotypes.
    """
    from ej_clusters.math.factories import random_clusterization
    from ej_conversations import create_conversation
    from ej_conversations.models import Vote
    from django.contrib.auth import get_user_model
    from django.db.transaction import atomic

    votes, centroids = random_clusterization([n_users] * k,
                                             n_comments,
                                             alpha=0.5,
                                             missing=missing)

    # Save to database
    with atomic():
        author = get_user_model().objects.filter(is_active=True).last()
        users = list(
            get_user_model().objects.filter(is_active=True)[:(n_users * k)])
        conversation = create_conversation("What?",
                                           "what",
                                           author,
                                           is_promoted=True)

        comments = []
        for n in range(n_comments):
            comment = conversation.create_comment(author,
                                                  f"Comment {n + 1}",
                                                  check_limits=False)
            comments.append(comment)

        clusterization = conversation.get_clusterization()
        for m in range(k):
            cluster = clusterization.clusters.create(name=f"Cluster-{m + 1}")
            stereotype = cluster.stereotypes.create(
                name=f"Persona for cluster {m + 1}/{conversation.id}",
                owner=author)
            for n, comment in enumerate(comments[:int(fraction * n_comments)]):
                stereotype.vote(comment,
                                1 if random() < centroids[m, n] else -1)

        db_votes = []
        for i, user in enumerate(users):
            for j, comment in enumerate(comments):
                choice = votes[i, j]
                if choice:
                    vote = comment.vote(user, choice, commit=False)
                    db_votes.append(vote)

        Vote.objects.bulk_create(db_votes)
        clusterization.update_clusterization(force=True)

        # Check correctness
        # py_votes = pd.DataFrame(votes, index=[u.id for u in users], columns=[c.id for c in comments])
        # db_votes = conversation.comments.votes_table()
        # assert ((db_votes - py_votes) == 0).all()

    return conversation
Ejemplo n.º 5
0
 def test_get_board_default_palette_from_conversation(self, mk_user):
     user = mk_user(email="*****@*****.**")
     conversation = create_conversation("foo", "conv1", user)
     board = Board.objects.create(slug="board1",
                                  owner=user,
                                  description="board")
     board.conversations.add(conversation)
     assert conversation.css_palette == "bluePalette"
Ejemplo n.º 6
0
 def test_get_board_palette_from_conversation(self, mk_conversation, mk_user):
     user = mk_user(email="*****@*****.**")
     conversation = create_conversation("foo", "conv1", user)
     board = Board.objects.create(slug="board1", owner=user, palette="Orange", description="board")
     board.conversations.add(conversation)
     assert conversation.css_palette == "orangePalette"
     assert conversation.css_light_palette == "orangePalette-light"
     assert conversation.css_text_palette == "orangePalette-text"
Ejemplo n.º 7
0
def create_colors_experiment(skip_prob=0.25,
                             n_times=1,
                             n_users=21,
                             has_yellow=False):
    """
    The "colors" experiment creates a few groups tagged by color names.
    Each comment has a baseline probability of around 25% for agree/disagree in
    the general population, but has some different probability for each user.
    """
    from ej_conversations import create_conversation
    from ej_clusters.models import Clusterization
    from ej_clusters.enums import ClusterStatus

    # Conversation
    rgb = ("red", "green", "blue")
    author = create_user("color", "admin")
    conversation = create_conversation("What is your favorite color?",
                                       "Color",
                                       author,
                                       is_promoted=True)

    # Create users
    colors = (*rgb, "yellow") if has_yellow else rgb
    user_map = {color: users(color, n_users) for color in colors}

    # Create comments
    comment_map = {
        color: repeat(n_times, comments, color, user_map[color][0],
                      conversation)
        for color in rgb
    }

    # Cast votes for users and stereotypes
    clusterization = Clusterization.objects.create(
        conversation=conversation, cluster_status=ClusterStatus.ACTIVE)
    votes = cast_user_votes(comment_map, user_map, skip_prob)
    stereotype_votes = cast_stereotypes_votes(comment_map, clusterization)
    votes.extend(stereotype_votes)
    clusterization.update_clusterization(force=True)
    return votes
Ejemplo n.º 8
0
def make_clusters(verbose=True, force=False):
    if force:
        Conversation.objects.filter(title='Economy').delete()

    conversation = create_conversation(
        'How should our society organize the production of goods and services?',
        'Economy',
        author=User.objects.filter(is_staff=True).first(),
    )
    set_clusters_from_comments(conversation, {
        'Liberal': [
            'Free market should regulate how enterprises invest money and hire '
            'employees.',
            'State should provide a stable judicial system and refrain from '
            'regulating the economy.',
        ],
        'Socialist': [
            'Government and the society as a whole must regulate business '
            'decisions to favor the common good rather than private interests.',
            'State leadership is necessary to drive a strong economy.',
        ]
    })
Ejemplo n.º 9
0
def make_conversation_with_clusters_pt_br():
    conversation = create_conversation(
        "Que medidas devem ser feitas para melhorar a educação de jovens e adolescentes?",
        "Educação",
        is_promoted=True,
        author=User.objects.filter(is_staff=True).first(),
    )
    set_clusters_from_comments(
        conversation,
        {
            "Estatista": [
                "É necessário aumentar a verba destinada à educação pública de qualidade",
                "Devemos incentivar a participação da classe média na escola pública reservando vagas nas "
                "universidades.",
                "O Brasil deve utilizar o dinheiro do pré-sal somente para a educação.",
            ],
            "Privatista": [
                "Estado deve financiar a criação de parcerias público-privadas para a educação",
                "Escolas particulares promovem maior autonomia pedagógica e dão poder de escolha aos pais.",
                "O Brasil deve financiar alunos carentes com vagas em escolas particulares.",
            ],
            "Liberal": [
                "Escolas devem promover criatividade e autonomia dos jovens",
                "Jovens devem possuir atividades extra-classe regulares em museus, parques, bibliotecas, etc.",
                "É necessário dar aulas de filosofia, sociologia, etc para incentivar o pensamento crítico",
            ],
            "Disciplinador": [
                "Escolas devem treinar a disciplina e respeito à autoridade e ao cumprimento de regras.",
                "Alunos e professores devem ser punidos exemplarmente por desordem e violação das regras.",
                "As escolas devem proibir manifestações políticas do professor em sala de aula",
            ],
            "Tecnocrata": [
                "A escola deve fornecer treinamento para o mercado de trabalho e capacitação profissional desde cedo.",
                "As disciplinas e conteúdos ensinados na escola devem refletir demandas do mercado de trabalho.",
                "É necessário um currículo e testes unificados.",
            ],
        },
    )
    return conversation
Ejemplo n.º 10
0
 def test_create_conversation_saves_model_in_db(self, user_db):
     conversation = create_conversation('what?', 'test', user_db)
     assert conversation.id is not None
     assert conversation.author == user_db
Ejemplo n.º 11
0
 def test_create_conversation(self, user):
     conversation = create_conversation('what?', 'test', user, commit=False)
     assert conversation.author == user
Ejemplo n.º 12
0
def conversation(db, user):
    return create_conversation(text='test', title='title', author=user)
Ejemplo n.º 13
0
def conversation(db, user):
    return create_conversation(text="test",
                               title="title",
                               author=user,
                               is_promoted=True)
Ejemplo n.º 14
0
def user(db):
    user = User.objects.create_user("*****@*****.**", "password")
    create_conversation(text="test", title="title", author=user, is_promoted=True)
    return user
Ejemplo n.º 15
0
def conversation(db, user):
    return create_conversation(text='test',
                               title='title',
                               author=user,
                               is_promoted=True)