import re

from rest_framework import serializers

from . import mixins, models

class BaseMediaFileSerializer(serializers.Serializer):
id = serializers.IntegerField()
file_name = serializers.CharField(max_length=1000)
file_path = serializers.CharField(max_length=1000, source="file_path.url")

class AudioFileSerializer(BaseMediaFileSerializer):
duration = serializers.IntegerField()

class VideoFileSerializer(AudioFileSerializer):
frame_rate = serializers.IntegerField()

class BaseMaterialList(mixins.MaterialCreationDateMixinSerializer):
annotation = serializers.SerializerMethodField(label="Аннотация")


@staticmethod
def get_annotation(instance):
    max_tokens = 11
    if instance.annotation:
        tokens = re.findall(r"\S+", instance.annotation)
        annotation = " ".join(tokens[:max_tokens])
        annotation += " ..." if len(tokens) > max_tokens else ""
        return annotation
class ImageMaterialListSerializer(BaseMaterialList, serializers.ModelSerializer):
class Meta:
model = models.ImageMaterial
fields = ("id", "annotation", "persons", "creation_place", "creation_date", "author")

class AudioMaterialListSerializer(BaseMaterialList, serializers.ModelSerializer):
class Meta:
model = models.AudioMaterial
fields = (
"id",
"title",
"annotation",
"text_author",
"performer",
"music_author",
"creation_date",
"creation_place",
)

class VideoMaterialListSerializer(BaseMaterialList, serializers.ModelSerializer):
class Meta:
model = models.VideoMaterial
fields = ("id", "title", "annotation", "roles", "director", "studio", "creation_date", "creation_place")

class BaseMaterialDetailSerializer(
mixins.ToRepresentationMixinSerializer,
mixins.MaterialCreationDateMixinSerializer,
):
media_files = BaseMediaFileSerializer(many=True)

class VideoMaterialDetailSerializer(BaseMaterialDetailSerializer):
media_files = VideoFileSerializer(many=True)


class Meta:
    model = models.VideoMaterial
    fields = (
        "title",
        "keywords",
        "annotation",
        "persons",
        "description",
        "montage_sheet",
        "roles",
        "scriptwriter",
        "director",
        "cameraman",
        "sound_engineer",
        "painter",
        "composer",
        "studio",
        "role_dubbing",
        "video_creators",
        "creation_date",
        "creation_date_comment",
        "literature_source",
        "creation_place",
        "receive_date",
        "video_type",
        "color",
        "language",
        "voice_type",
        "source",
        "founder",
        "archive_number",
        "media_files",
    )
class AudioMaterialDetailSerializer(BaseMaterialDetailSerializer):
media_files = AudioFileSerializer(many=True)


class Meta:
    model = models.AudioMaterial
    fields = (
        "title",
        "keywords",
        "annotation",
        "text_author",
        "performer",
        "persons",
        "music_author",
        "arrangement",
        "conductor",
        "art_director",
        "source",
        "founder",
        "language",
        "choir",
        "orchestra",
        "receive_date",
        "creation_date",
        "creation_date_comment",
        "creation_place",
        "montage_sheet",
        "archive_number",
        "media_files",
    )
class ImageMaterialDetailSerializer(BaseMaterialDetailSerializer):
class Meta:
model = models.ImageMaterial
fields = (
"annotation",
"keywords",
"persons",
"creation_place",
"creation_date",
"creation_date_comment",
"author",
"source",
"founder",
"receive_date",
"photo_type",
"color",
"archive_number",
"media_files",
)
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework.response import Response

from backend.apps.core import metadata as core_metadata
from backend.apps.core import views as core_views

from . import models, serializers

class BaseMaterialViewSet(core_views.BaseReadOnlyModelViewSet):
metadata_class = core_metadata.MaterialGetRequestMetadata


def get_common_search_lookup(self, common_search_value):
    lookup = Q()
    for field in self.common_search_fields:
        lookup |= Q(**{f"{field}__icontains": common_search_value})
    return lookup

