Skip to content

Admin

DataMultiModalConversationFKAdmin

Bases: ImportExportModelAdmin

All the obj above will be self.multi_modal_conversation

Source code in API/hardware/admin.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
class DataMultiModalConversationFKAdmin(ImportExportModelAdmin):
    """
    All the obj above will be self.multi_modal_conversation
    """

    def audio__time_range(self, obj):
        # format it "%Y-%m-%d %H:%M:%S"
        if obj.multi_modal_conversation.audio is None:
            return "No Audio"
        start_time_str = obj.multi_modal_conversation.audio.start_time.strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        end_time_str = obj.multi_modal_conversation.audio.end_time.strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        return f"{start_time_str} - {end_time_str}"

    audio__time_range.short_description = "Time Range: Audio"

    def video__time_range(self, obj):
        if len(obj.multi_modal_conversation.video.all()) == 0:
            return "No Video"
        videos = obj.multi_modal_conversation.video.all().order_by("start_time")
        # get the first video start time and the last video end time
        start_time_str = videos.first().start_time.strftime("%Y-%m-%d %H:%M:%S")
        end_time_str = videos.last().end_time.strftime("%Y-%m-%d %H:%M:%S")
        return f"{start_time_str} - {end_time_str}"

    video__time_range.short_description = "Time Range: Video"

    def play_audio(self, obj):
        if obj.multi_modal_conversation.audio is None:
            return "No Audio"

        return mark_safe(
            f'<audio controls name="media">'
            f'<source src="{obj.multi_modal_conversation.audio.url()}" type="audio/mpeg"></audio>'
        )

    def play_video(self, obj):
        if (
            obj.multi_modal_conversation.video is None
            or len(obj.multi_modal_conversation.video.all()) == 0
        ):
            return "No Video"
        return mark_safe(
            f'<video width="320" height="240" controls>'
            f'<source src="{obj.multi_modal_conversation.video_url()}" type="video/mp4"></video>'
        )

    def play_res_speech(self, obj):
        if obj.multi_modal_conversation.res_speech is None:
            return "No Response Speech"
        return mark_safe(
            f'<audio controls name="media">'
            f'<source src="{obj.multi_modal_conversation.res_speech.url()}" type="audio/mpeg"></audio>'
        )

    def speech_to_text(self, obj):
        if obj.multi_modal_conversation.text is None:
            return "No Text"
        return obj.multi_modal_conversation.text.text

    def response_text(self, obj):
        if obj.multi_modal_conversation.res_text is None:
            return "No Response Text"
        return obj.multi_modal_conversation.res_text.text

    def annotation_records(self, obj):
        annotations = obj.annotations
        if not annotations:
            return "No Annotations"
        """
        Get this presentation into a html like this:

        User: {username}
        Annotation Overall: {annotation_overall}
        Annotation Text Modality: {annotation_text_modality}
        Annotation Audio Modality: {annotation_audio_modality}
        ----
        User: {username}
        ....

        """

        return_html = "<div>"
        return_html += f"<h5>Total Annotator: {len(annotations.items())} </h5>"
        return_html += "<hr>"
        for user_id, annotation in annotations.items():
            user = User.objects.get(pk=user_id)
            return_html += f"<h6>User: {user.username}</h6>"
            return_html += "<ul>"
            for annotation_key, annotation_value in annotation.items():
                return_html += f"<li>{annotation_key}: {annotation_value}</li>"
            return_html += "</ul>"
            return_html += "<hr>"
        return_html += "</div>"
        return mark_safe(return_html)

    list_display = (
        "id",
        "audio__time_range",
        "video__time_range",
    )
    exclude = (
        "audio",
        "video",
        "text",
        "annotations",
    )
    search_fields = (
        "text__text",
        "res_text__text",
        "track_id",
        "text",
    )
    readonly_fields = (
        # "track_id",
        "play_audio",
        "audio__time_range",
        "speech_to_text",
        "play_video",
        "video__time_range",
        "response_text",
        "play_res_speech",
        "created_at",
        "updated_at",
        "annotation_records",
    )
    list_filter = ("created_at", ClusterFilter)

    change_form_template = "admin/hardware/conversation/change_form.html"

    def response_change(self, request, obj):
        if "_saveandnext" in request.POST:
            next_obj = self.get_next_obj(obj)
            if next_obj:
                return HttpResponseRedirect(
                    reverse(
                        "admin:%s_%s_change"
                        % (
                            obj._meta.app_label,
                            obj._meta.model_name,
                        ),
                        args=[next_obj.pk],
                    )
                )
        return super().response_change(request, obj)

    def get_next_obj(self, obj):
        # Define your logic to get the next object
        # use self model to get the next object
        obj_model = obj.__class__
        next_obj = obj_model.objects.filter(pk__gt=obj.pk).order_by("pk").first()
        return next_obj

    def change_view(self, request, object_id, form_url="", extra_context=None):
        if extra_context is None:
            extra_context = {}

        extra_context["additional_save_buttons"] = [
            {"name": "_saveandnext", "value": "Save and Next"}
        ]

        return super().change_view(request, object_id, form_url, extra_context)

    def get_form(self, request, *args, **kwargs):
        form = super().get_form(request, *args, **kwargs)
        form.current_user = request.user
        return form

    def save_model(self, request, obj, form, change):
        annotation_data = {}
        for key, value in form.cleaned_data.items():
            if key.startswith("annotation_"):
                annotation_data[key] = value

        if not obj.annotations:
            obj.annotations = {}
        current_annotations = obj.annotations.get(request.user.id, {})
        obj.annotations[request.user.id] = {
            **annotation_data,
            **current_annotations,
        }

        super().save_model(request, obj, form, change)