Esempio n. 1
0
    def test_serialize_deserialize(self):
        s = Score()
        s.max = 100.0
        s.min = 0.0
        s.raw = 80.0
        s.scaled = 0.8

        self.assertSerializeDeserialize(s)
Esempio n. 2
0
    def answer_evaluation(cls, answer, score, **kwargs):
        from compair.models import ScoringAlgorithm

        result = cls.basic(**kwargs)
        result.extensions = Extensions(
        ) if not result.extensions else result.extensions

        result.score = Score(raw=score.score)

        score_details = {
            'algorithm': score.scoring_algorithm.value,
            'wins': score.wins,
            'loses': score.loses,
            'rounds': score.rounds,
            'opponents': score.opponents,
        }

        if score.scoring_algorithm == ScoringAlgorithm.comparative_judgement:
            result.score.min = 0.0
            result.score.max = 1.0
            score_details['expected score'] = score.variable1

        elif score.scoring_algorithm == ScoringAlgorithm.true_skill:
            score_details['mu'] = score.variable1
            score_details['sigma'] = score.variable2

        result.extensions[XAPIExtension.result_extensions.get(
            'score details')] = score_details

        return result
Esempio n. 3
0
    def setUp(self):
        self.endpoint = lrs_properties.endpoint
        self.version = lrs_properties.version
        self.username = lrs_properties.username
        self.password = lrs_properties.password
        self.lrs = RemoteLRS(
            version=self.version,
            endpoint=self.endpoint,
            username=self.username,
            password=self.password,
        )

        self.agent = Agent(mbox="mailto:[email protected]")
        self.agent2 = Agent(mbox="mailto:[email protected]")
        self.verb = Verb(id="http://adlnet.gov/expapi/verbs/experienced",
                         display=LanguageMap({"en-US": "experienced"}))

        self.group = Group(member=[self.agent, self.agent2])

        self.activity = Activity(
            id="http://tincanapi.com/TinCanPython/Test/Unit/0",
            definition=ActivityDefinition())
        self.activity.definition.type = "http://id.tincanapi.com/activitytype/unit-test"
        self.activity.definition.name = LanguageMap({"en-US": "Python Tests"})
        self.activity.definition.description = LanguageMap(
            {"en-US": "Unit test in the test suite for the Python library"})
        self.activity.object_type = 'Activity'

        self.parent = Activity(id="http://tincanapi.com/TinCanPython/Test",
                               definition=ActivityDefinition())
        self.parent.definition.type = "http://id.tincanapi.com/activitytype/unit-test-suite"
        self.parent.definition.name = LanguageMap({"en-US": "Python Tests"})
        self.parent.definition.description = LanguageMap(
            {"en-US": "Unit test in the test suite for the Python library"})
        self.parent.object_type = 'Activity'

        self.statement_ref = StatementRef(id=uuid.uuid4())

        self.context = Context(registration=uuid.uuid4(),
                               statement=self.statement_ref)
        # self.context.context_activities = ContextActivities(parent=[self.parent])

        self.score = Score(raw=97, scaled=0.97, max=100, min=0)

        self.result = Result(score=self.score,
                             success=True,
                             completion=True,
                             duration="PT120S")

        self.substatement = SubStatement(
            actor=self.agent,
            verb=self.verb,
            object=self.activity,
        )
Esempio n. 4
0
    def test_serialize_deserialize(self):
        s = Score()
        s.max = 100.0
        s.min = 0.0
        s.raw = 80.0
        s.scaled = 0.8

        self.assertSerializeDeserialize(s)
Esempio n. 5
0
    def get_result(self, course_grade):
        """
        Get result for the statement.

        Arguments:
            course_grade (CourseGrade): Course grade.
        """
        return Result(score=Score(
            scaled=course_grade.percent,
            raw=course_grade.percent * 100,
            min=MIN_SCORE,
            max=MAX_SCORE,
        ),
                      success=course_grade.passed,
                      completion=course_grade.passed)