def get_queryset(self):
    queryset = super().get_queryset()
    common_search_query = self.request.GET.get("common_search_query")
    if common_search_query:
        query_lookup = self.get_common_search_lookup(common_search_query)
        return queryset.filter(query_lookup)
    return queryset

def list(self, request, *args, **kwargs):
    queryset = self.get_queryset()
    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
    serializer = self.get_serializer(self.queryset, many=True)
    return self.get_paginated_response(serializer.data) if page is not None else Response(serializer.data)
class AudioMaterialViewSet(BaseMaterialViewSet):
queryset = models.AudioMaterial.objects.all()
serializer_class = serializers.AudioMaterialListSerializer
serializer_classes = {
"retrieve": serializers.AudioMaterialDetailSerializer,
}
common_search_fields = ["keywords", "annotation", "persons", "title"]

class ImageMaterialViewSet(BaseMaterialViewSet):
queryset = models.ImageMaterial.objects.all()
serializer_class = serializers.ImageMaterialListSerializer
serializer_classes = {
"retrieve": serializers.ImageMaterialDetailSerializer,
}
common_search_fields = ["keywords", "annotation", "persons", "author"]


def get_queryset(self):
    queryset = super().get_queryset()

    # Handle common search query first
    common_search_query = self.request.GET.get("common_search_query")
    if common_search_query:
        query_lookup = self.get_common_search_lookup(common_search_query)
        queryset = queryset.filter(query_lookup)

    # Handle advanced search parameters
    keywords = self.request.GET.get('keywords')
    persons = self.request.GET.get('persons')
    annotation = self.request.GET.get('annotation')
    creation_date_from = self.request.GET.get('creation_date_from')
    creation_date_to = self.request.GET.get('creation_date_to')
    creation_place = self.request.GET.get('creation_place')
    author = self.request.GET.get('author')

    if keywords:
        queryset = queryset.filter(keywords__icontains=keywords)
    if persons:
        queryset = queryset.filter(persons__icontains=persons)
    if annotation:
        queryset = queryset.filter(annotation__icontains=annotation)
    if creation_date_from:
        queryset = queryset.filter(creation_date__gte=creation_date_from)
    if creation_date_to:
        queryset = queryset.filter(creation_date__lte=creation_date_to)
    if creation_place:
        queryset = queryset.filter(creation_place__icontains=creation_place)
    if author:
        queryset = queryset.filter(author__icontains=author)

    return queryset
class VideoMaterialViewSet(BaseMaterialViewSet):
queryset = models.VideoMaterial.objects.all()
serializer_class = serializers.VideoMaterialListSerializer
serializer_classes = {
"retrieve": serializers.VideoMaterialDetailSerializer,
}
common_search_fields = ["keywords", "annotation", "persons", "title", "description"]

def get_video_url(request, video_id):
video = get_object_or_404(models.VideoFile, id=video_id)
return JsonResponse({"url": video.file_path.url})

def get_audio_url(request, audio_id):
audio = get_object_or_404(models.AudioFile, id=audio_id)
return JsonResponse({"url": audio.file_path.url})

def get_image_url(request, image_id):
image = get_object_or_404(models.ImageFile, id=image_id)
return JsonResponse({"url": image.file_path.url})
from django.urls import path
from rest_framework.routers import DefaultRouter

from . import views

router = DefaultRouter()
router.register(r"audio-materials", views.AudioMaterialViewSet, basename="audio-materials")
router.register(r"image-materials", views.ImageMaterialViewSet, basename="image-materials")
router.register(r"video-materials", views.VideoMaterialViewSet, basename="video-materials")

urlpatterns = [
path("get-video-url/int:video_id/", views.get_video_url, name="get_video_url"),
path("get-audio-url/int:audio_id/", views.get_audio_url, name="get_audio_url"),
path("get-image-url/int:image_id/", views.get_image_url, name="get_image_url"),
*router.urls,
]

