Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: get rid of text model remains #311

Merged
merged 1 commit into from
Oct 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
259 changes: 69 additions & 190 deletions apis_core/api_routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,6 @@ def generic_serializer_creation_factory():
for x in exclude_lst:
if x in entity_field_name_list:
exclude_lst_fin.append(x)
if entity_str.lower() == "text":
exclude_lst_fin.extend(["kind"])
for f in entity._meta.get_fields():
if f.__class__.__name__ == "ManyToManyField":
prefetch_rel.append(f.name)
Expand All @@ -273,167 +271,84 @@ class Meta:
def add_labels(self, obj):
return {"id": obj.pk, "label": str(obj)}

if entity_str.lower() == "text":

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._highlight = False
self.fields["kind"] = LabelSerializer(many=False, read_only=True)

else:

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
entity_str = self._entity.__name__
app_label = self._app_label
lst_labels_set = deep_get(
getattr(settings, app_label.upper(), {}),
"{}.labels".format(entity_str),
[],
)
for f in self._entity._meta.get_fields():
if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
f.name
).endswith("_set"):
if f.name in self.fields.keys():
self.fields.pop(f.name)
continue
ck_many = f.__class__.__name__ == "ManyToManyField"
if f.name in self._exclude_lst:
continue
elif f.__class__.__name__ in [
"ManyToManyField",
"ForeignKey",
"InheritanceForeignKey",
] and "apis_vocabularies" not in str(f.related_model):
self.fields[f.name] = ApisBaseSerializer(
many=ck_many, read_only=True
)
elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
self.fields[f.name] = LabelSerializer(
many=ck_many, read_only=True
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
entity_str = self._entity.__name__
app_label = self._app_label
lst_labels_set = deep_get(
getattr(settings, app_label.upper(), {}),
"{}.labels".format(entity_str),
[],
)
for f in self._entity._meta.get_fields():
if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
f.name
).endswith("_set"):
if f.name in self.fields.keys():
self.fields.pop(f.name)
continue
ck_many = f.__class__.__name__ == "ManyToManyField"
if f.name in self._exclude_lst:
continue
elif f.__class__.__name__ in [
"ManyToManyField",
"ForeignKey",
"InheritanceForeignKey",
] and "apis_vocabularies" not in str(f.related_model):
self.fields[f.name] = ApisBaseSerializer(
many=ck_many, read_only=True
)
elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
self.fields[f.name] = LabelSerializer(
many=ck_many, read_only=True
)

TemplateSerializer.__name__ = (
TemplateSerializer.__qualname__
) = f"{entity_str.title().replace(' ', '')}Serializer"

class TemplateSerializerRetrieve(TemplateSerializer):

