Skip to content

Commit

Permalink
Add labels for documents
Browse files Browse the repository at this point in the history
  • Loading branch information
nickmwangemi committed Jul 27, 2023
1 parent fd19816 commit 19d4ae6
Show file tree
Hide file tree
Showing 10 changed files with 4,087 additions and 14 deletions.
27 changes: 25 additions & 2 deletions peachjam/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
Journal,
Judge,
Judgment,
Label,
LegalInstrument,
Legislation,
Locality,
Expand Down Expand Up @@ -317,7 +318,12 @@ class DocumentAdmin(admin.ModelAdmin):
exclude = ("doc_type",)
date_hierarchy = "date"
prepopulated_fields = {"frbr_uri_number": ("title",)}
actions = ["extract_citations", "reextract_content", "reindex_for_search"]
actions = [
"extract_citations",
"reextract_content",
"reindex_for_search",
"apply_labels",
]

fieldsets = [
(
Expand Down Expand Up @@ -492,14 +498,25 @@ def reextract_content(self, request, queryset):
reextract_content.short_description = "Re-extract content from DOCX files"

def reindex_for_search(self, request, queryset):
"""Setup a background task to re-index documents for search."""
"""Set up a background task to re-index documents for search."""
count = queryset.count()
for doc in queryset:
search_model_saved(doc._meta.label, doc.pk)
self.message_user(request, f"Queued tasks to re-index for {count} documents.")

reindex_for_search.short_description = "Re-index for search (background)"

def apply_labels(self, request, queryset):
"""Set up a background task to apply labels to documents."""
count = queryset.count()
for doc in queryset:
doc.apply_labels()
self.message_user(
request, f"Applying labels in the background for {count} documents."
)

apply_labels.short_description = "Apply labels"

def has_delete_permission(self, request, obj=None):
if obj:
if (
Expand Down Expand Up @@ -854,6 +871,12 @@ class UserAdminCustom(ImportExportMixin, UserAdmin):
resource_class = UserResource


@admin.register(Label)
class LabelAdmin(admin.ModelAdmin):
list_display = ("name", "code")
prepopulated_fields = {"code": ("name",)}


admin.site.register(
[
Locality,
Expand Down
42 changes: 42 additions & 0 deletions peachjam/migrations/0093_add_model_labels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Generated by Django 3.2.19 on 2023-07-25 14:19

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("peachjam", "0092_documentcontent_content_xml"),
]

operations = [
migrations.CreateModel(
name="Label",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"name",
models.CharField(max_length=1024, unique=True, verbose_name="name"),
),
(
"code",
models.SlugField(max_length=1024, unique=True, verbose_name="code"),
),
],
),
migrations.AddField(
model_name="coredocument",
name="labels",
field=models.ManyToManyField(
blank=True, to="peachjam.Label", verbose_name="labels"
),
),
]
35 changes: 26 additions & 9 deletions peachjam/models/core_document_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,24 @@


class Label(models.Model):
name = models.CharField(_("name"), max_length=255, unique=True)
code = models.SlugField(_("code"), max_length=255, unique=True)
name = models.CharField(
_("name"), max_length=1024, unique=True, null=False, blank=False
)
code = models.SlugField(_("code"), max_length=1024, unique=True)

def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
if not self.code:
self.code = slugify(self.name)
return super().save(*args, **kwargs)

class Meta:
verbose_name = _("label")
verbose_name_plural = _("labels")
ordering = ["name"]

def __str__(self):
return f"{self.name}"


class DocumentNature(models.Model):
name = models.CharField(
Expand Down Expand Up @@ -407,7 +417,7 @@ class CoreDocument(PolymorphicModel):

# options for the FRBR URI doctypes
frbr_uri_doctypes = FRBR_URI_DOCTYPES
labels = models.ManyToManyField(Label, verbose_name=_("labels"))
labels = models.ManyToManyField(Label, verbose_name=_("labels"), blank=True)

class Meta:
ordering = ["doc_type", "title"]
Expand All @@ -419,6 +429,9 @@ class Meta:
def __str__(self):
return f"{self.doc_type} - {self.title}"

def apply_labels(self):
pass

def get_all_fields(self):
return self._meta.get_fields()

Expand Down Expand Up @@ -517,10 +530,14 @@ def pre_save(self):
self.work.save()

def save(self, *args, **kwargs):
# give ourselves and subclasses a chance to pre-populate derived fields before saving, in case full_clean() has
# not yet been called
self.pre_save()
return super().save(*args, **kwargs)
try:
# give ourselves and subclasses a chance to pre-populate derived fields before saving,
# in case full_clean() has not yet been called
self.pre_save()
return super().save(*args, **kwargs)
finally:
# apply labels
self.apply_labels()

@cached_property
def relationships_as_subject(self):
Expand Down
15 changes: 15 additions & 0 deletions peachjam/models/generic_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
CoreDocument,
CoreDocumentManager,
CoreDocumentQuerySet,
Label,
Work,
)
from peachjam.models.author import Author
Expand Down Expand Up @@ -85,6 +86,20 @@ class Meta(CoreDocument.Meta):
def __str__(self):
return self.title

def apply_labels(self):
# label to indicate that this legislation is repealed
label, _ = Label.objects.get_or_create(
code="repealed", defaults={"name": "Repealed", "code": "repealed"}
)
# apply label if repealed
if self.repealed:
self.labels.add(label.pk)
else:
# not repealed, remove label
self.labels.remove(label.pk)

super().apply_labels()

def pre_save(self):
self.doc_type = "legislation"
return super().pre_save()
17 changes: 16 additions & 1 deletion peachjam/models/judgment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from django.utils.translation import gettext_lazy as _
from django.utils.translation import override as lang_override

from peachjam.models import CoreDocument
from peachjam.models import CoreDocument, Label


class Attorney(models.Model):
Expand Down Expand Up @@ -284,6 +284,21 @@ def assign_title(self):
self.title = " ".join(parts)
self.citation = self.title

def apply_labels(self):
"""Apply labels to this judgment based on its properties."""
# label showing that a judgment is cited/reported in law reports, hence "more important"
label, _ = Label.objects.get_or_create(
code="reported",
defaults={"name": "Reported", "code": "reported"},
)

# if the judgment has alternative_names, apply the "reported" label
if self.alternative_names.exists():
self.labels.add(label.pk)
# if the judgment no alternative_names, remove the "reported" label
else:
self.labels.remove(label.pk)

def pre_save(self):
# ensure registry aligns to the court
if self.registry:
Expand Down
3,934 changes: 3,932 additions & 2 deletions peachjam/static/js/app-prod.js

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions peachjam/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ def extract_citations(document_id):
log.info("Citations extracted")


@background(queue="peachjam", remove_existing_tasks=True)
def apply_labels(document_id):
"""Applying labels for a document in the background."""

log.info(f"Applying labels for document {document_id}")

doc = CoreDocument.objects.filter(pk=document_id).first()
if not doc:
log.info(f"No document with id {document_id} exists, ignoring.")
return

try:
if doc.apply_labels():
doc.save()
except Exception as e:
log.error(f"Error applying labels for {doc}", exc_info=e)
raise

log.info("Labels applied")


@background(queue="peachjam", schedule=60, remove_existing_tasks=True)
def update_extracted_citations_for_a_work(work_id):
"""Update Extracted Citations for a work."""
Expand Down
8 changes: 8 additions & 0 deletions peachjam/templates/peachjam/_labels.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% if labels %}
<div class="d-flex align-items-center">
{% for label in labels %}
{% if label.code == "repealed" %}<span class="badge rounded-pill bg-danger">{{ label.name }}</span>{% endif %}
{% if label.code == "reported" %}<span class="badge rounded-pill bg-success">{{ label.name }}</span>{% endif %}
{% endfor %}
</div>
{% endif %}
1 change: 1 addition & 0 deletions peachjam/templates/peachjam/layouts/document_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
{% block document-title %}
<div class="d-md-flex justify-content-md-between py-4">
<h1>{{ document.title }}</h1>
{% include 'peachjam/_labels.html' %}
<div class="d-flex align-items-center">
<a href="https://api.whatsapp.com/send?text={{ request.build_absolute_uri }}"
class="btn btn-link"
Expand Down
1 change: 1 addition & 0 deletions peachjam/views/generic_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ def get_context_data(self, **kwargs):
context["cited_documents_count"]
+ context["documents_citing_current_doc_count"]
)
context["labels"] = doc.labels.all()

return context

Expand Down

0 comments on commit 19d4ae6

Please sign in to comment.