can u modify this code by creating a separate filters.py file that make imagematerial filter mechanism? (make it mechanism very short and simple, for example like in this from django.contrib.contenttypes.models import ContentType
from django.db.models import Subquery
from django.utils.functional import lazy
from ww_filters import filter_collections as collections
from ww_filters import filters, updaters
from ww_filters.filters import BaseModelMultiChoiceFilter, Filter

from apps.directory import models
from apps.route import models as route_models

class DirStatusBooleanFilter(Filter):
true = updaters.TrueBoolean("Активен")
false = updaters.FalseBoolean("Не активен")

class DirectoryStatusFilterMixin(collections.ModelFilterCollection):
dir_status = DirStatusBooleanFilter("Статус")

class EPKFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.EPK
fields = ("code", "name", "master_id", "parent", "start_date", "end_date")

class ControlLevelFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.ControlLevel
fields = ("code", "name", "start_date", "end_date")

class LawPublisherFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.LawPublisher
fields = ("code", "name_ru", "name_by", "master_id")

class MemberFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Member
fields = (
"code",
"name",
"control_level",
"start_date",
"end_date",
"subject_legislative_initiative",
"rule_making",
)
titles = {"control_level": "Уровень участника системы"}

class DepartmentFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Department
fields = ("code", "name", "start_date", "end_date")

class SubDepartmentFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Department
fields = ("code", "name", "start_date", "end_date")

class GlobalStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.GlobalStage
fields = ("code", "name", "start_date", "end_date")

class ActKindFilterForm(collections.ModelFilterCollection):
name_by = filters.BaseStringFilter("Наименование белорусское")


class Meta:
    model = models.ActKind
    fields = ("code", "name_ru", "name_by", "master_id")
class DocTypeFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.DocType
fields = ("name", "start_date", "end_date")

class ActTypeFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.ActType
fields = ("name", "act_kind", "act_category", "dir_status")

class NpStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.NpStage
fields = ("code", "name", "type", "start_date", "end_date")

class NpStatusFilterForm(DirectoryStatusFilterMixin):
np_stage = filters.BaseModelMultiChoiceFilter("Стадия НП/ЗП", queryset=models.NpStage.objects.all())


class Meta:
    model = models.NpStatus
    fields = ("name", "np_stage", "dir_status")
class AgreeStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.AgreeStage
fields = ("code", "name", "start_date", "end_date", "master_id")

class AgreeTypeFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.AgreeType
fields = ("code", "name", "start_date", "end_date")

class PostFilterForm(DirectoryStatusFilterMixin):
member = filters.ModelMultiChoiceFilterWithEmpty(
title="Участник системы", queryset=models.Member.active_objects.all()
)


class Meta:
    model = models.Post
    fields = ("name", "member", "dir_status")
class MinisterFilterForm(DirectoryStatusFilterMixin):
minister_user__member = filters.ModelMultiChoiceFilterWithEmpty(
title="Участник системы", queryset=models.Member.objects.all()
)


class Meta:
    model = models.Minister
    fields = ("minister_user", "dir_status", "minister_user__member")
class RiskGroupFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.RiskGroup
fields = ("name", "dir_status")

class RiskFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.Risk
fields = ("name", "risk_group", "dir_status")

class ActionFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Action
fields = ("name",)
class RubricatorFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Rubricator
fields = ("code", "name", "start_date", "end_date")

class AcceptStageFilterForm(DirectoryStatusFilterMixin):
np_stage = filters.BaseModelMultiChoiceFilter("Стадия НП/ЗП", queryset=models.NpStage.objects.all())


class Meta:
    model = models.AcceptStage
    fields = ("np_stage", "name", "dir_status")
class FunctionalBlockFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.FunctionalBlock
fields = ("name",)

class RejectionReasonFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.RejectionReason
fields = ("name", "start_date", "end_date", "dir_status")

class RecomendationFilterForm(collections.ModelFilterCollection):
stage = filters.ModelMultiChoiceFilterWithEmpty(title="Этап", queryset=models.ActStage.active_objects.all())


class Meta:
    model = models.Recomendation
    fields = ("act_kind", "group_member", "stage")
def get_directories_choices():
content_type_objs = ContentType.objects.filter(
id__in=Subquery(models.DownloadLog.objects.values_list("directory_model_id", flat=True).distinct())
)
sorted_content_types = sorted(
content_type_objs, key=lambda content_type: content_type.model_class()._meta.verbose_name
)
return [(content_type.id, content_type.model_class()._meta.verbose_name) for content_type in sorted_content_types]

class DownloadLogFilterForm(collections.ModelFilterCollection):
directory_model_id = filters.MultiChoiceFilterWithEmpty(
choices=lazy(get_directories_choices, list)(), title="Наименование справочника"
)


class Meta:
    model = models.DownloadLog
    fields = ("directory_model_id", "start_download", "upload_status", "user")
class PatternsFilterForm(collections.ModelFilterCollection):
member = filters.ModelMultiChoiceFilterWithEmpty(
title="Участник системы", queryset=models.Member.active_objects.all()
)


class Meta:
    model = models.Patterns
    fields = ("member", "doc_type", "doc_attr", "start_date", "end_date")
class SpecialistsFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.Specialists
fields = ("name", "dir_status")

class DeadlinesExaminationsFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.DeadlinesExaminations
fields = ("stage", "members", "type_days", "term", "agree_type")

class DeadlinesFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.Deadlines
fields = ("stage", "type_days", "term", "agree_type")

class CardStatusFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.CardStatus
fields = ("name", "dir_status")

class ActStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.ActStage
fields = ("name",)

class MultiActCategoryFilter(BaseModelMultiChoiceFilter):
def update_qs(self, qs, name, data=None, initial=None):
if data is not None:
data_name = "_".join([name, "filter"])
if data_name in data:
qs = qs.filter(act_type__act_category__id__in=data["act_category_filter_choice_multi-value"].split(","))
return qs

class TemplatesDocumentsFilterForm(DirectoryStatusFilterMixin):
created_at = filters.BaseDateTimeFilter("Дата загрузки")


class Meta:
    model = models.TemplatesDocuments
    fields = ("name", "language", "act_kind", "created_at", "dir_status")
class LetterTemplatesFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.LetterTemplates
fields = ("name", "type_doc", "dir_status", "language")

class SettingsMotionFilterForm(collections.ModelFilterCollection):
route = filters.ModelMultiChoiceFilterWithEmpty(
title="Маршрут", queryset=route_models.Route.active_objects.filter(is_copy=False)
)
group_members = filters.ModelMultiChoiceFilterWithEmpty(
title="Группировка участников", queryset=models.GroupMembers.active_objects.all()
)


class Meta:
    model = models.MotionSettings

    fields = ("stage_sender", "route", "group_members", "members")
class SettingsRequiredDocumentsFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.SettingsRequiredDocuments
fields = ("receive_type_of_stage", "send_type_of_stage", "act_kind")

class SettingsOpenStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.SettingsOpenStage
fields = (
"type_of_stage",
"created_at",
"user",
)

class SettingsCompleteStageFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.SettingsCompleteStage
fields = (
"is_active",
"type_of_stage",
"availability_of_special_doc_type",
"presence_type_of_stage_closing_next",
"type_of_stage_closing_next",
)

class LearningSubSectionFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.LearningSubSection
fields = ("name", "learning_section", "dir_status")

class LearningSectionFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.LearningSection
fields = ("name", "dir_status")

class MemberRolesFilterForm(DirectoryStatusFilterMixin):
class Meta:
model = models.MemberRoles
fields = ("member", "dir_status")

class LegalExaminationInitialDataSettingsFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.LegalExaminationInitialDataSettings
fields = ("stage", "action", "legal_managements")

class OtherInitialDataSettingsFilterForm(collections.ModelFilterCollection):
class Meta:
model = models.OtherInitialDataSettings
fields = ("action", "stage", "send_members") (IT JUST EXAMPLE, I DON'T HAVE WW_FILTERS)