Esempio n. 6
0
    def answer_score(cls, answer, score, **kwargs):
        from compair.models import ScoringAlgorithm

        result = cls.basic(**kwargs)
        result.extensions = Extensions() if not result.extensions else result.extensions

        result.score = Score(raw=score.score)

        score_details = {
            'score': score.score,
            'algorithm': score.scoring_algorithm.value,
            'wins': score.wins,
            'loses': score.loses,
            'rounds': score.rounds,
            'opponents': score.opponents,
            'criteria': {}
        }

        if score.scoring_algorithm == ScoringAlgorithm.true_skill:
            score_details['mu'] = score.variable1
            score_details['sigma'] = score.variable2

        for criterion_score in answer.criteria_scores:
            criterion_score_details = {
                'score': criterion_score.score,
                'wins': criterion_score.wins,
                'loses': criterion_score.loses,
                'rounds': criterion_score.rounds,
                'opponents': criterion_score.opponents,
            }

            if criterion_score.scoring_algorithm == ScoringAlgorithm.true_skill:
                criterion_score_details['mu'] = criterion_score.variable1
                criterion_score_details['sigma'] = criterion_score.variable2

            score_details['criteria'][ResourceIRI.criterion(criterion_score.criterion_uuid)] = criterion_score_details

        result.extensions['http://xapi.learninganalytics.ubc.ca/extension/score-details'] = score_details

        return result
    def get_result(self, persistent_course_grade):
        """
        Get result for the statement.

        Arguments:
            persistent_course_grade (PersistentCourseGrade): PersistentCourseGrade record
        """
        completed = 0
        success = 0

        if persistent_course_grade.passed_timestamp is not None:
            completed = 1
            success = 1

        return Result(score=Score(
            scaled=persistent_course_grade.percent_grade,
            raw=persistent_course_grade.percent_grade * 100,
            min=MIN_SCORE,
            max=MAX_SCORE,
        ),
                      success=success,
                      completion=completed)
 def setUp(self):
     self.score = Score(max=100.0, min=0.0, raw=80.0, scaled=0.8)
     self.extensions = Extensions({
         'http://example.com/extension':
         'extension value',
     })
Esempio n. 9
0
def socialmedia_builder(statement_id,
                        verb,
                        platform,
                        account_name,
                        account_homepage,
                        object_type,
                        object_id,
                        message,
                        tags=[],
                        parent_object_type=None,
                        parent_id=None,
                        rating=None,
                        instructor_name=None,
                        instructor_email=None,
                        team_name=None,
                        unit=None,
                        account_email=None,
                        user_name=None,
                        timestamp=None,
                        other_contexts=[]):

    agentaccount = AgentAccount(name=account_name, home_page=account_homepage)
    actor = Agent(account=agentaccount)

    # XAPI statements can only have one of: AgentAccount, mbox, mboxsha1 or Openid
    #if (account_email is not None):
    #    actor.mbox = account_email
    #if (user_name is not None):
    #    actor.name = user_name

    verb_obj = Verb(id=xapi_settings.get_verb_iri(verb),
                    display=LanguageMap({'en-US': verb}))

    #message = message.decode('utf-8').encode('ascii', 'ignore') #message.decode('utf-8').replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013", "-").replace(u"\ud83d", " ").replace(u"\ude09", " ").replace(u"\u00a0l", " ").replace(u"\ud83d", " ").replace(u"\u2026", " ").replace(u"\ude09", " ").replace(u"\u00a0"," ")

    object = Activity(
        id=object_id,
        object_type=object_type,
        definition=ActivityDefinition(
            name=LanguageMap({'en-US': message}),
            type=xapi_settings.get_object_iri(object_type)),
    )

    taglist = []
    for tag in tags:
        tagobject = Activity(
            id='http://id.tincanapi.com/activity/tags/tincan',
            object_type='Activity',
            definition=ActivityDefinition(
                name=LanguageMap({'en-US': tag}),
                type=xapi_settings.get_object_iri('Tag')),
        )
        taglist.append(tagobject)

    # Add "other" in contextActivities
    other_contexts_list = []
    for other in other_contexts:
        other_context_obj = Activity(
            id=other['obj_id'],
            object_type=other['obj_type'],
            definition=ActivityDefinition(name=LanguageMap(
                {'en-US': other['definition']['name']}),
                                          type=other['definition']['type']),
        )
        other_contexts_list.append(other_context_obj)
    taglist.extend(other_contexts_list)

    parentlist = []
    if (verb in ['liked', 'shared', 'commented',
                 'rated']):  #recipe specific config
        parentobject = Activity(
            id=parent_id,
            object_type=parent_object_type,
        )
        parentlist.append(parentobject)
    elif (platform == 'GitHub' or platform.lower() == 'trello'):
        parentobject = Activity(
            id=parent_id,
            object_type=parent_object_type,
        )
        parentlist.append(parentobject)

    courselist = []
    if unit is not None:
        courseobject = Activity(
            id="http://adlnet.gov/expapi/activities/course",
            object_type='Course',
            definition=ActivityDefinition(
                name=LanguageMap({'en-US': unit.code}),
                description=LanguageMap({
                    'en-US':
                    "A course/unit of learning hosted on the CLAToolkit"
                })))
        courselist.append(courseobject)

    instructor = None
    if (instructor_name is not None):
        instructor = Agent(name=instructor_name, mbox=instructor_email)

    team = None
    if (team_name is not None):
        team = Group(Agent(name=team_name), object_type='Group')

    result = None
    if (rating is not None):
        rating_as_float = float(rating)
        result = Result(score=Score(raw=rating_as_float))

    context = Context(registration=uuid.uuid4(),
                      platform=platform,
                      instructor=instructor,
                      team=team,
                      context_activities=ContextActivities(
                          other=ActivityList(taglist),
                          parent=ActivityList(parentlist),
                          grouping=ActivityList(courselist)))

    # Xapi spec requires that the learning provider SHOULD provide the authority
    # Authority is a group with Agent as oauth consumer app where name is token url and homepage is consumer_key
    account = AgentAccount(name=unit.get_lrs_key(),
                           home_page=unit.get_lrs_access_token_url())

    authority = Group(Agent(account=account))

    statement = statement_builder(statement_id, actor, verb_obj, object,
                                  context, result, authority, timestamp)

    return statement
