Skip to content

Commit

Permalink
Merge pull request #26 from acdh-oeaw/feature/crosslink-tei
Browse files Browse the repository at this point in the history
Feature/crosslink tei
  • Loading branch information
gythaogg authored May 21, 2024
2 parents a19f832 + 2869c32 commit 4377251
Show file tree
Hide file tree
Showing 17 changed files with 1,906 additions and 16 deletions.
30 changes: 30 additions & 0 deletions apis_ontology/management/commands/import_excerpts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import logging
from apis_ontology.models import Excerpts
import pandas as pd
from django.apps import apps
from django.core.management.base import BaseCommand
from tqdm.auto import tqdm

logger = logging.getLogger(__name__)


class Command(BaseCommand):
"""
Imports excerpts from data/excerpts.csv
"""

def handle(self, *args, **kwargs):
def create_record(row):
record, _ = Excerpts.objects.get_or_create(xml_id=row.xml_id)
record.xml_content = row.xml_content
record.source = row.source
record.save()

print(len(Excerpts.objects.all()))
import_file = "data/excerpts.csv"
df = pd.read_csv(import_file)
for _, row in tqdm(df.iterrows(), total=df.shape[0]):
create_record(row)

self.stdout.write(self.style.SUCCESS(f"Processed {df.shape[0]} excerpts."))
print(len(Excerpts.objects.all()))
31 changes: 31 additions & 0 deletions apis_ontology/migrations/0009_excerpts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 4.2.13 on 2024-05-19 00:22

import apis_core.generic.abc
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("apis_ontology", "0008_instancecopiedwrittendownatplace_and_more"),
]

operations = [
migrations.CreateModel(
name="Excerpts",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("xml_id", models.CharField(max_length=255, unique=True)),
("xml_content", models.TextField()),
("source", models.CharField(max_length=255, unique=True)),
],
bases=(apis_core.generic.abc.GenericModel, models.Model),
),
]
17 changes: 17 additions & 0 deletions apis_ontology/migrations/0010_alter_excerpts_source.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.13 on 2024-05-19 00:42

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("apis_ontology", "0009_excerpts"),
]

operations = [
migrations.AlterField(
model_name="excerpts",
name="source",
field=models.CharField(max_length=255),
),
]
6 changes: 6 additions & 0 deletions apis_ontology/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,12 @@ class ZoteroEntry(GenericModel, models.Model):
)


class Excerpts(GenericModel, models.Model):
xml_id = models.CharField(max_length=255, unique=True)
xml_content = models.TextField()
source = models.CharField(max_length=255) # the TEI file source


#######################################################################################
###################################RELATIONS###########################################
#######################################################################################
Expand Down
17 changes: 17 additions & 0 deletions apis_ontology/static/scripts/show_popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
function showPopup(recordId, renderStyle) {
renderStyle = "tei";
fetch(`/apis/excerpts/${recordId}/${renderStyle}`)
.then(response => response.text())
.then(data => {
// Display the data in the popup
document.getElementById('popupContent').innerHTML = data;
document.getElementById('popupModal').style.display = 'block';
})
.catch(error => {
console.error('Error fetching dynamic content:', error);
});
}

function closePopup() {
document.getElementById('popupModal').style.display = 'none';
}
24 changes: 21 additions & 3 deletions apis_ontology/tables.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from django.utils.html import escape

import django_tables2 as tables
from apis_core.apis_entities.tables import AbstractEntityTable
from apis_core.generic.tables import GenericTable
from django_tables2.utils import A

from .models import Instance, Person, Place, TibScholRelationMixin, Work
from .models import Excerpts, Instance, Person, Place, TibScholRelationMixin, Work
from .templatetags.filter_utils import (
render_coordinate,
render_links,
Expand All @@ -18,6 +20,7 @@
from django.utils.safestring import mark_safe
from django.urls import reverse

from lxml import etree

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -109,6 +112,9 @@ class RelationsTable(GenericTable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Define the obj attribute based on the value of self.reverse
xslt_file = "apis_ontology/xslt/teibp.xsl"
xslt = etree.parse(xslt_file)
self.transform = etree.XSLT(xslt)

def render_name(self, record):
if self.context["object"].pk == record.subj.pk:
Expand Down Expand Up @@ -141,6 +147,18 @@ def render_obj(self, record):
+ "</a>"
)

def render_tei_refs(self, value):
delim = "\n" if "\n" in value else "," if "," in value else " "
xml_ids = value.split(delim)
links = []
for xml_id in xml_ids:
true_id = xml_id.replace('"', "").replace("xml:id=", "").strip()
links.append(
f"""<a href="#" onclick="showPopup('{true_id}'); return false;">{true_id}</a>"""
)

return mark_safe("<br />".join(links))


class RelationsTableEdit(RelationsTable):
class Meta(GenericTable.Meta):
Expand All @@ -151,7 +169,7 @@ class Meta(GenericTable.Meta):
"obj",
"support_notes",
"zotero_refs",
"TEI",
"tei_refs",
"edit",
"delete",
]
Expand All @@ -175,6 +193,6 @@ class Meta(GenericTable.Meta):
"obj",
"support_notes",
"zotero_refs",
"TEI",
"tei_refs",
]
exclude = ["view", "edit", "desc", "delete", "subj"]
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
{% endblock col-zero %}

{% block col-one %}
{% include "excerpts/popup.html" %}

<h4>Relations</h4>
{% related_entity_types as related_entity_types %}
<div class="container">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{% load apiscore %}
{% load relationsng %}
{% load relations %}
{% include "excerpts/popup.html" %}

<h4>Relations</h4> <!-- Edit View -->
{% related_entity_types as related_entity_types %}
Expand Down
19 changes: 19 additions & 0 deletions apis_ontology/templates/excerpts/popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<script src="/static/scripts/show_popup.js"></script>

<div class="modal" id="popupModal" style="display:none;" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Excerpt</h5>
</div>
<div class="modal-body">

<span id="popupContent"></span>
</div>
<div class="modal-footer">

<button onclick="closePopup()">Close</button>
</div>
</div>
</div>
</div>
6 changes: 6 additions & 0 deletions apis_ontology/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from apis_ontology.views import ExcerptsView
from django.contrib import admin
from django.urls import include, path
from django.views.generic import TemplateView
Expand All @@ -13,6 +14,11 @@
path("accounts/", include("django.contrib.auth.urls")),
path("entity/<int:pk>/", GetEntityGeneric.as_view(), name="GetEntityGenericRoot"),
path("", TemplateView.as_view(template_name="base.html")),
path(
"apis/excerpts/<str:xml_id>/<str:render_style>/",
ExcerptsView.as_view(),
name="excerpts_view",
),
]

urlpatterns += staticfiles_urlpatterns()
Expand Down
19 changes: 19 additions & 0 deletions apis_ontology/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from django.http import HttpResponse
from django.views import View
from django.shortcuts import get_object_or_404
from .models import Excerpts


class ExcerptsView(View):
def get(self, request, xml_id, render_style, *args, **kwargs):
print("You are here!")
record = get_object_or_404(Excerpts, xml_id=xml_id)

# Generate dynamic content based on link_type
if render_style == "tei":
# TODO: render correctly with xslt
content = f"{record.xml_content}"
else:
content = f"{record.xml_content}"

return HttpResponse(content)
Loading

0 comments on commit 4377251

Please sign in to comment.