if entity_str.lower() == "text":
text = serializers.SerializerMethodField(
method_name="txt_serializer_add_text"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
entity_str = self._entity.__name__
app_label = self._app_label
lst_labels_set = deep_get(
getattr(settings, app_label.upper(), {}),
"{}.labels".format(entity_str),
[],
)
if "apis_highlighter" in getattr(settings, "INSTALLED_APPS"):
annotations = serializers.SerializerMethodField(
method_name="txt_serializer_add_annotations"
)

@extend_schema_field(AnnotationSerializer(many=True))
def txt_serializer_add_annotations(self, instance):
if self._highlight:
return AnnotationSerializer(
self._annotations, context=self.context, many=True
).data
else:
return None

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
highlight = self.context.get("highlight", True)
self._inline_annotations = False
if highlight is not None and "apis_highlighter" in getattr(
settings, "INSTALLED_APPS"
for f in self._entity._meta.get_fields():
if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
f.name
).endswith("_set"):
if f.name in self.fields.keys():
self.fields.pop(f.name)
continue
ck_many = f.__class__.__name__ == "ManyToManyField"
if f.name in self._exclude_lst:
continue
elif f.__class__.__name__ in [
"ManyToManyField",
"ForeignKey",
] and "apis_vocabularies" not in str(f.related_model):
self.fields[f.name] = ApisBaseSerializer(
many=ck_many, read_only=True
)
elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
self.fields[f.name] = LabelSerializer(
many=ck_many, read_only=True
)
if len(args) > 0:
entity = args[0]
if hasattr(entity, "triple_set_from_subj") or hasattr(
entity, "triple_set_from_obj"
):
self._highlight = highlight
if self._highlight == "":
self._highlight = True
if not isinstance(self._highlight, bool):
if self._highlight.lower() == "false":
self._highlight = False
self._ann_proj_pk = self.context.get("ann_proj_pk", None)
self._types = self.context.get("types", None)
self._users_show = self.context.get("users_show", None)
self._inline_annotations = self.context.get(
"inline_annotations", True
self.fields["relations"] = RelatedTripleSerializer(
read_only=True,
source="get_triples",
many=True,
pk_instance=entity.pk,
)
if not isinstance(self._inline_annotations, bool):
if self._inline_annotations.lower() == "false":
self._inline_annotations = False
elif self._inline_annotations.lower() == "true":
self._inline_annotations = True
try:
self._txt_html, self._annotations = highlight_text_new(
self.instance,
set_ann_proj=self._ann_proj_pk,
types=self._types,
users_show=self._users_show,
inline_annotations=self._inline_annotations,
)
qs_an = {"text": self.instance}
if self._users_show is not None:
qs_an["users_added__in"] = self._users_show
if self._ann_proj_pk is not None:
qs_an["annotation_project_id"] = self._ann_proj_pk
# self._annotations = Annotation.objects.filter(
# **qs_an
# ) # FIXME: Currently this QS is called twice (highlight_text_new)
except Exception as e:
self._txt_html = ""
self._annotations = []
else:
self._highlight = False
self.fields["kind"] = LabelSerializer(many=False, read_only=True)

def txt_serializer_add_text(self, instance):
if self._inline_annotations:
return self._txt_html
else:
return instance.text

else:

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
entity_str = self._entity.__name__
app_label = self._app_label
lst_labels_set = deep_get(
getattr(settings, app_label.upper(), {}),
"{}.labels".format(entity_str),
[],
)
for f in self._entity._meta.get_fields():
if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
f.name
).endswith("_set"):
if f.name in self.fields.keys():
self.fields.pop(f.name)
continue
ck_many = f.__class__.__name__ == "ManyToManyField"
if f.name in self._exclude_lst:
continue
elif f.__class__.__name__ in [
"ManyToManyField",
"ForeignKey",
] and "apis_vocabularies" not in str(f.related_model):
self.fields[f.name] = ApisBaseSerializer(
many=ck_many, read_only=True
)
elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
self.fields[f.name] = LabelSerializer(
many=ck_many, read_only=True
)
if len(args) > 0:
entity = args[0]
if hasattr(entity, "triple_set_from_subj") or hasattr(
entity, "triple_set_from_obj"
):
self.fields["relations"] = RelatedTripleSerializer(
read_only=True,
source="get_triples",
many=True,
pk_instance=entity.pk,
)

TemplateSerializerRetrieve.__name__ = (
TemplateSerializerRetrieve.__qualname__
Expand Down Expand Up @@ -555,42 +470,6 @@ def list_viewset(self, request):
def dispatch(self, request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)

if entity_str.lower() == "text":

@extend_schema(
parameters=[
OpenApiParameter(
name="highlight",
description="Whether to add annotations or not, defaults to true",
type=OpenApiTypes.BOOL,
),
OpenApiParameter(
name="inline_annotations",
description="Whether to add html5 mark tags for annotations to the text, defaults to false",
type=OpenApiTypes.BOOL,
),
OpenApiParameter(
name="ann_proj_pk",
description="PK of the annotation project to use for annotations",
type=OpenApiTypes.INT,
),
OpenApiParameter(
name="types",
description="Content type pks of annotation types to show. E.g. PersonPlace relations (comma sperated list)",
type=OpenApiTypes.STR,
),
OpenApiParameter(
name="users_show",
description="Filter annotations for users. PKs of users, comma seperated list",
type=OpenApiTypes.STR,
),
],
responses={200: TemplateSerializerRetrieve},
)
def retrieve(self, request, pk=None):
res = super(self.__class__, self).retrieve(request, pk=pk)
return res

TemplateViewSet.__name__ = (
TemplateViewSet.__qualname__
) = f"Generic{entity_str.title().replace(' ', '')}ViewSet"
Expand Down