Esempio n. 10
0
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            project = get_object_or_404(Project, id=data['project'])
            user = data['user']

            timezone = pytz.timezone("Europe/Rome")

            actor = Agent(
                name=user.get_display_name(),
                mbox='mailto:%s' % user.email,
            )

            project_id = get_object_id(request, project)

            activity_type = xapi_activities['assessment']['type']
            object_language = 'it'
            verb = Verb(
                id=xapi_verbs['completed']['id'],
                display=LanguageMap(**xapi_verbs['completed']['display']),
            )

            file = request.FILES['file']
            filename = file.name
            extension = filename.split(".")[-1]
            content = file.read()
            records = pyexcel.get_records(file_type=extension,
                                          file_content=content)
            name_dict = records[0]
            keys = name_dict.keys()
            rows = []
            for record in records:
                date_time = record['Ora']
                lesson = record['Lezione']
                course = record['Corso']
                activity = record['Attività']
                duration_seconds = record['Durata (Secondi)']
                response_seconds = record['Tempo medio di risposta (Secondi)']
                score_percent = record['Punteggio (%)']
                questions = record['Domande con risposta']
                correct_answers = record['Risposte corrette']

                timestamp = datetime.strptime(date_time, "%d/%m/%Y %H.%M")
                timestamp = timezone.localize(timestamp)

                object_name = 'EarMaster: {}'.format(activity)
                object_description = 'Esercizio di {} in lezione EarMaster "{}"'.format(
                    activity, lesson)
                activity_definition = ActivityDefinition(
                    name=LanguageMap(**{object_language: object_name}),
                    description=object_description
                    and LanguageMap(**{object_language: object_description})
                    or None,
                    type=activity_type,
                )
                course_id = '{}{}'.format(project_id, slugify(course))
                lesson_id = '{}/{}'.format(course_id, slugify(lesson))
                object = Activity(
                    objectType='Activity',
                    id=lesson_id,
                    definition=activity_definition,
                )
                parent = {
                    'objectType': 'Activity',
                    'id': course_id,
                    'definition': {
                        'type': xapi_activities['course']['type'],
                        'name': {
                            'it': course
                        }
                    }
                }
                grouping = {
                    'objectType': 'Activity',
                    'id': project_id,
                    'definition': {
                        'type':
                        xapi_activities['project']['type'],
                        'name':
                        LanguageMap(**{get_language(project): project.name})
                    }
                }
                context = {
                    'platform': 'EarMaster',
                    'context_activities': {
                        'parent': parent,
                        'grouping': grouping
                    }
                }
                context = Context(**context)

                score_scaled = float(score_percent.replace('%', '')) / 100
                score_max = questions
                score_raw = correct_answers
                score = {
                    'min': 0,
                    'max': score_max,
                    'raw': score_raw,
                    'scaled': score_scaled
                }
                score = Score(**score)
                result = {'duration': duration_seconds, 'score': score}
                result = Result(**result)

                statement = Statement(actor=actor,
                                      verb=verb,
                                      object=object,
                                      context=context,
                                      result=result,
                                      timestamp=timestamp)
                result = send_statement(statement)
            return HttpResponseRedirect('/project/%s/' % project.slug)
        return render(request, self.template_name,
                      {'earmaster_import_results_form': form})
Esempio n. 11
0
    def test_bad_property_init(self):
        with self.assertRaises(AttributeError):
            Score(bad_name=2)

        with self.assertRaises(AttributeError):
            Score({'bad_name': 2})
Esempio n. 12
0
    def test_serialize_deserialize_init(self):
        s = Score(max=100.0, min=0.0, raw=80.0, scaled=0.8)

        self.assertSerializeDeserialize(s)
Esempio n. 13
0
def socialmedia_builder(verb, platform, account_name, account_homepage, object_type, object_id, message, tags=[], parent_object_type=None, parent_id=None, rating=None, instructor_name=None, instructor_email=None, team_name=None, course_code=None, account_email=None, user_name=None, timestamp=None):
    verbmapper = {'created': 'http://activitystrea.ms/schema/1.0/create', 'shared': 'http://activitystrea.ms/schema/1.0/share', 'liked': 'http://activitystrea.ms/schema/1.0/like', 'rated': 'http://id.tincanapi.com/verb/rated', 'commented': 'http://adlnet.gov/expapi/verbs/commented'}
    objectmapper = {'Note': 'http://activitystrea.ms/schema/1.0/note', 'Tag': 'http://id.tincanapi.com/activitytype/tag', 'Article': 'http://activitystrea.ms/schema/1.0/article', 'Video': 'http://activitystrea.ms/schema/1.0/video'}

    agentaccount = AgentAccount(name=account_name, home_page=account_homepage)
    actor = Agent(account=agentaccount)
    if (account_email is not None):
        actor.mbox = account_email
    if (user_name is not None):
        actor.name = user_name

    verb_obj = Verb(id=verbmapper[verb],display=LanguageMap({'en-US': verb}))

    #message = message.decode('utf-8').encode('ascii', 'ignore') #message.decode('utf-8').replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013", "-").replace(u"\ud83d", " ").replace(u"\ude09", " ").replace(u"\u00a0l", " ").replace(u"\ud83d", " ").replace(u"\u2026", " ").replace(u"\ude09", " ").replace(u"\u00a0"," ")

    object = Activity(
        id=object_id,
        object_type=object_type,
        definition=ActivityDefinition(
            name=LanguageMap({'en-US': message}),
            type=objectmapper[object_type]
        ),
    )

    taglist = []
    for tag in tags:
        tagobject = Activity(
            id='http://id.tincanapi.com/activity/tags/tincan',
            object_type='Activity',
            definition=ActivityDefinition(
                name=LanguageMap({'en-US': tag}),
                type=objectmapper['Tag']
                ),
            )
        taglist.append(tagobject)

    parentlist = []
    if (verb in ['liked','shared','commented','rated']):
        parentobject = Activity(
            id=parent_id,
            object_type=parent_object_type,
            )
        parentlist.append(parentobject)

    courselist = []
    if (course_code is not None):
        courseobject = Activity(
            id=course_code,
            object_type='Course',
            definition=ActivityDefinition(type="http://adlnet.gov/expapi/activities/course")
            )
        courselist.append(courseobject)

    instructor = None
    if (instructor_name is not None):
        instructor=Agent(name=instructor_name,mbox=instructor_email)

    team = None
    if (team_name is not None):
        team = Group(Agent(name=team_name), object_type='Group')

    result = None
    if (rating is not None):
        rating_as_float = float(rating)
        result = Result(score=Score(raw=rating_as_float))

    context = Context(
        registration=uuid.uuid4(),
        platform=platform,
        instructor=instructor,
        team=team,
        context_activities=ContextActivities(other=ActivityList(taglist),parent=ActivityList(parentlist),grouping=ActivityList(courselist))
    )

    statement = statement_builder(actor, verb_obj, object, context, result, timestamp)

    return statement
Esempio n. 14
0
    def sendStatement(self, reqData):
        #load requested data for statement generation
        data = json.loads(reqData)

        # create RemoteLRS endpoint
        lrs = self.LRS

        # generate statement

        # 1. actor
        actor = Agent(
            name=data["name"],
            mbox='mailto:' + data["name"] + '@id.lrs',
        )

        # 2. verb
        verb = Verb(
            id=self.verbs.get(data["verb"]),
            display=LanguageMap({'en-US': data["verb"]}),
        )

        # 3. object
        obj = Activity(
            id=self.objects.get(data["activity"]),
            definition=ActivityDefinition(
                name=LanguageMap({'en-US': data["activityid"]})
            )
        )

        # 4. context
        context = Context(
            extensions=Extensions({
                self.extensions.get("difficulty"): data["difficulty"],
                self.extensions.get("interaction"): data["interaction"],
                self.extensions.get("topic"): data["topic"]
            })
        )

        # 5. result
        result = Result(
            score=Score(
                raw=data["score"]
            ),
            success=data["success"]
        )

        # build statement
        statement = Statement(
            actor=actor,
            verb=verb,
            object=obj,
            context=context,
            result=result
        )

        # save statement
        response = lrs.save_statement(statement)

        # check response
        if not response:
            raise ValueError("statement failed to save")
        return str(True)