Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • arkindex/backend
1 result
Show changes
Commits on Source (82)
Showing with 1741 additions and 1216 deletions
......@@ -2,6 +2,9 @@
.git
.eggs
*.egg
logs
**/__pycache__/
**/*.pyc
docker/
Makefile
test-report.xml
arkindex/config.yml
......@@ -5,3 +5,4 @@ exclude=build,.cache,.eggs,.git,src,arkindex/*/migrations/0001_initial.py
# the only interesting ignore is W503, which goes against PEP8.
# See https://lintlyci.github.io/Flake8Rules/rules/W503.html
ignore = E203,E501,W503
inline-quotes = "
......@@ -16,3 +16,4 @@ htmlcov
*.key
arkindex/config.yml
test-report.xml
docker/ssl/*.pem
......@@ -18,10 +18,8 @@ include:
- .cache/pip
before_script:
# Custom line to install our own deps from Git using GitLab CI credentials
- "pip install -e git+https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.teklia.com/arkindex/license#egg=teklia-license"
- pip install -r tests-requirements.txt
- "echo 'database: {host: postgres, port: 5432}\npublic_hostname: http://ci.arkindex.localhost' > $CONFIG_PATH"
- "echo database: {host: postgres, port: 5432} > $CONFIG_PATH"
- pip install -e .[test]
# Those jobs require the base image; they might fail if the image is not up to date.
# Allow them to fail when building a new base image, to prevent them from blocking a new base image build
......@@ -60,7 +58,7 @@ backend-tests:
- test-report.xml
script:
- python3 setup.py test
- arkindex test
backend-lint:
image: python:3.10
......@@ -93,8 +91,7 @@ backend-migrations:
alias: postgres
script:
- pip install -e .
- arkindex/manage.py makemigrations --check --noinput --dry-run -v 3
- arkindex makemigrations --check --noinput --dry-run -v 3
backend-openapi:
extends: .backend-setup
......@@ -156,29 +153,7 @@ backend-build:
- when: never
script:
- ci/build.sh Dockerfile
backend-build-binary-docker:
stage: build
image: docker:19.03.1
services:
- docker:dind
variables:
DOCKER_DRIVER: overlay2
DOCKER_HOST: tcp://docker:2375/
# Run this on master and tags except base tags and schedules
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: never
- if: '$CI_COMMIT_BRANCH == "master"'
when: on_success
- if: '$CI_COMMIT_TAG && $CI_COMMIT_TAG !~ /^base-.*/'
when: on_success
- when: never
script:
- ci/build.sh Dockerfile.binary "-binary"
- ci/build.sh
# Make sure arkindex is always compatible with Nuitka
backend-build-binary:
......
......@@ -10,6 +10,12 @@ repos:
additional_dependencies:
- 'flake8-copyright==0.2.2'
- 'flake8-debugger==3.1.0'
- 'flake8-quotes==3.3.2'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.11
hooks:
- id: ruff
args: [--fix]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
......
......@@ -6,19 +6,6 @@ ADD . build
RUN cd build && python3 setup.py sdist
FROM registry.gitlab.teklia.com/arkindex/backend/base:gitlab-teklia
ARG LICENSE_BRANCH=master
ARG LICENSE_ID=37
# Auth token expires on 01/07/2024
ARG GITLAB_TOKEN="glpat-3sBZPFgkZbqJxfSqjcAa"
# Install teklia-license from private repo
RUN \
mkdir /tmp/teklia-license && \
wget --header "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.teklia.com/api/v4/projects/$LICENSE_ID/repository/archive.tar.gz?sha=$LICENSE_BRANCH -O /tmp/teklia-license.tar.gz && \
tar --strip-components=1 -xvf /tmp/teklia-license.tar.gz -C /tmp/teklia-license && \
cd /tmp/teklia-license && pip install --disable-pip-version-check --no-cache-dir --quiet . && \
rm -rf /tmp/teklia-license
# Install arkindex and its deps
# Uses a source archive instead of full local copy to speedup docker build
......@@ -32,10 +19,13 @@ RUN chown -R ark:teklia /backend_static
# Copy Version file
COPY VERSION /etc/arkindex.version
HEALTHCHECK --start-period=1m --interval=1m --timeout=5s \
CMD wget --spider --quiet http://localhost/api/v1/public-key/ || exit 1
ENV PORT 8000
HEALTHCHECK --start-period=10s --interval=30s --timeout=5s \
CMD wget --spider --quiet http://localhost:$PORT/api/v1/corpus/ || exit 1
# Allow usage of django-admin by exposing our settings
ENV DJANGO_SETTINGS_MODULE "arkindex.project.settings"
# Run with Gunicorn
ENV PORT 8000
EXPOSE $PORT
CMD manage.py gunicorn --host=0.0.0.0 --port $PORT
CMD arkindex gunicorn --host=0.0.0.0 --port $PORT
# syntax=docker/dockerfile:1
FROM python:3.10-slim-bookworm AS compilation
RUN apt-get update && apt-get install --no-install-recommends -y build-essential wget
RUN pip install nuitka
ARG LICENSE_BRANCH=master
ARG LICENSE_ID=37
# Auth token expires on 01/07/2024
ARG GITLAB_TOKEN="glpat-3sBZPFgkZbqJxfSqjcAa"
# We build in /usr/share because Django will try to load some files relative to that path
# once executed in the binary (management commands, ...)
WORKDIR /usr/share
# Add our own source code
ADD arkindex /usr/share/arkindex
ADD base/requirements.txt /tmp/requirements-base-arkindex.txt
ADD requirements.txt /tmp/requirements-arkindex.txt
# Install teklia-license from private repo
RUN \
mkdir /tmp/teklia-license && \
wget --header "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.teklia.com/api/v4/projects/$LICENSE_ID/repository/archive.tar.gz?sha=$LICENSE_BRANCH -O /tmp/teklia-license.tar.gz && \
tar --strip-components=1 -xvf /tmp/teklia-license.tar.gz -C /tmp/teklia-license && \
mv /tmp/teklia-license/teklia_license /usr/share && \
cp /tmp/teklia-license/requirements.txt /tmp/requirements-license-arkindex.txt
# Build full requirements, removing relative or remote references to arkindex projects
RUN cat /tmp/requirements-*arkindex.txt | sort | uniq | grep -v -E '^arkindex|^#|teklia-license' > /requirements.txt
# List all management commands
RUN find /usr/share/arkindex/*/management -name '*.py' -not -name '__init__.py' > /commands.txt
# Remove arkindex unit tests
RUN find /usr/share/arkindex -type d -name tests | xargs rm -rf
# This configuration is needed to avoid a compilation crash at linking stage
# It only seems to happen on recent gcc
# See https://github.com/Nuitka/Nuitka/issues/959
ENV NUITKA_RESOURCE_MODE=linker
# Compile all our python source code
# Do not use the -O or -OO python flags here as it removes assert statements (see backend#432)
RUN python -m nuitka \
--nofollow-imports \
--include-package=arkindex \
--include-package=teklia_license \
--show-progress \
--lto=yes \
--output-dir=/build \
arkindex/manage.py
# Start over from a clean setup
FROM registry.gitlab.teklia.com/arkindex/backend/base:gitlab-teklia as build
# Import files from compilation
RUN mkdir /usr/share/arkindex
COPY --from=compilation /build/manage.bin /usr/bin/arkindex
COPY --from=compilation /requirements.txt /usr/share/arkindex
COPY --from=compilation /commands.txt /usr/share/arkindex
# Install open source Python dependencies
# We also add gunicorn, to be able to run `arkindex gunicorn`
RUN pip install -r /usr/share/arkindex/requirements.txt gunicorn
# Setup Arkindex VERSION
COPY VERSION /etc/arkindex.version
# Copy templates in base dir for binary
ENV BASE_DIR=/usr/share/arkindex
COPY arkindex/templates /usr/share/arkindex/templates
COPY arkindex/documents/export/*.sql /usr/share/arkindex/documents/export/
# Touch python files for needed management commands
# Otherwise Django will not load the compiled module
RUN for cmd in $(cat /usr/share/arkindex/commands.txt); do mkdir -p $(dirname $cmd); touch $cmd; done
HEALTHCHECK --start-period=1m --start-interval=1s --interval=1m --timeout=5s \
CMD wget --spider --quiet http://localhost/api/v1/public-key/ || exit 1
# Run gunicorn server
ENV PORT=80
EXPOSE $PORT
CMD arkindex gunicorn --host=0.0.0.0 --port $PORT
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Teklia is a French company focused on text recognition through AI
Copyright (C) 2024 Teklia
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
include VERSION
include LICENSE
include requirements.txt
include base/requirements.txt
include tests-requirements.txt
......
ROOT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
IMAGE_TAG=registry.gitlab.teklia.com/arkindex/backend
.PHONY: all release
.PHONY: all release services
all: clean build
......@@ -13,39 +13,36 @@ clean:
find . -name '*.pyc' -exec rm {} \;
build:
CI_PROJECT_DIR=$(ROOT_DIR) CI_REGISTRY_IMAGE=$(IMAGE_TAG) $(ROOT_DIR)/ci/build.sh Dockerfile
binary:
CI_PROJECT_DIR=$(ROOT_DIR) CI_REGISTRY_IMAGE=$(IMAGE_TAG) $(ROOT_DIR)/ci/build.sh Dockerfile.binary -binary
CI_PROJECT_DIR=$(ROOT_DIR) CI_REGISTRY_IMAGE=$(IMAGE_TAG) $(ROOT_DIR)/ci/build.sh
worker:
arkindex/manage.py rqworker -v 2 default high
arkindex rqworker -v 2 default high tasks
test-fixtures:
$(eval export PGPASSWORD=devdata)
psql -h 127.0.0.1 -p 9100 -U devuser -c 'ALTER DATABASE arkindex_dev RENAME TO arkindex_tmp_fixtures' template1
psql -h 127.0.0.1 -p 9100 -U devuser -c 'CREATE DATABASE arkindex_dev' template1
psql -h 127.0.0.1 -p 5432 -U devuser -c 'ALTER DATABASE arkindex_dev RENAME TO arkindex_tmp_fixtures' template1
psql -h 127.0.0.1 -p 5432 -U devuser -c 'CREATE DATABASE arkindex_dev' template1
# A "try...finally" block in a Makefile: ensure we bring back the dev database even when test-fixtures fails
-$(MAKE) test-fixtures-run
$(MAKE) test-fixtures-restore
test-fixtures-run:
arkindex/manage.py migrate
arkindex/manage.py build_fixtures
arkindex/manage.py dumpdata --indent 4 process documents images users auth ponos training > arkindex/documents/fixtures/data.json
arkindex migrate
arkindex build_fixtures
arkindex dumpdata --indent 4 process documents images users auth ponos training > arkindex/documents/fixtures/data.json
test-fixtures-restore:
# This first renaming ensures that arkindex_tmp_fixtures exists; we don't want to drop arkindex_dev without a backup
psql -h 127.0.0.1 -p 9100 -U devuser -c 'ALTER DATABASE arkindex_tmp_fixtures RENAME TO arkindex_dev_replace' template1
psql -h 127.0.0.1 -p 9100 -U devuser -c 'DROP DATABASE arkindex_dev' template1
psql -h 127.0.0.1 -p 9100 -U devuser -c 'ALTER DATABASE arkindex_dev_replace RENAME TO arkindex_dev' template1
psql -h 127.0.0.1 -p 5432 -U devuser -c 'ALTER DATABASE arkindex_tmp_fixtures RENAME TO arkindex_dev_replace' template1
psql -h 127.0.0.1 -p 5432 -U devuser -c 'DROP DATABASE arkindex_dev' template1
psql -h 127.0.0.1 -p 5432 -U devuser -c 'ALTER DATABASE arkindex_dev_replace RENAME TO arkindex_dev' template1
require-version:
@if [ ! "$(version)" ]; then echo "Missing version to publish"; exit 1; fi
@git rev-parse $(version) >/dev/null 2>&1 && (echo "Version $(version) already exists on local git repo !" && exit 1) || true
schema:
./arkindex/manage.py spectacular --fail-on-warn --validate --file schema.yml
arkindex spectacular --fail-on-warn --validate --file schema.yml
release:
$(eval version:=$(shell cat VERSION))
......@@ -53,3 +50,21 @@ release:
git commit VERSION -m "Version $(version)"
git tag $(version)
git push origin master $(version)
clean-docker:
$(eval containers:=$(shell docker ps -a -q))
@if [ -n "$(containers)" ]; then \
echo "Cleaning up past containers\n" \
docker rm -f $(containers) ; \
fi
stack: docker/ssl/ark-cert.pem
docker compose -p arkindex up --build
services: docker/ssl/ark-cert.pem
docker compose -p arkindex -f docker/docker-compose.services.yml up
docker/ssl/ark-cert.pem:
$(eval export CAROOT=$(ROOT_DIR)/docker/ssl)
mkcert -install
mkcert -cert-file=$(ROOT_DIR)/docker/ssl/ark-cert.pem -key-file=$(ROOT_DIR)/docker/ssl/ark-key.pem ark.localhost *.ark.localhost *.iiif.ark.localhost
Backend for Historical Manuscripts Indexing
===========================================
# Arkindex Backend
[![pipeline status](https://gitlab.teklia.com/arkindex/backend/badges/master/pipeline.svg)](https://gitlab.teklia.com/arkindex/backend/commits/master)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
This project is the open-source backend of Arkindex, used to manage and process image documents with Machine Learning tools.
It is licensed under the [AGPL-v3 license](./LICENSE).
## Requirements
* Clone of the [architecture](https://gitlab.teklia.com/arkindex/architecture)
* Git
* Make
* Python 3.6+
* Python 3.10+
* pip
* [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/)
* [Docker 24+](https://docs.docker.com/engine/install/#supported-platforms)
* [mkcert](https://github.com/FiloSottile/mkcert?tab=readme-ov-file#installation)
* [GeoDjango system dependencies](https://docs.djangoproject.com/en/3.1/ref/contrib/gis/install/geolibs/): `sudo apt install binutils libproj-dev gdal-bin`
## Dev Setup
## Setup for developers
```
You'll also need the [Arkindex frontend](https://gitlab.teklia.com/arkindex/frontend) to be able to develop on the whole platform.
```console
git clone git@gitlab.teklia.com:arkindex/backend.git
git clone git@gitlab.teklia.com:arkindex/frontend.git
cd backend
mkvirtualenv ark -a .
mkvirtualenv ark -a . -p /usr/bin/python3.10
pip install -e .[test]
```
When the [architecture](https://gitlab.teklia.com/arkindex/architecture) is running locally to provide required services:
The Arkindex backend relies on some open-source services to store data and communicate to asynchronous workers.
To run all the required services, please run in a dedicated shell:
```
arkindex/manage.py migrate
arkindex/manage.py createsuperuser
```console
make services
```
### Local configuration
On a first run, you'll need to:
For development purposes, you can customize the Arkindex settings by adding a YAML file as `arkindex/config.yml`. This file is not tracked by Git; if it exists, any configuration directive set in this file will be used for exposed settings from `settings.py`. You can view the full list of settings [on the wiki](https://wiki.vpn/en/arkindex/deploy/configuration).
1. Configure the instance by enabling the sample configuration.
2. Populate the database structure.
3. Initialize some fields in the database.
4. Create an administration account.
All of these steps are done through:
Another mean to customize your Arkindex instance is to add a Python file in `arkindex/project/local_settings.py`. Here you are not limited to exposed settings, and can customize any setting, or even load Python dependencies at boot time. This is not recommended, as your customization may not be available to real-world Arkindex instances.
```console
cp config.yml.sample arkindex/config.yml
arkindex migrate
arkindex bootstrap
arkindex createsuperuser
```
### ImageMagick setup
Finally, you can run the backend:
PDF and image imports in Arkindex will require ImageMagick. Due to its ability to take any computer down if you give it the right parameters (for example, converting a 1000-page PDF file into JPEG files at 30 000 DPI), it has a security policy file. By default, on Ubuntu, PDF conversion is forbidden.
```console
arkindex runserver
```
You will need to edit the ImageMagick policy file to get PDF and Image imports to work in Arkindex. The file is located at `/etc/ImageMagick-6/policy.xml`.
At this stage, you can use `http://localhost:8000/admin` to access the administration interface.
The line that sets the PDF policy is `<policy domain="coder" rights="none" pattern="PDF" />`. Replace `none` with `read|write` for it to work. See [this StackOverflow question](https://stackoverflow.com/questions/52998331) for more info.
### Asycnhronous tasks
### GitLab OAuth setup
To run asynchronous tasks, run in another shell:
Arkindex uses OAuth to let a user connect their GitLab account(s) and register Git repositories. In local development, you will need to register Arkindex as a GitLab OAuth application for it to work.
```console
make worker
```
Go to GitLab's [Applications settings](https://gitlab.teklia.com/profile/applications) and create a new application with the `api` scope and add the following callback URIs:
### Dockerized stack
```
http://127.0.0.1:8000/api/v1/oauth/providers/gitlab/callback/
http://ark.localhost:8000/api/v1/oauth/providers/gitlab/callback/
https://ark.localhost/api/v1/oauth/providers/gitlab/callback/
```
It is also possible to run the whole Arkindex stack through Docker containers. This is useful to quickly test the platform.
Once the application is created, GitLab will provide you with an application ID and a secret. Use the `arkindex/config.yml` file to set them:
This command will build all the required Docker images (backend & frontend) and run them as Docker containers:
```yaml
gitlab:
app_id: 24cacf5004bf68ae9daad19a5bba391d85ad1cb0b31366e89aec86fad0ab16cb
app_secret: 9d96d9d5b1addd7e7e6119a23b1e5b5f68545312bfecb21d1cdc6af22b8628b8
```console
make stack
```
You'll be able to access the platform at the url `https://ark.localhost`.
### Local configuration
For development purposes, you can customize the Arkindex settings by adding a YAML file as `arkindex/config.yml`. This file is not tracked by Git; if it exists, any configuration directive set in this file will be used for exposed settings from `settings.py`. You can view the full list of settings [on the wiki](https://redmine.teklia.com/projects/arkindex/wiki/Backend_configuration).
Another way to customize your Arkindex instance is to add a Python file in `arkindex/project/local_settings.py`. Here you are not limited to exposed settings, and can customize any setting, or even load Python dependencies at boot time. This is not recommended, as your customization may not be available to real-world Arkindex instances.
### Local image server
Arkindex splits up image URLs in their image server and the image path. For example, a IIIF server at `http://iiif.irht.cnrs.fr/iiif/` and an image at `/Paris/JJ042/1.jpg` would be represented as an ImageServer instance holding one Image. Since Arkindex has a local IIIF server for image uploads and thumbnails, a special instance of ImageServer is required to point to this local server. In local development, this server should be available at `https://ark.localhost/iiif`. You will therefore need to create an ImageServer via the Django admin or the Django shell with this URL. To set the local server ID, you can add a custom setting in `arkindex/config.yml`:
......@@ -73,19 +97,14 @@ local_imageserver_id: 999
Here is how to quickly create the ImageServer using the shell:
```
backend/arkindex$ ./manage.py shell
```python
$ arkindex shell
>>> from arkindex.images.models import ImageServer
>>> ImageServer.objects.create(id=1, display_name='local', url='https://ark.localhost/iiif')
```
Note that this local server will only work inside Docker.
### User groups
We use a custom group model in `arkindex.users.models` (not the `django.contrib.auth` one).
In this early version groups do not define any right yet.
## Usage
### Makefile
......@@ -95,31 +114,28 @@ At the root of the repository is a Makefile that provides commands for common op
* `make` or `make all`: Clean and build;
* `make base`: Create and push the `arkindex-base` Docker image that is used to build the `arkindex-app` image;
* `make clean`: Cleanup the Python package build and cache files;
* `make clean-docker`: Deletes all running containers to avoid naming and network ports conflicts;
* `make build`: Build the arkindex Python package and recreate the `arkindex-app:latest` without pushing to the GitLab container registry;
* `make test-fixtures`: Create the unit tests fixtures on a temporary PostgreSQL database and save them to the `data.json` file used by most Django unit tests.
### Django commands
Aside from the usual Django commands, some custom commands are available via `manage.py`:
Aside from the usual Django commands, some custom commands are available via `arkindex`:
* `build_fixtures`: Create a set of database elements designed for use by unit tests in a fixture (see `make test-fixtures`);
* `from_csv`: Import manifests and index files from a CSV list;
* `import_annotations`: Import index files from a folder into a specific volume;
* `import_acts`: Import XML surface files and CSV act files;
* `delete_corpus`: Delete a big corpus using an RQ task;
* `reindex`: Reindex elements into Solr;
* `telegraf`: A special command with InfluxDB-compatible output for Grafana statistics.
* `move_lines_to_parents`: Moves element children to their geographical parents;
* `build_fixtures`: Create a set of database elements designed for use by unit tests in a fixture (see `make test-fixtures`).
* `delete_corpus`: Delete a big corpus using an RQ task.
* `reindex`: Reindex elements into Solr.
* `move_lines_to_parents`: Moves element children to their geographical parents.
See `manage.py <command> --help` to view more details about a specific command.
See `arkindex <command> --help` to view more details about a specific command.
## Code validation
Once your code appears to be working on a local server, a few checks have to be performed:
* **Migrations:** Ensure that all migrations have been created by typing `./manage.py makemigrations`.
* **Unit tests:** Run `./manage.py test` to perform unit tests.
- Use `./manage.py test module_name` to perform tests on a single module, if you wish to spend less time waiting for all tests to complete.
* **Migrations:** Ensure that all migrations have been created by typing `arkindex makemigrations`.
* **Unit tests:** Run `arkindex test` to perform unit tests.
- Use `arkindex test module_name` to perform tests on a single module, if you wish to spend less time waiting for all tests to complete.
### Linting
......@@ -127,9 +143,9 @@ We use [pre-commit](https://pre-commit.com/) to check the Python source code syn
To be efficient, you should run pre-commit before committing (hence the name...).
To do that, run once :
To do that, run once:
```
```console
pip install pre-commit
pre-commit install
```
......@@ -142,13 +158,13 @@ If you want to run the full workflow on all the files: `pre-commit run -a`.
Run `pip install ipython django-debug-toolbar django_extensions` to install all the available optional dev tools for the backend.
IPython will give you a nicer shell with syntax highlighting, auto reloading and much more via `./manage.py shell`.
IPython will give you a nicer shell with syntax highlighting, auto reloading and much more via `arkindex shell`.
[Django Debug Toolbar](https://django-debug-toolbar.readthedocs.io/en/latest/) provides you with a neat debug sidebar that will help diagnosing slow API endpoints or weird template bugs. Since the Arkindex frontend is completely decoupled from the backend, you will need to browse to an API endpoint to see the debug toolbar.
[Django Extensions](https://django-extensions.readthedocs.io/en/latest/) adds a *lot* of `manage.py` commands ; the most important one is `./manage.py shell_plus` which runs the usual shell but with all the available models pre-imported. You can add your own imports with the `local_settings.py` file. Here is an example that imports most of the backend's enums and some special QuerySet features:
[Django Extensions](https://django-extensions.readthedocs.io/en/latest/) adds a *lot* of `arkindex` commands ; the most important one is `arkindex shell_plus` which runs the usual shell but with all the available models pre-imported. You can add your own imports with the `local_settings.py` file. Here is an example that imports some of the backend's enums and some special QuerySet features:
``` python
```python
SHELL_PLUS_POST_IMPORTS = [
('django.db.models', ('Value', )),
('django.db.models.functions', '*'),
......@@ -157,31 +173,43 @@ SHELL_PLUS_POST_IMPORTS = [
'Right',
)),
('arkindex.process.models', (
'DataImportMode',
'ProcessMode',
)),
('arkindex.project.aws', (
'S3FileStatus',
)),
('arkindex.users.models', (
'OAuthStatus',
))
]
```
## Asynchronous tasks
We use [rq](https://python-rq.org/), integrated via [django-rq](https://pypi.org/project/django-rq/), to run tasks without blocking an API request or causing timeouts. To call them in Python code, you should use the trigger methods in `arkindex.project.triggers`; those will do some safety checks to make catching some errors easier in dev. The actual tasks are in `arkindex.documents.tasks`. The following tasks exist:
We use [rq](https://python-rq.org/), integrated via [django-rq](https://pypi.org/project/django-rq/), to run tasks without blocking an API request or causing timeouts. To call them in Python code, you should use the trigger methods in `arkindex.project.triggers`; those will do some safety checks to make catching some errors easier in dev. The actual tasks are in `arkindex.documents.tasks`, or in other `tasks` modules within each Django app. The following tasks exist:
* Delete a corpus: `corpus_delete`
* Delete a list of elements: `element_trash`
* Delete worker results (transcriptions, classifications, etc. of a worker version): `worker_results_delete`
* Move an element to another parent: `move_element`
* Create `WorkerActivity` instances for all elements of a process: `intitialize_activity`
* Create `WorkerActivity` instances for all elements of a process: `initialize_activity`
* Delete a process and its worker activities: `process_delete`
* Export a corpus to an SQLite database: `export_corpus`
To run them, use `make worker` to start a RQ worker. You will need to have Redis running; `make slim` or `make` in the architecture will provide it. `make` in the architecture also provides a RQ worker running in Docker from a binary build.
To run them, use `make worker` to start a RQ worker. You will need to have Redis running; `make services` will provide it. `make stack` also provides an RQ worker running in Docker from a binary build.
## Metrics
The application serves metrics for Prometheus under the `/metrics` prefix.
A specific port can be used by setting the `PROMETHEUS_METRICS_PORT` environment variable, thus separating the application from the metrics API.
## Migration from `architecture` setup
If you were using the `architecture` repository previously to run Arkindex, you'll need to migrate MinIO data from a static path on your computer towards a new docker volume.
```console
docker volume create arkindex_miniodata
mv /usr/share/arkindex/s3/data/iiif /var/lib/docker/volumes/arkindex_miniodata/_data/uploads
mv /usr/share/arkindex/s3/data/{export,iiif-cache,ponos-logs,ponos-artifacts,staging,thumbnails,training} /var/lib/docker/volumes/arkindex_miniodata/_data/
```
You will also need to setup [mkcert](https://github.com/FiloSottile/mkcert?tab=readme-ov-file#installation) as we do not use Teklia development Certificate Authority anymore. `mkcert` will take care of SSL certificates automatically, updating your browsers and system certificate store !
Finally, you can remove the `architecture` project from your work folder, as it's now archived and could be confusing.
1.5.3-rc2
1.6.0
......@@ -11,8 +11,6 @@ from arkindex.documents.models import (
Element,
ElementType,
Entity,
EntityLink,
EntityRole,
EntityType,
MetaData,
MLClass,
......@@ -22,8 +20,8 @@ from arkindex.documents.models import (
class ElementTypeInline(admin.TabularInline):
model = ElementType
fields = ('slug', 'display_name', 'folder', 'indexable')
readonly_fields = ('slug', 'display_name', 'folder')
fields = ("slug", "display_name", "folder", "indexable")
readonly_fields = ("slug", "display_name", "folder")
def has_add_permission(self, request, obj=None):
return False
......@@ -33,66 +31,66 @@ class ElementTypeInline(admin.TabularInline):
class CorpusAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'public', 'top_level_type', 'created')
search_fields = ('name', )
list_display = ("id", "name", "public", "top_level_type", "created")
search_fields = ("name", )
inlines = (ElementTypeInline, )
ordering = ('-created', )
ordering = ("-created", )
def has_delete_permission(self, request, obj=None):
# Require everyone to use the asynchronous corpus deletion
return False
def get_queryset(self, request):
return super().get_queryset(request).select_related('top_level_type')
return super().get_queryset(request).select_related("top_level_type")
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
if obj:
# Limit top level type queryset to the types of this corpus
form.base_fields['top_level_type'].queryset = ElementType.objects.filter(corpus=obj)
form.base_fields["top_level_type"].queryset = ElementType.objects.filter(corpus=obj)
return form
class CorpusExportAdmin(admin.ModelAdmin):
list_display = ('id', 'corpus', 'user', 'state')
ordering = ('-created', )
list_display = ("id", "corpus", "user", "state")
ordering = ("-created", )
class ClassificationInline(admin.TabularInline):
model = Classification
readonly_fields = ('confidence', 'high_confidence', )
raw_id_fields = ('worker_version', 'worker_run', 'moderator', 'ml_class')
readonly_fields = ("confidence", "high_confidence", )
raw_id_fields = ("worker_version", "worker_run", "moderator", "ml_class")
class AllowedMetaDataAdmin(admin.ModelAdmin):
list_display = ('id', 'corpus', 'type', 'name')
readonly_fields = ('id', )
list_display = ("id", "corpus", "type", "name")
readonly_fields = ("id", )
def get_form(self, *args, **kwargs):
form = super().get_form(*args, **kwargs)
form.base_fields['corpus'].queryset = Corpus.objects.order_by('name', 'id')
form.base_fields["corpus"].queryset = Corpus.objects.order_by("name", "id")
return form
class MetaDataAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'type', )
list_filter = [('type', EnumFieldListFilter), ]
readonly_fields = ('id', )
raw_id_fields = ('element', 'entity', 'worker_version', 'worker_run')
list_display = ("id", "name", "type", )
list_filter = [("type", EnumFieldListFilter), ]
readonly_fields = ("id", )
raw_id_fields = ("element", "entity", "worker_version", "worker_run")
class MetaDataInline(admin.TabularInline):
model = MetaData
raw_id_fields = ('entity', 'worker_version', 'worker_run')
raw_id_fields = ("entity", "worker_version", "worker_run")
class ElementAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'type', 'corpus', )
list_filter = ['type__slug', 'corpus']
fields = ('id', 'type', 'name', 'image', 'corpus', 'confidence', 'worker_run', )
raw_id_fields = ('worker_run',)
readonly_fields = ('id', 'corpus', 'image',)
search_fields = ('name', )
list_display = ("id", "name", "type", "corpus", )
list_filter = ["type__slug", "corpus"]
fields = ("id", "type", "name", "image", "corpus", "confidence", "worker_run", )
raw_id_fields = ("worker_run",)
readonly_fields = ("id", "corpus", "image",)
search_fields = ("name", )
inlines = (MetaDataInline, ClassificationInline)
# Disable element creation through the admin to prevent element_type conflicts
......@@ -100,34 +98,34 @@ class ElementAdmin(admin.ModelAdmin):
return False
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'type':
if db_field.name == "type":
# Only display types available on the element's corpus
# It would make no sense to pick a type from another corpus
# Display all elements on creation, as we do not know yet the corpus
element_id = request.resolver_match.kwargs.get('object_id')
element_id = request.resolver_match.kwargs.get("object_id")
if element_id:
element = self.get_object(request, element_id)
kwargs['queryset'] = ElementType.objects.filter(corpus=element.corpus).order_by('display_name')
kwargs["queryset"] = ElementType.objects.filter(corpus=element.corpus).order_by("display_name")
return super().formfield_for_foreignkey(db_field, request, **kwargs)
class TranscriptionAdmin(admin.ModelAdmin):
list_display = ('id', 'text', 'confidence', 'orientation', 'element', )
fields = ('id', 'text', 'confidence', 'orientation', 'element', )
readonly_fields = ('id', )
raw_id_fields = ('element', )
list_display = ("id", "text", "confidence", "orientation", "element", )
fields = ("id", "text", "confidence", "orientation", "element", )
readonly_fields = ("id", )
raw_id_fields = ("element", )
class MLClassAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'corpus')
list_filter = ('corpus',)
search_fields = ('name',)
fields = ('name', 'corpus')
list_display = ("id", "name", "corpus")
list_filter = ("corpus",)
search_fields = ("name",)
fields = ("name", "corpus")
def get_form(self, *args, **kwargs):
form = super().get_form(*args, **kwargs)
form.base_fields['corpus'].queryset = Corpus.objects.order_by('name', 'id')
form.base_fields["corpus"].queryset = Corpus.objects.order_by("name", "id")
return form
......@@ -135,39 +133,25 @@ class EntityMetaForm(forms.ModelForm):
metas = HStoreFormField()
class EntityLinkInLine(admin.TabularInline):
model = EntityLink
fk_name = 'parent'
raw_id_fields = ('child', )
class EntityAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'type')
list_filter = ['corpus', 'type']
readonly_fields = ('id', )
raw_id_fields = ('worker_version', 'worker_run', )
search_fields = ('name', )
inlines = (EntityLinkInLine, )
list_display = ("id", "name", "type")
list_filter = ["corpus", "type"]
readonly_fields = ("id", )
raw_id_fields = ("worker_version", "worker_run", )
search_fields = ("name", )
form = EntityMetaForm
class EntityRoleAdmin(admin.ModelAdmin):
list_display = ('id', 'corpus', 'parent_name', 'child_name')
list_filter = ('corpus', )
readonly_fields = ('id', )
ordering = ('corpus', 'parent_name', 'child_name')
class EntityTypeAdmin(admin.ModelAdmin):
list_display = ('id', 'corpus', 'name', 'color')
list_filter = ('corpus', )
list_display = ("id", "corpus", "name", "color")
list_filter = ("corpus", )
def get_readonly_fields(self, request, obj=None):
# Make the corpus field read-only only for existing entity types.
# Otherwise, new EntityTypes would be created with corpus=None
if obj:
return ('id', 'corpus')
return ('id', )
return ("id", "corpus")
return ("id", )
def has_delete_permission(self, request, obj=None):
# Require everyone to use the frontend or DestroyEntityType
......@@ -180,7 +164,6 @@ admin.site.register(Transcription, TranscriptionAdmin)
admin.site.register(MLClass, MLClassAdmin)
admin.site.register(MetaData, MetaDataAdmin)
admin.site.register(Entity, EntityAdmin)
admin.site.register(EntityRole, EntityRoleAdmin)
admin.site.register(EntityType, EntityTypeAdmin)
admin.site.register(AllowedMetaData, AllowedMetaDataAdmin)
admin.site.register(CorpusExport, CorpusExportAdmin)
......@@ -67,7 +67,7 @@ from arkindex.documents.serializers.elements import (
ElementNeighborsSerializer,
ElementParentSerializer,
ElementSerializer,
ElementSlimSerializer,
ElementTinySerializer,
ElementTypeSerializer,
MetaDataBulkSerializer,
MetaDataCreateSerializer,
......@@ -97,7 +97,7 @@ from arkindex.training.models import DatasetElement, ModelVersion
from arkindex.users.models import Role
from arkindex.users.utils import filter_rights
classifications_queryset = Classification.objects.select_related('ml_class', 'worker_version').order_by('-confidence')
classifications_queryset = Classification.objects.select_related("ml_class", "worker_version").order_by("-confidence")
def _fetch_has_children(elements):
......@@ -133,9 +133,9 @@ def _fetch_has_children(elements):
with connection.cursor() as cursor:
execute_values(
cursor,
'SELECT DISTINCT ON (e.id) e.id, p.id is not null as has_children '
'FROM (VALUES %s) e (id) '
'LEFT JOIN documents_elementpath p ON (ARRAY[e.id] && p.path)',
"SELECT DISTINCT ON (e.id) e.id, p.id is not null as has_children "
"FROM (VALUES %s) e (id) "
"LEFT JOIN documents_elementpath p ON (ARRAY[e.id] && p.path)",
tuple((element.id, ) for element in elements),
)
has_children = dict(cursor.fetchall())
......@@ -149,11 +149,11 @@ def _fetch_has_children(elements):
# Operators available for numeric filters in element lists
# Maps valid operator names in the API to Django QuerySet lookups
NUMERIC_OPERATORS = {
'eq': 'exact',
'lt': 'lt',
'gt': 'gt',
'lte': 'lte',
'gte': 'gte',
"eq": "exact",
"lt": "lt",
"gt": "gt",
"lte": "lte",
"gte": "gte",
}
# Operators available for metadata values.
......@@ -161,42 +161,42 @@ METADATA_OPERATORS = {
# Only for numeric metadata
**NUMERIC_OPERATORS,
# The contains operator should be case-insensitive
'contains': 'icontains',
"contains": "icontains",
}
# Operators that do not require the metadata value to be a number
METADATA_STRING_OPERATORS = {'eq', 'contains'}
METADATA_STRING_OPERATORS = {"eq", "contains"}
# Ordering options available on element lists.
# The keys are the values that the user can set in `&order=…`
# and the values are tuples of fields sent as the arguments to QuerySet.order_by() for an ascending order.
ELEMENT_ORDERINGS = {
'name': ('name', 'id'),
'created': ('created', 'id'),
'random': ('?', ),
"name": ("name", "id"),
"created": ("created", "id"),
"random": ("?", ),
# In PostgreSQL, ASC orderings implicitly use NULLS LAST, and DESC orderings use NULLS FIRST.
# Since we have to use a descending order for right-to-left orderings, nulls end up coming first.
# To stay consistent in what looks like an ascending order for the user, we explicitly set NULLS LAST
# using F() expressions.
TextOrientation.HorizontalLeftToRight.value: (
F('polygon__centroid__y').asc(nulls_last=True),
F('polygon__centroid__x').asc(nulls_last=True),
'id',
F("polygon__centroid__y").asc(nulls_last=True),
F("polygon__centroid__x").asc(nulls_last=True),
"id",
),
TextOrientation.HorizontalRightToLeft.value: (
F('polygon__centroid__y').asc(nulls_last=True),
F('polygon__centroid__x').desc(nulls_last=True),
'id',
F("polygon__centroid__y").asc(nulls_last=True),
F("polygon__centroid__x").desc(nulls_last=True),
"id",
),
TextOrientation.VerticalLeftToRight.value: (
F('polygon__centroid__x').asc(nulls_last=True),
F('polygon__centroid__y').asc(nulls_last=True),
'id',
F("polygon__centroid__x").asc(nulls_last=True),
F("polygon__centroid__y").asc(nulls_last=True),
"id",
),
TextOrientation.VerticalRightToLeft.value: (
F('polygon__centroid__x').desc(nulls_last=True),
F('polygon__centroid__y').asc(nulls_last=True),
'id',
F("polygon__centroid__x").desc(nulls_last=True),
F("polygon__centroid__y").asc(nulls_last=True),
"id",
),
}
......@@ -212,69 +212,69 @@ class ElementsListAutoSchema(AutoSchema):
# Parameters that apply to all methods
parameters = [
OpenApiParameter(
'type',
description='Filter elements by type',
"type",
description="Filter elements by type",
required=False,
),
OpenApiParameter(
'name',
description='Only include elements whose name contains a given string (case-insensitive)',
"name",
description="Only include elements whose name contains a given string (case-insensitive)",
required=False,
),
OpenApiParameter(
'folder',
description='Restrict to or exclude elements with folder types',
"folder",
description="Restrict to or exclude elements with folder types",
type=bool,
required=False,
),
OpenApiParameter(
'worker_version',
description='Only include elements created by a specific worker version. '
'If set to `False`, only include elements created by humans.',
"worker_version",
description="Only include elements created by a specific worker version. "
"If set to `False`, only include elements created by humans.",
type=UUID_OR_FALSE,
required=False,
),
OpenApiParameter(
'worker_run',
description='Only include elements created by a specific worker run. '
'If set to `False`, only include elements created by humans.',
"worker_run",
description="Only include elements created by a specific worker run. "
"If set to `False`, only include elements created by humans.",
type=UUID_OR_FALSE,
required=False,
),
OpenApiParameter(
'rotation_angle',
description='Restrict to elements with the given rotation angle.',
"rotation_angle",
description="Restrict to elements with the given rotation angle.",
type={
'type': 'integer',
'minimum': 0,
'maximum': 359,
"type": "integer",
"minimum": 0,
"maximum": 359,
},
required=False,
),
OpenApiParameter(
'mirrored',
description='Restrict to or exclude mirrored elements.',
"mirrored",
description="Restrict to or exclude mirrored elements.",
type=bool,
required=False,
)
]
# Add method-specific parameters
if self.method.lower() == 'get':
if self.method.lower() == "get":
parameters.extend([
OpenApiParameter(
'confidence',
description='Restrict to elements with the given confidence. '
'The comparison operator can be set using `confidence_operator`.',
"confidence",
description="Restrict to elements with the given confidence. "
"The comparison operator can be set using `confidence_operator`.",
type={
'type': 'number',
'minimum': 0,
'maximum': 1
"type": "number",
"minimum": 0,
"maximum": 1
},
required=False,
),
OpenApiParameter(
'confidence_operator',
"confidence_operator",
description=dedent("""
Set the comparison operator to filter on element confidence scores:
......@@ -287,23 +287,23 @@ class ElementsListAutoSchema(AutoSchema):
This requires `confidence` to be set.
"""),
enum=NUMERIC_OPERATORS.keys(),
default='eq',
default="eq",
required=False,
),
OpenApiParameter(
'metadata_name',
description='Restrict to elements having a metadata with the given name.',
"metadata_name",
description="Restrict to elements having a metadata with the given name.",
required=False,
),
OpenApiParameter(
'metadata_value',
description='Restrict to elements having a metadata with the given value. '
'The comparison operator can be set using `metadata_operator`. '
'Requires `metadata_name` to be set.',
"metadata_value",
description="Restrict to elements having a metadata with the given value. "
"The comparison operator can be set using `metadata_operator`. "
"Requires `metadata_name` to be set.",
required=False,
),
OpenApiParameter(
'metadata_operator',
"metadata_operator",
description=dedent("""
Set the comparison operator to filter on metadata values:
......@@ -317,38 +317,38 @@ class ElementsListAutoSchema(AutoSchema):
This requires `metadata_name` and `metadata_value` to be set.
"""),
enum=METADATA_OPERATORS.keys(),
default='eq',
default="eq",
required=False,
),
OpenApiParameter(
'class_id',
description='Restrict to elements having a classification with the specified ML class ID.'
'If `classification_confidence` or `classification_high_confidence` are set, '
'the elements must have a classification that satisfies all of the parameters at once.',
"class_id",
description="Restrict to elements having a classification with the specified ML class ID."
"If `classification_confidence` or `classification_high_confidence` are set, "
"the elements must have a classification that satisfies all of the parameters at once.",
type=UUID,
required=False,
),
OpenApiParameter(
'creator_email',
description='Restrict to elements created by the user with the specified email address.',
"creator_email",
description="Restrict to elements created by the user with the specified email address.",
type=OpenApiTypes.EMAIL,
required=False,
),
OpenApiParameter(
'classification_confidence',
description='Restrict to elements having a classification with the given confidence. '
'The comparison operator can be set using `classification_confidence_operator`. '
'If `class_id` or `classification_high_confidence` are set, the elements must have a '
'classification that satisfies all of the parameters at once.',
"classification_confidence",
description="Restrict to elements having a classification with the given confidence. "
"The comparison operator can be set using `classification_confidence_operator`. "
"If `class_id` or `classification_high_confidence` are set, the elements must have a "
"classification that satisfies all of the parameters at once.",
type={
'type': 'number',
'minimum': 0,
'maximum': 1
"type": "number",
"minimum": 0,
"maximum": 1
},
required=False,
),
OpenApiParameter(
'classification_confidence_operator',
"classification_confidence_operator",
description=dedent("""
Set the comparison operator to filter on classification confidence scores:
......@@ -361,32 +361,32 @@ class ElementsListAutoSchema(AutoSchema):
This requires `classification_confidence` to be set.
"""),
enum=NUMERIC_OPERATORS.keys(),
default='eq',
default="eq",
required=False,
),
OpenApiParameter(
'classification_high_confidence',
description='Restrict to elements having a classification marked as `high_confidence`. '
'If `class_id` or `classification_confidence` are set, the elements must have a '
'classification that satisfies all of the parameters at once.',
"classification_high_confidence",
description="Restrict to elements having a classification marked as `high_confidence`. "
"If `class_id` or `classification_confidence` are set, the elements must have a "
"classification that satisfies all of the parameters at once.",
type=bool,
required=False,
),
OpenApiParameter(
'transcription_confidence',
description='Restrict to elements having a transcription with the given confidence. '
'The comparison operator can be set using `transcription_confidence_operator`. '
'If `transcription_worker_version` is set, the elements must have a '
'transcription that satisfies both filters at once.',
"transcription_confidence",
description="Restrict to elements having a transcription with the given confidence. "
"The comparison operator can be set using `transcription_confidence_operator`. "
"If `transcription_worker_version` is set, the elements must have a "
"transcription that satisfies both filters at once.",
type={
'type': 'number',
'minimum': 0,
'maximum': 1
"type": "number",
"minimum": 0,
"maximum": 1
},
required=False,
),
OpenApiParameter(
'transcription_confidence_operator',
"transcription_confidence_operator",
description=dedent("""
Set the comparison operator to filter on transcription confidence scores:
......@@ -399,29 +399,29 @@ class ElementsListAutoSchema(AutoSchema):
This requires `transcription_confidence` to be set.
"""),
enum=NUMERIC_OPERATORS.keys(),
default='eq',
default="eq",
required=False,
),
OpenApiParameter(
'transcription_worker_version',
description='Only include elements that have a transcription created by a specific worker version. '
'If set to `False`, only include elements with a transcription created by humans. '
'If `transcription_confidence` is set, the elements must have a '
'transcription that satisfies both filters at once.',
"transcription_worker_version",
description="Only include elements that have a transcription created by a specific worker version. "
"If set to `False`, only include elements with a transcription created by humans. "
"If `transcription_confidence` is set, the elements must have a "
"transcription that satisfies both filters at once.",
type=UUID_OR_FALSE,
required=False,
),
OpenApiParameter(
'transcription_worker_run',
description='Only include elements that have a transcription created by a specific worker run. '
'If set to `False`, only include elements with a transcription created by humans. '
'If `transcription_confidence` is set, the elements must have a '
'transcription that satisfies both filters at once.',
"transcription_worker_run",
description="Only include elements that have a transcription created by a specific worker run. "
"If set to `False`, only include elements with a transcription created by humans. "
"If `transcription_confidence` is set, the elements must have a "
"transcription that satisfies both filters at once.",
type=UUID_OR_FALSE,
required=False,
),
OpenApiParameter(
'order',
"order",
description=dedent("""
Defines how the elements should be sorted:
......@@ -450,68 +450,68 @@ class ElementsListAutoSchema(AutoSchema):
The `rotation_angle` and `mirrored` attributes do not affect the centroid ordering.
""").strip(),
enum=ELEMENT_ORDERINGS.keys(),
default='name',
default="name",
required=False,
),
OpenApiParameter(
'order_direction',
description='Direction in which to sort elements. Ignored when using the `random` order.',
enum={'asc', 'desc'},
default='asc',
"order_direction",
description="Direction in which to sort elements. Ignored when using the `random` order.",
enum={"asc", "desc"},
default="asc",
required=False,
),
OpenApiParameter(
'with_classes',
description='Returns all classifications for each element. '
'Otherwise, `classes` will always be null.',
"with_classes",
description="Returns all classifications for each element. "
"Otherwise, `classes` will always be null.",
type=bool,
required=False,
),
OpenApiParameter(
'with_metadata',
description='Returns all metadata without entities for each element. '
'Otherwise, `metadata` will always be null.',
"with_metadata",
description="Returns all metadata without entities for each element. "
"Otherwise, `metadata` will always be null.",
type=bool,
required=False,
),
OpenApiParameter(
'with_has_children',
description='Include the `has_children` boolean to tell if each element has direct children. '
'Otherwise, `has_children` will always be null.',
"with_has_children",
description="Include the `has_children` boolean to tell if each element has direct children. "
"Otherwise, `has_children` will always be null.",
type=bool,
required=False,
),
OpenApiParameter(
'with_corpus',
description='Returns the corpus attribute for each element. '
'When not set, the corpus attribute will be returned by default.',
"with_corpus",
description="Returns the corpus attribute for each element. "
"When not set, the corpus attribute will be returned by default.",
type=bool,
default=True,
required=False,
),
OpenApiParameter(
'with_zone',
description='Returns the zone attribute for each element. '
'When not set, the zone attribute will be returned by default.',
"with_zone",
description="Returns the zone attribute for each element. "
"When not set, the zone attribute will be returned by default.",
type=bool,
default=True,
required=False,
),
OpenApiParameter(
'If-Modified-Since',
"If-Modified-Since",
location=OpenApiParameter.HEADER,
description='Return HTTP 304 Not Modified when no elements have been created or updated since that time, '
'otherwise respond normally. Expects HTTP date formats (`Wed, 21 Oct 2015 07:28:00 GMT`). '
'Note that this is unable to detect deletions and will not filter the returned elements.',
description="Return HTTP 304 Not Modified when no elements have been created or updated since that time, "
"otherwise respond normally. Expects HTTP date formats (`Wed, 21 Oct 2015 07:28:00 GMT`). "
"Note that this is unable to detect deletions and will not filter the returned elements.",
required=False
)
])
elif self.method.lower() == 'delete':
elif self.method.lower() == "delete":
parameters.extend([
OpenApiParameter(
'delete_children',
description='Delete all child elements of those elements recursively.',
"delete_children",
description="Delete all child elements of those elements recursively.",
type=bool,
required=False,
)
......@@ -520,7 +520,7 @@ class ElementsListAutoSchema(AutoSchema):
return parameters
def get_tags(self):
return ['elements']
return ["elements"]
class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
......@@ -543,18 +543,18 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
self.clean_params = {}
# Set attributes for Spectacular's schema generation
self.schema.path = ''
self.schema.path = ""
self.schema.method = self.request.method
for param in self.schema._get_parameters():
if param['in'] == 'header':
if param["in"] == "header":
origin_dict = self.request.headers
elif param['in'] == 'query':
elif param["in"] == "query":
origin_dict = self.request.query_params
else:
raise NotImplementedError
if param['name'] in origin_dict:
self.clean_params[param['name']] = origin_dict[param['name']]
if param["name"] in origin_dict:
self.clean_params[param["name"]] = origin_dict[param["name"]]
def check_corpus_access(self, corpus):
"""
......@@ -566,15 +566,15 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
role = Role.Contributor
if self.request.method in permissions.SAFE_METHODS:
role = Role.Guest
elif self.request.method == 'DELETE':
elif self.request.method == "DELETE":
role = Role.Admin
if not self.has_access(corpus, role.value):
raise PermissionDenied(detail=f'You do not have {str(role).lower()} access to this corpus.')
raise PermissionDenied(detail=f"You do not have {str(role).lower()} access to this corpus.")
@cached_property
def selected_corpus(self):
# Retrieve the corpus and check user access rights only once
corpus_id = self.kwargs.get('corpus')
corpus_id = self.kwargs.get("corpus")
if corpus_id is None:
return
......@@ -584,23 +584,23 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
@property
def folder_filter(self):
if self.clean_params.get('folder') is None:
if self.clean_params.get("folder") is None:
return
return self.clean_params['folder'].lower() not in ('false', '0')
return self.clean_params["folder"].lower() not in ("false", "0")
@cached_property
def type_filter(self):
if 'type' not in self.request.query_params:
if "type" not in self.request.query_params:
return
try:
element_type = self.selected_corpus.types.get(slug=self.clean_params['type'])
element_type = self.selected_corpus.types.get(slug=self.clean_params["type"])
except ElementType.DoesNotExist:
raise ValidationError({'type': ['This type does not exist.']})
raise ValidationError({"type": ["This type does not exist."]})
# When an API request is made with &type=…&folder=true, we avoid adding a type__folder filder in the query,
# which would cause a join on ElementType, and instead check for the type's folder state here
if self.folder_filter is not None and element_type.folder != self.folder_filter:
raise ValidationError({'non_field_errors': [
raise ValidationError({"non_field_errors": [
f'This type is {"not " if self.folder_filter else ""} a folder type.']
})
......@@ -608,31 +608,31 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
def get_worker_version_filter(self, filter_name):
# If worker_version query param is False, we have to return elements created by humans
if self.clean_params[filter_name].lower() in ('false', '0'):
if self.clean_params[filter_name].lower() in ("false", "0"):
return None
try:
worker_version_id = uuid.UUID(self.clean_params[filter_name])
except (TypeError, ValueError):
raise ValidationError(['Invalid UUID'])
raise ValidationError(["Invalid UUID"])
if not WorkerVersion.objects.filter(id=worker_version_id).exists():
raise ValidationError(['This worker version does not exist.'])
raise ValidationError(["This worker version does not exist."])
return worker_version_id
def get_worker_run_filter(self, filter_name):
# If worker_run query param is False, we have to return elements created by humans
if self.clean_params[filter_name].lower() in ('false', '0'):
if self.clean_params[filter_name].lower() in ("false", "0"):
return None
try:
worker_run_id = uuid.UUID(self.clean_params[filter_name])
except (TypeError, ValueError):
raise ValidationError(['Invalid UUID'])
raise ValidationError(["Invalid UUID"])
if not WorkerRun.objects.filter(id=worker_run_id).exists():
raise ValidationError(['This worker run does not exist.'])
raise ValidationError(["This worker run does not exist."])
return worker_run_id
......@@ -641,9 +641,9 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
Returns a queryset that includes matched element IDs from metadata filters,
or None if no metadata filters apply.
"""
name = self.clean_params.get('metadata_name')
value = self.clean_params.get('metadata_value')
operator = self.clean_params.get('metadata_operator', '').lower().strip()
name = self.clean_params.get("metadata_name")
value = self.clean_params.get("metadata_value")
operator = self.clean_params.get("metadata_operator", "").lower().strip()
if not any((name, value, operator)):
return
......@@ -655,48 +655,48 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
if operator:
if operator not in METADATA_OPERATORS:
errors['metadata_operator'].append('This metadata operator is not supported.')
errors["metadata_operator"].append("This metadata operator is not supported.")
if value is None:
errors['metadata_operator'].append('This option is not supported without metadata_value.')
errors["metadata_operator"].append("This option is not supported without metadata_value.")
elif operator not in METADATA_STRING_OPERATORS:
try:
value = float(value)
except (ValueError, TypeError):
errors['metadata_value'].append('Value must be a float when using a numeric comparison operator.')
errors["metadata_value"].append("Value must be a float when using a numeric comparison operator.")
value = None
else:
operator = 'eq'
operator = "eq"
if value:
lookup = METADATA_OPERATORS[operator]
if name:
if operator in METADATA_STRING_OPERATORS:
queryset = queryset.filter(**{f'value__{lookup}': value})
queryset = queryset.filter(**{f"value__{lookup}": value})
else:
# Apply the numeric type filter, and filter on the value as a float
queryset = queryset \
.alias(numeric_value=Cast('value', output_field=FloatField())) \
.filter(type=MetaType.Numeric, **{f'numeric_value__{lookup}': value})
.alias(numeric_value=Cast("value", output_field=FloatField())) \
.filter(type=MetaType.Numeric, **{f"numeric_value__{lookup}": value})
else:
errors['metadata_value'].append('This filter is not supported without metadata_name.')
errors["metadata_value"].append("This filter is not supported without metadata_name.")
if errors:
raise ValidationError(errors)
return queryset.values('element_id')
return queryset.values("element_id")
def get_classification_queryset(self):
"""
Returns a queryset that includes matched element IDs from classification filters,
or None if no classification filters apply.
"""
class_id = self.clean_params.get('class_id')
confidence = self.clean_params.get('classification_confidence')
confidence_operator = self.clean_params.get('classification_confidence_operator', '').lower().strip()
high_confidence = self.clean_params.get('classification_high_confidence', '').lower().strip()
class_id = self.clean_params.get("class_id")
confidence = self.clean_params.get("classification_confidence")
confidence_operator = self.clean_params.get("classification_confidence_operator", "").lower().strip()
high_confidence = self.clean_params.get("classification_high_confidence", "").lower().strip()
if len(high_confidence):
high_confidence = high_confidence not in ('false', '0')
high_confidence = high_confidence not in ("false", "0")
else:
# An empty string should be treated as no filter at all
high_confidence = None
......@@ -713,29 +713,29 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
ml_class = self.selected_corpus.ml_classes.get(id=class_id)
except DjangoValidationError as e:
# An invalid UUID would cause a Django ValidationError
errors['class_id'].extend(e.messages)
errors["class_id"].extend(e.messages)
except MLClass.DoesNotExist:
errors['class_id'].append(f'ML class "{class_id}" not found')
errors["class_id"].append(f'ML class "{class_id}" not found')
else:
queryset = queryset.filter(ml_class=ml_class)
if confidence_operator:
if confidence_operator not in NUMERIC_OPERATORS:
errors['classification_confidence_operator'].append('This operator is not supported.')
errors["classification_confidence_operator"].append("This operator is not supported.")
if confidence is None:
errors['classification_confidence_operator'].append('This option is not supported without classification_confidence.')
errors["classification_confidence_operator"].append("This option is not supported without classification_confidence.")
else:
confidence_operator = 'eq'
confidence_operator = "eq"
if confidence:
try:
confidence = float(confidence)
assert 0 <= confidence <= 1, 'Confidence must be between 0 and 1'
assert 0 <= confidence <= 1, "Confidence must be between 0 and 1"
except (TypeError, ValueError, AssertionError) as e:
errors['classification_confidence'].append(str(e))
errors["classification_confidence"].append(str(e))
else:
lookup = NUMERIC_OPERATORS.get(confidence_operator, 'exact')
queryset = queryset.filter(**{f'confidence__{lookup}': confidence})
lookup = NUMERIC_OPERATORS.get(confidence_operator, "exact")
queryset = queryset.filter(**{f"confidence__{lookup}": confidence})
if high_confidence is not None:
queryset = queryset.filter(high_confidence=high_confidence)
......@@ -743,17 +743,17 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
if errors:
raise ValidationError(errors)
return queryset.values('element_id')
return queryset.values("element_id")
def get_transcription_queryset(self):
"""
Returns a queryset that includes matched element IDs from transcription filters,
or None if no transcription filters apply.
"""
worker_version_id = self.clean_params.get('transcription_worker_version')
worker_run_id = self.clean_params.get('transcription_worker_run')
confidence = self.clean_params.get('transcription_confidence')
confidence_operator = self.clean_params.get('transcription_confidence_operator', '').lower().strip()
worker_version_id = self.clean_params.get("transcription_worker_version")
worker_run_id = self.clean_params.get("transcription_worker_run")
confidence = self.clean_params.get("transcription_confidence")
confidence_operator = self.clean_params.get("transcription_confidence_operator", "").lower().strip()
if not worker_version_id and not worker_run_id and confidence is None and not confidence_operator:
# No filters apply
......@@ -763,64 +763,64 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
errors = defaultdict(list)
if worker_version_id and worker_run_id:
errors['__all__'] = ['The transcription worker run and transcription worker version filters are mutually exclusive.']
errors["__all__"] = ["The transcription worker run and transcription worker version filters are mutually exclusive."]
if worker_version_id:
try:
queryset = queryset.filter(worker_version_id=self.get_worker_version_filter('transcription_worker_version'))
queryset = queryset.filter(worker_version_id=self.get_worker_version_filter("transcription_worker_version"))
except ValidationError as e:
errors['transcription_worker_version'] = e.detail
errors["transcription_worker_version"] = e.detail
if worker_run_id:
try:
queryset = queryset.filter(worker_run_id=self.get_worker_run_filter('transcription_worker_run'))
queryset = queryset.filter(worker_run_id=self.get_worker_run_filter("transcription_worker_run"))
except ValidationError as e:
errors['transcription_worker_run'] = e.detail
errors["transcription_worker_run"] = e.detail
if confidence_operator:
if confidence_operator not in NUMERIC_OPERATORS:
errors['transcription_confidence_operator'].append('This operator is not supported.')
errors["transcription_confidence_operator"].append("This operator is not supported.")
if confidence is None:
errors['transcription_confidence_operator'].append('This option is not supported without transcription_confidence.')
errors["transcription_confidence_operator"].append("This option is not supported without transcription_confidence.")
else:
confidence_operator = 'eq'
confidence_operator = "eq"
if confidence:
try:
confidence = float(confidence)
assert 0 <= confidence <= 1, 'Confidence must be between 0 and 1'
assert 0 <= confidence <= 1, "Confidence must be between 0 and 1"
except (TypeError, ValueError, AssertionError) as e:
errors['transcription_confidence'].append(str(e))
errors["transcription_confidence"].append(str(e))
else:
lookup = NUMERIC_OPERATORS.get(confidence_operator, 'exact')
queryset = queryset.filter(**{f'confidence__{lookup}': confidence})
lookup = NUMERIC_OPERATORS.get(confidence_operator, "exact")
queryset = queryset.filter(**{f"confidence__{lookup}": confidence})
if errors:
raise ValidationError(errors)
return queryset.values('element_id')
return queryset.values("element_id")
def get_filters(self) -> Q:
filters = Q(corpus=self.selected_corpus)
errors = defaultdict(list)
if 'name' in self.clean_params:
filters &= Q(name__icontains=self.clean_params['name'])
if "name" in self.clean_params:
filters &= Q(name__icontains=self.clean_params["name"])
if 'creator_email' in self.clean_params:
filters &= Q(creator__email=self.clean_params['creator_email'])
if "creator_email" in self.clean_params:
filters &= Q(creator__email=self.clean_params["creator_email"])
if 'rotation_angle' in self.clean_params:
if "rotation_angle" in self.clean_params:
try:
rotation_angle = int(self.clean_params['rotation_angle'])
assert 0 <= rotation_angle <= 359, 'A rotation angle must be between 0 and 359 degrees'
rotation_angle = int(self.clean_params["rotation_angle"])
assert 0 <= rotation_angle <= 359, "A rotation angle must be between 0 and 359 degrees"
except (AssertionError, TypeError, ValueError) as e:
errors['rotation_angle'].append(str(e))
errors["rotation_angle"].append(str(e))
else:
filters &= Q(rotation_angle=rotation_angle)
if 'mirrored' in self.clean_params:
filters &= Q(mirrored=self.clean_params['mirrored'].lower() not in ('false', '0'))
if "mirrored" in self.clean_params:
filters &= Q(mirrored=self.clean_params["mirrored"].lower() not in ("false", "0"))
if self.type_filter:
filters &= Q(type=self.type_filter)
......@@ -837,40 +837,40 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
# will lower the amount of rows much more quickly, making it stop using multi-processing.
filters &= Q(type__corpus=self.selected_corpus, type__folder=self.folder_filter)
if 'worker_version' in self.clean_params and 'worker_run' in self.clean_params:
errors['__all__'] = ['The worker run and worker version filters are mutually exclusive.']
if "worker_version" in self.clean_params and "worker_run" in self.clean_params:
errors["__all__"] = ["The worker run and worker version filters are mutually exclusive."]
if 'worker_version' in self.clean_params:
if "worker_version" in self.clean_params:
try:
filters &= Q(worker_version_id=self.get_worker_version_filter('worker_version'))
filters &= Q(worker_version_id=self.get_worker_version_filter("worker_version"))
except ValidationError as e:
errors['worker_version'] = e.detail
errors["worker_version"] = e.detail
if 'worker_run' in self.clean_params:
if "worker_run" in self.clean_params:
try:
filters &= Q(worker_run_id=self.get_worker_run_filter('worker_run'))
filters &= Q(worker_run_id=self.get_worker_run_filter("worker_run"))
except ValidationError as e:
errors['worker_run'] = e.detail
errors["worker_run"] = e.detail
confidence = self.clean_params.get('confidence')
confidence_operator = self.clean_params.get('confidence_operator', '').lower().strip()
confidence = self.clean_params.get("confidence")
confidence_operator = self.clean_params.get("confidence_operator", "").lower().strip()
if confidence_operator:
if confidence_operator not in NUMERIC_OPERATORS:
errors['confidence_operator'].append('This operator is not supported.')
errors["confidence_operator"].append("This operator is not supported.")
if confidence is None:
errors['confidence_operator'].append('This option is not supported without `confidence`.')
errors["confidence_operator"].append("This option is not supported without `confidence`.")
else:
confidence_operator = 'eq'
confidence_operator = "eq"
if confidence:
try:
confidence = float(confidence)
assert 0 <= confidence <= 1, 'Confidence must be between 0 and 1'
assert 0 <= confidence <= 1, "Confidence must be between 0 and 1"
except (TypeError, ValueError, AssertionError) as e:
errors['confidence'].append(str(e))
errors["confidence"].append(str(e))
else:
lookup = NUMERIC_OPERATORS.get(confidence_operator, 'exact')
filters &= Q(**{f'confidence__{lookup}': confidence})
lookup = NUMERIC_OPERATORS.get(confidence_operator, "exact")
filters &= Q(**{f"confidence__{lookup}": confidence})
try:
metadata_queryset = self.get_metadata_queryset()
......@@ -903,43 +903,43 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
def get_serializer_context(self):
context = super().get_serializer_context()
context['corpus'] = self.selected_corpus
context["corpus"] = self.selected_corpus
if self.request:
context['with_zone'] = self.request.query_params.get('with_zone', 'true').lower() not in ('false', '0')
context['with_corpus'] = self.request.query_params.get('with_corpus', 'true').lower() not in ('false', '0')
context["with_zone"] = self.request.query_params.get("with_zone", "true").lower() not in ("false", "0")
context["with_corpus"] = self.request.query_params.get("with_corpus", "true").lower() not in ("false", "0")
return context
def get_prefetch(self):
# Select the image and server in one separate query
prefetch = {Prefetch('image', queryset=Image.objects.select_related('server')), 'type'}
prefetch = {Prefetch("image", queryset=Image.objects.select_related("server")), "type"}
with_classes = self.clean_params.get('with_classes')
if with_classes and with_classes.lower() not in ('false', '0'):
prefetch.add(Prefetch('classifications', queryset=classifications_queryset, to_attr='classes'))
with_classes = self.clean_params.get("with_classes")
if with_classes and with_classes.lower() not in ("false", "0"):
prefetch.add(Prefetch("classifications", queryset=classifications_queryset, to_attr="classes"))
with_metadata = self.clean_params.get('with_metadata')
if with_metadata and with_metadata.lower() not in ('false', '0'):
with_metadata = self.clean_params.get("with_metadata")
if with_metadata and with_metadata.lower() not in ("false", "0"):
prefetch.add(Prefetch(
'metadatas',
"metadatas",
queryset=MetaData.objects.filter(entity__isnull=True),
to_attr='prefetched_metadata',
to_attr="prefetched_metadata",
))
return prefetch
@property
def is_descending(self):
direction = self.clean_params.get('order_direction', 'asc').lower()
if direction not in ('asc', 'desc'):
raise ValidationError({'order_direction': ['Unknown sorting direction']})
return direction == 'desc'
direction = self.clean_params.get("order_direction", "asc").lower()
if direction not in ("asc", "desc"):
raise ValidationError({"order_direction": ["Unknown sorting direction"]})
return direction == "desc"
def get_order_by(self):
ordering = self.clean_params.get('order', 'name').lower()
ordering = self.clean_params.get("order", "name").lower()
order_expressions = ELEMENT_ORDERINGS.get(ordering)
if not order_expressions:
raise ValidationError({'order': ['Unknown sorting field']})
raise ValidationError({"order": ["Unknown sorting field"]})
return order_expressions
......@@ -952,8 +952,8 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
if self.is_descending:
queryset = queryset.reverse()
with_has_children = self.clean_params.get('with_has_children')
if with_has_children and with_has_children.lower() not in ('false', '0'):
with_has_children = self.clean_params.get("with_has_children")
if with_has_children and with_has_children.lower() not in ("false", "0"):
queryset = BulkMap(_fetch_has_children, queryset)
return queryset
......@@ -965,9 +965,9 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
# Retrieve the inner QuerySet from the BulkMap if it is used
if isinstance(queryset, BulkMap):
queryset = queryset.iterable
assert isinstance(queryset, QuerySet), 'A Django QuerySet is required to check for modified elements'
assert isinstance(queryset, QuerySet), "A Django QuerySet is required to check for modified elements"
modified_since_string = self.clean_params.get('If-Modified-Since')
modified_since_string = self.clean_params.get("If-Modified-Since")
if not modified_since_string:
return False
......@@ -975,7 +975,7 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
# Returns None if no date could be parsed or if the header was not defined
time_tuple = email.utils.parsedate_tz(modified_since_string)
if not time_tuple:
raise ValidationError({'If-Modified-Since': ['Bad date format']})
raise ValidationError({"If-Modified-Since": ["Bad date format"]})
# Build a datetime from the tuple
modified_since = datetime.fromtimestamp(email.utils.mktime_tz(time_tuple), timezone.utc)
......@@ -999,7 +999,7 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
def delete(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
delete_children = self.clean_params.get('delete_children', '').lower() not in ('false', '0')
delete_children = self.clean_params.get("delete_children", "").lower() not in ("false", "0")
if not queryset.exists():
raise NotFound
......@@ -1011,18 +1011,18 @@ class ElementsListBase(CorpusACLMixin, DestroyModelMixin, ListAPIView):
@extend_schema(
parameters=[
OpenApiParameter(
'top_level',
description='Restrict to or exclude folder elements without parent elements (top-level elements).',
"top_level",
description="Restrict to or exclude folder elements without parent elements (top-level elements).",
type=bool,
required=False,
)
]
)
@extend_schema_view(
get=extend_schema(operation_id='ListElements'),
delete=extend_schema(operation_id='DestroyElements', description=(
'Destroy elements in bulk.\n\n'
'Requires an **admin** access to the corpus.'
get=extend_schema(operation_id="ListElements"),
delete=extend_schema(operation_id="DestroyElements", description=(
"Destroy elements in bulk.\n\n"
"Requires an **admin** access to the corpus."
)),
)
class CorpusElements(ElementsListBase):
......@@ -1034,13 +1034,13 @@ class CorpusElements(ElementsListBase):
@property
def is_top_level(self):
if self.clean_params.get('top_level') is None:
if self.clean_params.get("top_level") is None:
return None
return self.clean_params['top_level'].lower() not in ('false', '0')
return self.clean_params["top_level"].lower() not in ("false", "0")
def get_queryset(self):
# Should not be possible due to the URL
assert self.selected_corpus, 'Missing corpus ID'
assert self.selected_corpus, "Missing corpus ID"
return self.selected_corpus.elements.all()
def get_filters(self) -> Q:
......@@ -1057,17 +1057,17 @@ class CorpusElements(ElementsListBase):
@extend_schema(
parameters=[
OpenApiParameter(
'recursive',
"recursive",
type=bool,
description='List recursively (parents, grandparents, etc.)',
description="List recursively (parents, grandparents, etc.)",
required=False,
),
]
)
@extend_schema_view(
get=extend_schema(operation_id='ListElementParents'),
delete=extend_schema(operation_id='DestroyElementParents', description=(
'Delete parent elements in bulk.\n\n'
get=extend_schema(operation_id="ListElementParents"),
delete=extend_schema(operation_id="DestroyElementParents", description=(
"Delete parent elements in bulk.\n\n"
"Requires an **admin** access to the element's corpus."
)),
)
......@@ -1080,8 +1080,8 @@ class ElementParents(ElementsListBase):
@property
def is_recursive(self):
recursive_param = self.clean_params.get('recursive')
return recursive_param is not None and recursive_param.lower() not in ('false', '0')
recursive_param = self.clean_params.get("recursive")
return recursive_param is not None and recursive_param.lower() not in ("false", "0")
@property
def selected_corpus(self):
......@@ -1089,20 +1089,20 @@ class ElementParents(ElementsListBase):
def get_queryset(self):
self.element = get_object_or_404(
Element.objects.select_related('corpus'),
id=self.kwargs['pk']
Element.objects.select_related("corpus"),
id=self.kwargs["pk"]
)
self.check_corpus_access(self.element.corpus)
return Element.objects.get_ascending(self.kwargs['pk'], recursive=self.is_recursive)
return Element.objects.get_ascending(self.kwargs["pk"], recursive=self.is_recursive)
@extend_schema(
parameters=[
OpenApiParameter(
'recursive',
"recursive",
type=bool,
description='List recursively (children, grandchildren, etc.)',
description="List recursively (children, grandchildren, etc.)",
required=False,
),
]
......@@ -1111,9 +1111,9 @@ class ElementParents(ElementsListBase):
# In the frontend, ListElementChildren uses 'position' for ordering by default,
# to display elements according to their ElementPath.ordering; it makes sense
# for the API to use the same default ordering as the frontend.
get=extend_schema(operation_id='ListElementChildren', parameters=[
get=extend_schema(operation_id="ListElementChildren", parameters=[
OpenApiParameter(
'order',
"order",
description=dedent("""
Sort elements by a specific field.
......@@ -1121,13 +1121,13 @@ class ElementParents(ElementsListBase):
[ListElementParents](#operation/ListElementParents), the `position` option is available
to sort elements by their position within the parent element.
""").strip(),
enum=set(ELEMENT_ORDERINGS.keys()) | {'position'},
default='position',
enum=set(ELEMENT_ORDERINGS.keys()) | {"position"},
default="position",
required=False,
)
]),
delete=extend_schema(operation_id='DestroyElementChildren', description=(
'Delete child elements in bulk.\n\n'
delete=extend_schema(operation_id="DestroyElementChildren", description=(
"Delete child elements in bulk.\n\n"
"Requires an **admin** access to the element's corpus."
)),
)
......@@ -1140,8 +1140,8 @@ class ElementChildren(ElementsListBase):
@property
def is_recursive(self):
recursive_param = self.clean_params.get('recursive')
return recursive_param is not None and recursive_param.lower() not in ('false', '0')
recursive_param = self.clean_params.get("recursive")
return recursive_param is not None and recursive_param.lower() not in ("false", "0")
@property
def selected_corpus(self):
......@@ -1151,9 +1151,9 @@ class ElementChildren(ElementsListBase):
filters = super().get_filters()
if self.is_recursive:
filters &= Q(paths__path__overlap=[self.kwargs['pk']])
filters &= Q(paths__path__overlap=[self.kwargs["pk"]])
else:
filters &= Q(paths__path__last=self.kwargs['pk'])
filters &= Q(paths__path__last=self.kwargs["pk"])
return filters
......@@ -1163,19 +1163,19 @@ class ElementChildren(ElementsListBase):
The only endpoint where a path ordering is made visible in the API
is ListElementNeighbors, in a field named `position`.
"""
if self.clean_params.get('order', 'position').lower() == 'position':
return ('paths__ordering', 'id')
if self.clean_params.get("order", "position").lower() == "position":
return ("paths__ordering", "id")
return super().get_order_by()
def get_queryset(self):
self.element = get_object_or_404(
Element.objects.select_related('corpus'),
id=self.kwargs['pk']
Element.objects.select_related("corpus"),
id=self.kwargs["pk"]
)
self.check_corpus_access(self.element.corpus)
# Let `self.get_filters` handle filtering optimisations
if self.clean_params.get('order', 'position').lower() == 'position':
if self.clean_params.get("order", "position").lower() == "position":
# This condition is necessary because when ordering by position ('paths__ordering')
# we run into this bug https://gitlab.teklia.com/arkindex/backend/-/issues/769 and unless
# the ordering is also used in the .distinct(), this leads to some results being
......@@ -1190,14 +1190,14 @@ class ElementChildren(ElementsListBase):
# from the results. Adding the 'paths__ordering' to the .distinct() here forces the
# duplicating bug to happen during the COUNT query as well, thus avoiding disappearing
# elements.
return Element.objects.all().distinct('id', 'paths__ordering')
return Element.objects.all().distinct("id", "paths__ordering")
return Element.objects.all().distinct()
@extend_schema(tags=['elements'])
@extend_schema(tags=["elements"])
@extend_schema_view(
get=extend_schema(description="Retrieve a single element's information and metadata"),
patch=extend_schema(description='Rename an element'),
patch=extend_schema(description="Edit an element's attributes. Requires a write access on the corpus."),
put=extend_schema(description="Edit an element's attributes. Requires a write access on the corpus."),
delete=extend_schema(
description=dedent("""
......@@ -1208,10 +1208,10 @@ class ElementChildren(ElementsListBase):
""").strip(),
parameters=[
OpenApiParameter(
'delete_children',
description='Delete all child elements of this element recursively. '
'By default, this only removes this element as a parent of the child elements, '
'without deleting any child element.',
"delete_children",
description="Delete all child elements of this element recursively. "
"By default, this only removes this element as a parent of the child elements, "
"without deleting any child element.",
type=bool,
required=False,
),
......@@ -1224,33 +1224,33 @@ class ElementRetrieve(ACLMixin, RetrieveUpdateDestroyAPIView):
def get_object(self):
# Prevent duplicating database request
if not hasattr(self, 'element'):
if not hasattr(self, "element"):
self.element = super().get_object()
return self.element
def get_queryset(self):
corpora = Corpus.objects.readable(self.request.user)
queryset = Element.objects.filter(corpus__in=corpora)
if self.request and self.request.method == 'DELETE':
if self.request and self.request.method == "DELETE":
# Only include corpus and creator for ACL check and ID for deletion
return (
queryset
.select_related('corpus')
.annotate(has_dataset=Exists(DatasetElement.objects.filter(element_id=OuterRef('pk'))))
.only('id', 'creator_id', 'corpus')
.select_related("corpus")
.annotate(has_dataset=Exists(DatasetElement.objects.filter(element_id=OuterRef("pk"))))
.only("id", "creator_id", "corpus")
)
return (
queryset
.select_related(
'corpus',
'type',
'image__server',
'creator',
'worker_run'
"corpus",
"type",
"image__server",
"creator",
"worker_run"
)
.prefetch_related(Prefetch('classifications', queryset=classifications_queryset))
.annotate(metadata_count=Count('metadatas'))
.prefetch_related(Prefetch("classifications", queryset=classifications_queryset))
.annotate(metadata_count=Count("metadatas"))
)
def check_object_permissions(self, request, obj):
......@@ -1259,26 +1259,26 @@ class ElementRetrieve(ACLMixin, RetrieveUpdateDestroyAPIView):
if request.method in permissions.SAFE_METHODS:
return
role = Role.Contributor
if request.method == 'DELETE' and obj.creator_id != request.user.id:
if request.method == "DELETE" and obj.creator_id != request.user.id:
role = Role.Admin
if not self.has_access(obj.corpus, role.value):
access_repr = 'admin' if role == Role.Admin else 'write'
raise PermissionDenied(detail=f'You do not have {access_repr} access to this element.')
access_repr = "admin" if role == Role.Admin else "write"
raise PermissionDenied(detail=f"You do not have {access_repr} access to this element.")
# Prevent the direct deletion of an element that is part of a dataset
if request.method == 'DELETE' and getattr(obj, 'has_dataset', False):
raise PermissionDenied(detail='You cannot delete an element that is part of a dataset.')
if request.method == "DELETE" and getattr(obj, "has_dataset", False):
raise PermissionDenied(detail="You cannot delete an element that is part of a dataset.")
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request and self.request.method != 'GET' and 'pk' in self.kwargs:
context['element'] = self.get_object()
if self.request and self.request.method != "GET" and "pk" in self.kwargs:
context["element"] = self.get_object()
return context
def delete(self, request, *args, **kwargs):
self.check_object_permissions(self.request, self.get_object())
queryset = Element.objects.filter(id=self.kwargs['pk'])
delete_children = self.request.query_params.get('delete_children', 'false').lower() not in ('false', '0')
queryset = Element.objects.filter(id=self.kwargs["pk"])
delete_children = self.request.query_params.get("delete_children", "false").lower() not in ("false", "0")
element_trash(queryset, user_id=self.request.user.id, delete_children=delete_children)
......@@ -1287,8 +1287,8 @@ class ElementRetrieve(ACLMixin, RetrieveUpdateDestroyAPIView):
@extend_schema_view(
get=extend_schema(
operation_id='ListElementNeighbors',
tags=['elements'],
operation_id="ListElementNeighbors",
tags=["elements"],
)
)
class ElementNeighbors(ACLMixin, ListAPIView):
......@@ -1303,29 +1303,28 @@ class ElementNeighbors(ACLMixin, ListAPIView):
queryset = Element.objects.none()
def get_queryset(self):
element = get_object_or_404(
# Include the attributes required for ACL checks and the API response
Element.objects.select_related('corpus', 'type').only('id', 'name', 'type__slug', 'corpus__public'),
id=self.kwargs['pk']
Element
.objects
.filter(corpus__in=Corpus.objects.readable(self.request.user))
.select_related("corpus", "type")
.only("id", "name", "type__slug", "corpus__public"),
id=self.kwargs["pk"]
)
# Check access permission
if not self.has_access(element.corpus, Role.Guest.value):
raise PermissionDenied(detail='You do not have a read access to this element.')
return Element.objects.get_neighbors(element)
@extend_schema(tags=['elements'], request=None)
@extend_schema(tags=["elements"], request=None)
@extend_schema_view(
post=extend_schema(
operation_id='CreateElementParent',
description='Link an element to a new parent',
operation_id="CreateElementParent",
description="Link an element to a new parent",
),
delete=extend_schema(
operation_id='DestroyElementParent',
description='Delete the relation between an element and one of its parents',
operation_id="DestroyElementParent",
description="Delete the relation between an element and one of its parents",
),
)
class ElementParent(CreateAPIView, DestroyAPIView):
......@@ -1336,8 +1335,8 @@ class ElementParent(CreateAPIView, DestroyAPIView):
permission_classes = (IsVerified, )
def get_serializer_from_params(self, child=None, parent=None, **kwargs):
data = {'child': child, 'parent': parent}
kwargs['context'] = self.get_serializer_context()
data = {"child": child, "parent": parent}
kwargs["context"] = self.get_serializer_context()
return ElementParentSerializer(data=data, **kwargs)
def create(self, request, *args, **kwargs):
......@@ -1363,26 +1362,26 @@ class RemoveSelectionAutoSchema(AutoSchema):
"""
def _get_request_body(self):
if self.method != 'DELETE':
if self.method != "DELETE":
return super()._get_request_body()
# To bypass the no-body rule for DELETE methods, we force the DELETE method to POST.
self.method = 'POST'
self.method = "POST"
request_body = super()._get_request_body()
# The body isn't required but it will be ignored by APIStar, so we must always use body={} when calling RemoveSelection.
request_body['required'] = False
request_body["required"] = False
# Now that we have retrieved the requestBody schema, we can reset the method to its true nature.
self.method = 'DELETE'
self.method = "DELETE"
return request_body
@extend_schema(tags=['elements'])
@extend_schema(tags=["elements"])
@extend_schema_view(
get=extend_schema(
operation_id='ListSelection',
description='List all selected elements',
operation_id="ListSelection",
description="List all selected elements",
)
)
class ManageSelection(SelectionMixin, ListAPIView):
......@@ -1392,40 +1391,40 @@ class ManageSelection(SelectionMixin, ListAPIView):
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
if not settings.ARKINDEX_FEATURES['selection']:
raise ValidationError(['Selection is not available on this instance.'])
if not settings.ARKINDEX_FEATURES["selection"]:
raise ValidationError(["Selection is not available on this instance."])
def get_queryset(self):
corpora = Corpus.objects.readable(self.request.user)
corpus_id = self.request.query_params.get('corpus')
corpus_id = self.request.query_params.get("corpus")
if corpus_id:
try:
UUID(corpus_id)
except ValueError:
raise ValidationError({'corpus': 'Not a valid UUID.'})
raise ValidationError({"corpus": "Not a valid UUID."})
get_object_or_404(corpora, pk=corpus_id)
queryset = self.get_selection(corpus_id=corpus_id)
return queryset.select_related('type', 'corpus', 'image__server').order_by('corpus', 'type__slug', 'name', 'id')
return queryset.select_related("type", "corpus", "image__server").order_by("corpus", "type__slug", "name", "id")
# TODO: Use many=True on the response without causing Spectacular to see a paginated list
@extend_schema(
operation_id='AddSelection',
description='Add specific elements',
responses={201: ElementSlimSerializer},
operation_id="AddSelection",
description="Add specific elements",
responses={201: ElementTinySerializer},
request=inline_serializer(
name="AddSelectionBodySerializer",
fields={'ids': serializers.ListField(child=serializers.UUIDField())}
fields={"ids": serializers.ListField(child=serializers.UUIDField())}
)
)
def post(self, request, *args, **kwargs):
if 'ids' not in request.data:
raise ValidationError({'ids': ['Element IDs are required.']})
if "ids" not in request.data:
raise ValidationError({"ids": ["Element IDs are required."]})
# Strange field validation done here,
# as we have different serializers on each request method on the same endpoint.
# Using serializer fields means we still preserve DRF's normal validation.
field = serializers.ListField(child=serializers.UUIDField())
element_ids = field.to_internal_value(request.data['ids'])
element_ids = field.to_internal_value(request.data["ids"])
# Silently de-duplicate element ids
element_ids = set(element_ids)
......@@ -1435,8 +1434,8 @@ class ManageSelection(SelectionMixin, ListAPIView):
))
if len(elements) != len(element_ids):
raise ValidationError({'ids': [
'Some element IDs do not exist or you do not have permission to access them.'
raise ValidationError({"ids": [
"Some element IDs do not exist or you do not have permission to access them."
]})
# Add new Selection objects in bulk, ignoring elements that were already selected
......@@ -1448,40 +1447,40 @@ class ManageSelection(SelectionMixin, ListAPIView):
ignore_conflicts=True,
)
prefetch_related_objects(elements, 'corpus', 'image__server', 'type')
prefetch_related_objects(elements, "corpus", "image__server", "type")
return Response(
status=status.HTTP_201_CREATED,
data=ElementSlimSerializer(
data=ElementTinySerializer(
elements,
context={'request': request},
context={"request": request},
many=True
).data,
)
@extend_schema(
operation_id='RemoveSelection',
description='Remove a specific element or delete any selection',
operation_id="RemoveSelection",
description="Remove a specific element or delete any selection",
request=inline_serializer(
name="RemoveSelectionBodySerializer",
fields={'id': serializers.UUIDField(required=False)}
fields={"id": serializers.UUIDField(required=False)}
)
)
def delete(self, request, *args, **kwargs):
if request.data.get('id'):
if request.data.get("id"):
field = serializers.PrimaryKeyRelatedField(queryset=self.get_selection())
try:
UUID(request.data['id'])
UUID(request.data["id"])
except (ValueError, AttributeError):
raise ValidationError({'id': ['Not a valid UUID.']})
element = field.to_internal_value(request.data['id'])
raise ValidationError({"id": ["Not a valid UUID."]})
element = field.to_internal_value(request.data["id"])
request.user.selections.get(element=element).delete()
elif request.data.get('corpus'):
elif request.data.get("corpus"):
corpora = Corpus.objects.readable(request.user)
try:
UUID(request.data['corpus'])
UUID(request.data["corpus"])
except ValueError:
raise ValidationError({'corpus': 'Not a valid UUID.'})
corpus = get_object_or_404(corpora, pk=request.data['corpus'])
raise ValidationError({"corpus": "Not a valid UUID."})
corpus = get_object_or_404(corpora, pk=request.data["corpus"])
request.user.selections.filter(element__corpus=corpus).delete()
else:
request.user.selections.all().delete()
......@@ -1489,10 +1488,10 @@ class ManageSelection(SelectionMixin, ListAPIView):
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(tags=['corpora'])
@extend_schema(tags=["corpora"])
@extend_schema_view(
get=extend_schema(description='List corpora with their access rights'),
post=extend_schema(description='Create a new corpus'),
get=extend_schema(description="List corpora with their access rights"),
post=extend_schema(description="Create a new corpus"),
)
class CorpusList(ListCreateAPIView):
"""
......@@ -1514,9 +1513,9 @@ class CorpusList(ListCreateAPIView):
corpora = Corpus.objects \
.filter(id__in=corpora_level) \
.annotate(authorized_users=Count('memberships')) \
.prefetch_related('types') \
.order_by('name', 'id')
.annotate(authorized_users=Count("memberships")) \
.prefetch_related("types") \
.order_by("name", "id")
for c in corpora:
c.access_level = corpora_level[c.id]
......@@ -1534,7 +1533,7 @@ class CorpusList(ListCreateAPIView):
return corpora
@extend_schema(tags=['corpora'])
@extend_schema(tags=["corpora"])
@extend_schema_view(
get=extend_schema(description=dedent("""
Retrieve a single corpus.
......@@ -1567,8 +1566,8 @@ class CorpusRetrieve(CorpusACLMixin, RetrieveUpdateDestroyAPIView):
def get_queryset(self):
return Corpus.objects.readable(self.request.user) \
.annotate(authorized_users=Count('memberships')) \
.prefetch_related('types')
.annotate(authorized_users=Count("memberships")) \
.prefetch_related("types")
def check_object_permissions(self, request, obj):
super().check_object_permissions(request, obj)
......@@ -1578,7 +1577,7 @@ class CorpusRetrieve(CorpusACLMixin, RetrieveUpdateDestroyAPIView):
return
if not self.has_admin_access(obj):
raise PermissionDenied(detail='You do not have admin access to this corpus.')
raise PermissionDenied(detail="You do not have admin access to this corpus.")
def perform_destroy(self, instance):
corpus_delete(instance, user_id=self.request.user.id)
......@@ -1590,32 +1589,32 @@ class TranscriptionsPagination(PageNumberPagination):
@extend_schema_view(
get=extend_schema(
operation_id='ListTranscriptions',
tags=['transcriptions'],
operation_id="ListTranscriptions",
tags=["transcriptions"],
parameters=[
OpenApiParameter(
'recursive',
"recursive",
type=bool,
description='Recursively list transcriptions on sub-elements',
description="Recursively list transcriptions on sub-elements",
required=False,
),
OpenApiParameter(
'worker_version',
"worker_version",
type=UUID_OR_FALSE,
description='Only include transcriptions created by a specific worker version. '
'If set to `False`, only include transcriptions created by humans.',
description="Only include transcriptions created by a specific worker version. "
"If set to `False`, only include transcriptions created by humans.",
required=False,
),
OpenApiParameter(
'worker_run',
"worker_run",
type=UUID_OR_FALSE,
description='Only include transcriptions created by a specific worker run. '
'If set to `False`, only include transcriptions created by no worker run.',
description="Only include transcriptions created by a specific worker run. "
"If set to `False`, only include transcriptions created by no worker run.",
required=False,
),
OpenApiParameter(
'element_type',
description='Filter transcriptions by element type',
"element_type",
description="Filter transcriptions by element type",
required=False,
)
]
......@@ -1635,13 +1634,13 @@ class ElementTranscriptions(ListAPIView):
def is_recursive(self):
if not self.request:
return
recursive = self.request.query_params.get('recursive')
return recursive is not None and recursive.lower() not in ('false', '0')
recursive = self.request.query_params.get("recursive")
return recursive is not None and recursive.lower() not in ("false", "0")
@cached_property
def element(self):
element = get_object_or_404(Element.objects.filter(
id=self.kwargs['pk'],
id=self.kwargs["pk"],
corpus__in=Corpus.objects.readable(self.request.user)
))
self.check_object_permissions(self.request, element)
......@@ -1650,11 +1649,11 @@ class ElementTranscriptions(ListAPIView):
def get_serializer_context(self):
context = super().get_serializer_context()
# Do serialize the element attached to each transcription in recursive mode only
context['ignore_element'] = not self.is_recursive
context["ignore_element"] = not self.is_recursive
return context
def get_queryset(self):
queryset = Transcription.objects.select_related('worker_run')
queryset = Transcription.objects.select_related("worker_run")
if self.is_recursive:
# List and filter children results. Current element transcriptions
......@@ -1665,7 +1664,7 @@ class ElementTranscriptions(ListAPIView):
# Also filter by corpus ID for better performance
.filter(element__corpus_id=self.element.corpus_id)
# Transcription's `element` field is only included when recursive=true
.select_related('element__type')
.select_related("element__type")
)
else:
queryset = queryset.filter(element_id=self.element.id)
......@@ -1677,30 +1676,30 @@ class ElementTranscriptions(ListAPIView):
errors = defaultdict(list)
# Filter by worker run
if 'worker_run' in self.request.query_params:
worker_run_id = self.request.query_params['worker_run']
if worker_run_id.lower() in ('false', '0'):
if "worker_run" in self.request.query_params:
worker_run_id = self.request.query_params["worker_run"]
if worker_run_id.lower() in ("false", "0"):
# Restrict to transcriptions without worker runs
filters &= Q(worker_run_id=None)
else:
try:
filters &= Q(worker_run_id=uuid.UUID(worker_run_id))
except (TypeError, ValueError):
errors['worker_run'].append(f'{worker_run_id}” is not a valid UUID.')
errors["worker_run"].append(f"{worker_run_id}” is not a valid UUID.")
# Filter by worker version
if 'worker_version' in self.request.query_params:
worker_version_id = self.request.query_params['worker_version']
if worker_version_id.lower() in ('false', '0'):
if "worker_version" in self.request.query_params:
worker_version_id = self.request.query_params["worker_version"]
if worker_version_id.lower() in ("false", "0"):
# Restrict to transcriptions without worker runs
filters &= Q(worker_version_id=None)
else:
try:
filters &= Q(worker_version_id=uuid.UUID(worker_version_id))
except (TypeError, ValueError):
errors['worker_version'].append(f'{worker_version_id}” is not a valid UUID.')
errors["worker_version"].append(f"{worker_version_id}” is not a valid UUID.")
elt_type_filter = self.request.query_params.get('element_type')
elt_type_filter = self.request.query_params.get("element_type")
if elt_type_filter:
queryset = queryset.filter(element__type__slug=elt_type_filter)
......@@ -1723,23 +1722,23 @@ class ElementTranscriptions(ListAPIView):
queryset = queryset.union(
(
self.element.transcriptions
.select_related('element__type', 'worker_run')
.select_related("element__type", "worker_run")
.filter(filters)
),
# No element can be duplicated here
all=True,
)
return queryset.order_by('id')
return queryset.order_by("id")
@extend_schema_view(
post=extend_schema(
operation_id='CreateElement',
tags=['elements'],
operation_id="CreateElement",
tags=["elements"],
parameters=[
OpenApiParameter(
'slim_output',
"slim_output",
deprecated=True,
type=bool,
description="This parameter should not be used anymore, as it does not significantly "
......@@ -1749,10 +1748,10 @@ class ElementTranscriptions(ListAPIView):
],
# Return either a full element or the element ID depending on slim_output
responses=PolymorphicProxySerializer(
component_name='CreateElementResponse',
resource_type_field_name='slim_output',
component_name="CreateElementResponse",
resource_type_field_name="slim_output",
serializers={
True: inline_serializer('CreateElementSlimOutput', fields={'id': serializers.UUIDField()}),
True: inline_serializer("CreateElementSlimOutput", fields={"id": serializers.UUIDField()}),
False: ElementSerializer,
}
)
......@@ -1768,12 +1767,12 @@ class ElementsCreate(CreateAPIView):
@extend_schema_view(
get=extend_schema(
operation_id='ListElementMetaData',
description='List all metadata linked to an element.',
tags=['elements'],
operation_id="ListElementMetaData",
description="List all metadata linked to an element.",
tags=["elements"],
parameters=[
OpenApiParameter(
'load_parents',
"load_parents",
description="List metadata for both the specified element and all of its parents.",
type=bool,
default=False,
......@@ -1781,8 +1780,8 @@ class ElementsCreate(CreateAPIView):
]
),
post=extend_schema(
operation_id='CreateMetaData',
tags=['elements'],
operation_id="CreateMetaData",
tags=["elements"],
)
)
class ElementMetadata(ListCreateAPIView):
......@@ -1813,7 +1812,7 @@ class ElementMetadata(ListCreateAPIView):
Returns the queryset to list metadata.
In case the load_parents flag is set, lists metadata for both the specified element and all of its parents
"""
with_parents = self.request.query_params.get('load_parents', 'false').lower() not in ('false', '0')
with_parents = self.request.query_params.get("load_parents", "false").lower() not in ("false", "0")
if with_parents:
qs = MetaData.objects.filter(
# Filter metadata on the current element and its parents
......@@ -1822,38 +1821,38 @@ class ElementMetadata(ListCreateAPIView):
# JOIN with the elements table using `Element.objects.get_ascending`.
# https://redmine.teklia.com/projects/arkindex/wiki/Optimizing_parent_elements_metadata
element.paths
.annotate(parent_id=Unnest('path'))
.values('parent_id')
.annotate(parent_id=Unnest("path"))
.values("parent_id")
.union(
Element.objects
# Use an annotation to execute a simple SELECT '<uuid>'::uuid FROM <table> LIMIT 1
# in order to also fetch element's metadata with no supplementary query.
.annotate(element_id=Value(element.id))
.values('element_id')[:1]
.values("element_id")[:1]
)
)
)
else:
qs = element.metadatas.all()
return qs.select_related('entity__worker_run', 'entity__type', 'worker_run')
return qs.select_related("entity__worker_run", "entity__type", "worker_run")
def get_queryset(self):
if self.request and self.request.method == 'GET':
element = get_object_or_404(Element, id=self.kwargs['pk'], corpus__in=Corpus.objects.readable(self.request.user))
if self.request and self.request.method == "GET":
element = get_object_or_404(Element, id=self.kwargs["pk"], corpus__in=Corpus.objects.readable(self.request.user))
return self.list_metadata(element)
# We need to use the default database to avoid stale read
# when a metadata is created immediately after an element creation.
# Note that this returns a queryset of elements and not metadata!
return Element.objects.using('default').filter(corpus__in=Corpus.objects.writable(self.request.user))
return Element.objects.using("default").filter(corpus__in=Corpus.objects.writable(self.request.user))
def get_serializer_context(self):
context = super().get_serializer_context()
# Ignore this step when generating the schema with OpenAPI
if not self.request:
return context
if self.request.method != 'GET':
context['element'] = self.get_object()
if self.request.method != "GET":
context["element"] = self.get_object()
return context
def perform_create(self, serializer):
......@@ -1864,8 +1863,8 @@ class ElementMetadata(ListCreateAPIView):
@extend_schema_view(
post=extend_schema(
operation_id='CreateMetaDataBulk',
tags=['elements'],
operation_id="CreateMetaDataBulk",
tags=["elements"],
)
)
class ElementMetadataBulk(CreateAPIView):
......@@ -1878,14 +1877,14 @@ class ElementMetadataBulk(CreateAPIView):
def get_queryset(self):
# We need to use the default database to avoid stale read
# when metadata are created immediately after an element creation
return Element.objects.using('default').filter(corpus__in=Corpus.objects.writable(self.request.user))
return Element.objects.using("default").filter(corpus__in=Corpus.objects.writable(self.request.user))
def get_serializer_context(self):
context = super().get_serializer_context()
# Ignore this step when generating the schema with OpenAPI
if not self.request:
return context
context['element'] = self.get_object()
context["element"] = self.get_object()
return context
def perform_create(self, serializer):
......@@ -1894,18 +1893,18 @@ class ElementMetadataBulk(CreateAPIView):
AllowedMetaData.objects.bulk_create(
[
AllowedMetaData(name=instance.name, type=instance.type, corpus=instance.element.corpus)
for instance in instances['metadata_list']
for instance in instances["metadata_list"]
],
ignore_conflicts=True
)
@extend_schema(tags=['elements'])
@extend_schema(tags=["elements"])
@extend_schema_view(
get=extend_schema(operation_id='RetrieveMetaData', description='Retrieve an existing metadata'),
patch=extend_schema(operation_id='PartialUpdateMetaData', description='Partially update an existing metadata'),
put=extend_schema(operation_id='UpdateMetaData', description='Update an existing metadata'),
delete=extend_schema(operation_id='DestroyMetaData', description='Delete an existing metadata')
get=extend_schema(operation_id="RetrieveMetaData", description="Retrieve an existing metadata"),
patch=extend_schema(operation_id="PartialUpdateMetaData", description="Partially update an existing metadata"),
put=extend_schema(operation_id="UpdateMetaData", description="Update an existing metadata"),
delete=extend_schema(operation_id="DestroyMetaData", description="Delete an existing metadata")
)
class MetadataEdit(ACLMixin, RetrieveUpdateDestroyAPIView):
"""
......@@ -1919,14 +1918,14 @@ class MetadataEdit(ACLMixin, RetrieveUpdateDestroyAPIView):
return (
MetaData
.objects
.select_related('element__corpus', 'worker_run', 'entity__worker_run')
.select_related("element__corpus", "worker_run", "entity__worker_run")
.filter(element__corpus__in=Corpus.objects.readable(self.request.user))
)
def check_object_permissions(self, request, obj):
super().check_object_permissions(request, obj)
if not self.has_access(obj.element.corpus, Role.Contributor.value):
self.permission_denied(request, message='You do not have write access to this corpus.')
self.permission_denied(request, message="You do not have write access to this corpus.")
def perform_destroy(self, instance):
serializer = self.get_serializer(instance)
......@@ -1937,12 +1936,12 @@ class AllowedMetaDataPagination(PageNumberPagination):
page_size = 200
@extend_schema(tags=['corpora'])
@extend_schema(tags=["corpora"])
@extend_schema_view(
get=extend_schema(operation_id='ListCorpusAllowedMetaDatas'),
get=extend_schema(operation_id="ListCorpusAllowedMetaDatas"),
post=extend_schema(
operation_id='CreateAllowedMetaData',
description='Create an allowed meta data in a corpus',
operation_id="CreateAllowedMetaData",
description="Create an allowed meta data in a corpus",
)
)
class CorpusAllowedMetaData(CorpusACLMixin, ListCreateAPIView):
......@@ -1959,23 +1958,23 @@ class CorpusAllowedMetaData(CorpusACLMixin, ListCreateAPIView):
role = Role.Guest
if self.request.method not in permissions.SAFE_METHODS:
role = Role.Admin
return self.get_corpus(self.kwargs['pk'], role=role)
return self.get_corpus(self.kwargs["pk"], role=role)
def get_queryset(self):
return AllowedMetaData.objects.filter(corpus=self.corpus)
def get_serializer_context(self):
context = super().get_serializer_context()
context['corpus_id'] = self.corpus.id
context["corpus_id"] = self.corpus.id
return context
@extend_schema(tags=['corpora'])
@extend_schema(tags=["corpora"])
@extend_schema_view(
get=extend_schema(operation_id='RetrieveAllowedMetaData', description='Retrieve an allowed metadata.'),
patch=extend_schema(operation_id='PartialUpdateAllowedMetaData', description='Edit an allowed metadata.'),
put=extend_schema(operation_id='UpdateAllowedMetaData', description='Edit an allowed metadata.'),
delete=extend_schema(operation_id='DestroyAllowedMetaData', description='Delete an existing allowed metadata.')
get=extend_schema(operation_id="RetrieveAllowedMetaData", description="Retrieve an allowed metadata."),
patch=extend_schema(operation_id="PartialUpdateAllowedMetaData", description="Edit an allowed metadata."),
put=extend_schema(operation_id="UpdateAllowedMetaData", description="Edit an allowed metadata."),
delete=extend_schema(operation_id="DestroyAllowedMetaData", description="Delete an existing allowed metadata.")
)
class AllowedMetaDataEdit(CorpusACLMixin, RetrieveUpdateDestroyAPIView):
permission_classes = (IsVerifiedOrReadOnly, )
......@@ -1987,18 +1986,18 @@ class AllowedMetaDataEdit(CorpusACLMixin, RetrieveUpdateDestroyAPIView):
role = Role.Guest
if self.request.method not in permissions.SAFE_METHODS:
role = Role.Admin
return self.get_corpus(self.kwargs['corpus'], role=role)
return self.get_corpus(self.kwargs["corpus"], role=role)
def get_queryset(self):
return AllowedMetaData.objects.filter(corpus=self.corpus)
def get_serializer_context(self):
context = super().get_serializer_context()
context['corpus_id'] = self.corpus.id
context["corpus_id"] = self.corpus.id
return context
@extend_schema(tags=['elements'])
@extend_schema(tags=["elements"])
class ElementTypeCreate(CreateAPIView):
"""
Create a new element type on a corpus.
......@@ -2011,7 +2010,7 @@ class ElementTypeCreate(CreateAPIView):
@extend_schema_view(
get=extend_schema(
operation_id='RetrieveElementType',
operation_id="RetrieveElementType",
description=dedent("""
Retrieve an existing element type.
......@@ -2019,7 +2018,7 @@ class ElementTypeCreate(CreateAPIView):
"""),
),
put=extend_schema(
operation_id='UpdateElementType',
operation_id="UpdateElementType",
description=dedent("""
Update an existing element type.
......@@ -2027,7 +2026,7 @@ class ElementTypeCreate(CreateAPIView):
"""),
),
patch=extend_schema(
operation_id='PartialUpdateElementType',
operation_id="PartialUpdateElementType",
description=dedent("""
Update parts of an existing element type.
......@@ -2035,7 +2034,7 @@ class ElementTypeCreate(CreateAPIView):
"""),
),
delete=extend_schema(
operation_id='DestroyElementType',
operation_id="DestroyElementType",
description=dedent("""
Delete an existing element type if it has no associated elements.
......@@ -2043,7 +2042,7 @@ class ElementTypeCreate(CreateAPIView):
""")
)
)
@extend_schema(tags=['elements'])
@extend_schema(tags=["elements"])
class ElementTypeUpdate(RetrieveUpdateDestroyAPIView):
serializer_class = ElementTypeLightSerializer
permission_classes = (IsVerifiedOrReadOnly, )
......@@ -2058,7 +2057,7 @@ class ElementTypeUpdate(RetrieveUpdateDestroyAPIView):
def perform_destroy(self, instance):
if instance.elements.exists():
raise ValidationError({'detail': ['Some elements are using this element type.']})
raise ValidationError({"detail": ["Some elements are using this element type."]})
# Update Process element type foreign keys manually because letting Django do that can fill up the RAM
instance.folder_imports.update(folder_type=None)
......@@ -2068,11 +2067,11 @@ class ElementTypeUpdate(RetrieveUpdateDestroyAPIView):
@extend_schema_view(
post=extend_schema(
operation_id='CreateElements',
tags=['elements'],
operation_id="CreateElements",
tags=["elements"],
responses=inline_serializer(
'ElementBulkCreateResponse',
fields={'id': serializers.UUIDField()},
"ElementBulkCreateResponse",
fields={"id": serializers.UUIDField()},
many=True,
),
)
......@@ -2086,10 +2085,10 @@ class ElementBulkCreate(CreateAPIView):
pagination_class = None
def get_object(self):
if not hasattr(self, 'element'):
if not hasattr(self, "element"):
self.element = super().get_object()
if not self.element.image_id:
raise ValidationError({'element': ['Cannot create child elements on an element without a zone.']})
raise ValidationError({"element": ["Cannot create child elements on an element without a zone."]})
return self.element
def get_queryset(self):
......@@ -2097,15 +2096,15 @@ class ElementBulkCreate(CreateAPIView):
return Element.objects.none()
return Element \
.objects \
.using('default') \
.using("default") \
.filter(corpus__in=Corpus.objects.writable(self.request.user)) \
.select_related('image') \
.only('id', 'corpus_id', 'rotation_angle', 'mirrored', 'image')
.select_related("image") \
.only("id", "corpus_id", "rotation_angle", "mirrored", "image")
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request:
context['element'] = self.get_object()
context["element"] = self.get_object()
return context
def create(self, request, *args, **kwargs):
......@@ -2117,56 +2116,56 @@ class ElementBulkCreate(CreateAPIView):
@transaction.atomic
def perform_create(self, serializer):
worker_run = serializer.validated_data['worker_run']
elements = serializer.validated_data['elements']
worker_run = serializer.validated_data["worker_run"]
elements = serializer.validated_data["elements"]
next_ordering = self.element.get_next_order()
# Prepare elements
for element_data in elements:
# Keep ordering in the element payload to optimize element path creation later
element_data['ordering'] = next_ordering
element_data["ordering"] = next_ordering
next_ordering += 1
element_data['element'] = Element(
element_data["element"] = Element(
id=uuid.uuid4(),
corpus_id=self.element.corpus_id,
type_id=element_data['type'],
name=element_data['name'],
type_id=element_data["type"],
name=element_data["name"],
worker_version_id=worker_run.version_id,
worker_run=worker_run,
image_id=self.element.image.id,
polygon=element_data['polygon'],
polygon=element_data["polygon"],
rotation_angle=self.element.rotation_angle,
mirrored=self.element.mirrored,
confidence=element_data['confidence'],
confidence=element_data["confidence"],
)
Element.objects.bulk_create([
element_data['element'] for element_data in elements
element_data["element"] for element_data in elements
])
# Support top level elements, by adding an empty initial path to trigger loops below
parent_paths = list(self.element.paths.all().values_list('path', flat=True))
parent_paths = list(self.element.paths.all().values_list("path", flat=True))
if not parent_paths:
parent_paths = [[]]
ElementPath.objects.bulk_create([
ElementPath(
path=parent_path + [self.element.id],
element_id=element_data['element'].id,
ordering=element_data['ordering'],
element_id=element_data["element"].id,
ordering=element_data["ordering"],
)
for parent_path in parent_paths
for element_data in elements
])
return [{'id': element_data['element'].id} for element_data in elements]
return [{"id": element_data["element"].id} for element_data in elements]
@extend_schema_view(
delete=extend_schema(
operation_id='DestroyCorpusSelection',
tags=['elements'],
operation_id="DestroyCorpusSelection",
tags=["elements"],
)
)
class CorpusSelectionDestroy(CorpusACLMixin, SelectionMixin, DestroyAPIView):
......@@ -2177,13 +2176,13 @@ class CorpusSelectionDestroy(CorpusACLMixin, SelectionMixin, DestroyAPIView):
permission_classes = (IsVerified, )
def delete(self, request, *args, **kwargs):
corpus = self.get_corpus(self.kwargs['pk'], role=Role.Admin)
corpus = self.get_corpus(self.kwargs["pk"], role=Role.Admin)
selected_elements = self.get_selection(corpus_id=corpus.id)
if not selected_elements.exists():
raise NotFound
for batch in range(0, selected_elements.count(), 50):
queryset = Element.objects.filter(id__in=list(selected_elements[batch:batch + 50].values_list('id', flat=True)))
queryset = Element.objects.filter(id__in=list(selected_elements[batch:batch + 50].values_list("id", flat=True)))
element_trash(queryset, user_id=self.request.user.id)
return Response(status=status.HTTP_204_NO_CONTENT)
......@@ -2191,35 +2190,43 @@ class CorpusSelectionDestroy(CorpusACLMixin, SelectionMixin, DestroyAPIView):
@extend_schema_view(
delete=extend_schema(
operation_id='DestroyWorkerResults',
operation_id="DestroyWorkerResults",
parameters=[
OpenApiParameter(
'worker_version_id',
"worker_run_id",
type=UUID,
required=False,
description='Only delete Worker Results produced by a specific worker version',
description="Only delete Worker Results produced by a specific worker run. "
"If this parameter is set, any `worker_version_id`, `model_version_id` "
"or `configuration_id` parameters will be ignored.",
),
OpenApiParameter(
'element_id',
"worker_version_id",
type=UUID,
required=False,
description='Only delete Worker Results under this parent element',
description="Only delete Worker Results produced by a specific worker version",
),
OpenApiParameter(
'use_selection',
"element_id",
type=UUID,
required=False,
description="Only delete Worker Results under this parent element",
),
OpenApiParameter(
"use_selection",
type=bool,
required=False,
description='Only delete Worker Results on selected elements in this corpus. '
'Cannot be used together with `element_id`.',
description="Only delete Worker Results on selected elements in this corpus. "
"Cannot be used together with `element_id`.",
),
OpenApiParameter(
'model_version_id',
"model_version_id",
type=UUID,
required=False,
description='Only delete Worker Results produced by a specific model version.',
description="Only delete Worker Results produced by a specific model version.",
),
OpenApiParameter(
'configuration_id',
"configuration_id",
type=UUID_OR_FALSE,
required=False,
description=dedent("""
......@@ -2228,115 +2235,145 @@ class CorpusSelectionDestroy(CorpusACLMixin, SelectionMixin, DestroyAPIView):
""")
),
],
tags=['ml'],
tags=["ml"],
)
)
class WorkerResultsDestroy(CorpusACLMixin, DestroyAPIView):
"""
Delete all Worker Results from all WorkerVersions or a specific one
on a Corpus or under a specified parent element (parent element included)
Delete all Worker Results, or Worker Results produced by specific WorkerRuns or WorkerVersions
(the results to delete can also be filtered by ModelVersion and Configuration)
on a Corpus, the selection, or under a specified parent element (parent element included)
"""
permission_classes = (IsVerified, )
# https://github.com/tfranzel/drf-spectacular/issues/308
@extend_schema(responses={204: None})
def delete(self, request, *args, **kwargs):
corpus = self.get_corpus(self.kwargs['corpus'], role=Role.Admin)
def results_filters(self):
errors = defaultdict(list)
use_selection = self.request.query_params.get('use_selection', 'false').lower() not in ('false', '0')
if use_selection:
# Only check for selected elements if the selection feature is enabled
if settings.ARKINDEX_FEATURES['selection']:
if 'element_id' in self.request.query_params:
errors['use_selection'].append('use_selection and element_id cannot be used simultaneously.')
if not self.request.user.selected_elements.filter(corpus=corpus).exists():
errors['use_selection'].append('No elements of the specified corpus have been selected.')
else:
errors['use_selection'].append('Selection is not available on this instance.')
element_id = None
if 'element_id' in self.request.query_params:
if "worker_run_id" in self.request.query_params:
try:
element_id = UUID(self.request.query_params['element_id'])
worker_run_id = UUID(self.request.query_params["worker_run_id"])
except (TypeError, ValueError):
errors['element_id'].append('Invalid UUID.')
raise ValidationError({"worker_run_id": ["Invalid UUID."]})
else:
if not corpus.elements.filter(id=element_id).exists():
errors['element_id'].append('This element does not exist in the specified corpus.')
try:
worker_run = WorkerRun.objects.get(id=worker_run_id)
except WorkerRun.DoesNotExist:
raise ValidationError({"worker_run_id": ["This worker run does not exist."]})
# Ignore the other parameters when a worker run ID is set
return {
"worker_run": worker_run,
}
worker_version = None
if 'worker_version_id' in self.request.query_params:
if "worker_version_id" in self.request.query_params:
try:
worker_version_id = UUID(self.request.query_params['worker_version_id'])
worker_version_id = UUID(self.request.query_params["worker_version_id"])
except (TypeError, ValueError):
errors['worker_version_id'].append('Invalid UUID.')
errors["worker_version_id"].append("Invalid UUID.")
else:
try:
# Includes the worker and revision to get a nice job display name
worker_version = WorkerVersion.objects.select_related('worker', 'revision').get(id=worker_version_id)
worker_version = WorkerVersion.objects.select_related("worker", "revision").get(id=worker_version_id)
except WorkerVersion.DoesNotExist:
errors['worker_version_id'].append('This worker version does not exist.')
errors["worker_version_id"].append("This worker version does not exist.")
model_version = None
if 'model_version_id' in self.request.query_params:
if "model_version_id" in self.request.query_params:
try:
model_version_id = UUID(self.request.query_params['model_version_id'])
model_version_id = UUID(self.request.query_params["model_version_id"])
except (TypeError, ValueError):
errors['model_version_id'].append('Invalid UUID.')
errors["model_version_id"].append("Invalid UUID.")
else:
try:
model_version = ModelVersion.objects.select_related('model').get(id=model_version_id)
model_version = ModelVersion.objects.select_related("model").get(id=model_version_id)
except ModelVersion.DoesNotExist:
errors['model_version_id'].append('This model version does not exist.')
errors["model_version_id"].append("This model version does not exist.")
configuration = None
if 'configuration_id' in self.request.query_params:
conf_id = self.request.query_params['configuration_id']
if conf_id.lower() in ('false', '0'):
if "configuration_id" in self.request.query_params:
conf_id = self.request.query_params["configuration_id"]
if conf_id.lower() in ("false", "0"):
configuration = False
else:
try:
conf_id = UUID(conf_id)
except (TypeError, ValueError):
errors['configuration_id'].append(
errors["configuration_id"].append(
'Invalid UUID. You can set "false" to exclude results with a configuration.'
)
else:
try:
configuration = WorkerConfiguration.objects.get(id=conf_id)
except WorkerConfiguration.DoesNotExist:
errors['configuration_id'].append(
'This worker configuration does not exist.'
errors["configuration_id"].append(
"This worker configuration does not exist."
)
if errors:
raise ValidationError(errors)
return {
"version": worker_version,
"model_version": model_version,
"configuration": configuration
}
# https://github.com/tfranzel/drf-spectacular/issues/308
@extend_schema(responses={204: None})
def delete(self, request, *args, **kwargs):
corpus = self.get_corpus(self.kwargs["corpus"], role=Role.Admin)
errors = defaultdict(list)
use_selection = self.request.query_params.get("use_selection", "false").lower() not in ("false", "0")
if use_selection:
# Only check for selected elements if the selection feature is enabled
if settings.ARKINDEX_FEATURES["selection"]:
if "element_id" in self.request.query_params:
errors["use_selection"].append("use_selection and element_id cannot be used simultaneously.")
if not self.request.user.selected_elements.filter(corpus=corpus).exists():
errors["use_selection"].append("No elements of the specified corpus have been selected.")
else:
errors["use_selection"].append("Selection is not available on this instance.")
element_id = None
if "element_id" in self.request.query_params:
try:
element_id = UUID(self.request.query_params["element_id"])
except (TypeError, ValueError):
errors["element_id"].append("Invalid UUID.")
else:
if not corpus.elements.filter(id=element_id).exists():
errors["element_id"].append("This element does not exist in the specified corpus.")
try:
filters = self.results_filters()
except ValidationError as errs:
errors = errors | errs.detail
if errors:
raise ValidationError(errors)
if use_selection:
selection_worker_results_delete(
corpus=corpus,
version=worker_version,
model_version=model_version,
configuration=configuration,
user_id=self.request.user.id,
**filters
)
else:
worker_results_delete(
corpus_id=corpus.id,
version=worker_version,
element_id=element_id,
model_version=model_version,
configuration=configuration,
user_id=self.request.user.id,
**filters
)
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema_view(
post=extend_schema(operation_id='MoveElement', tags=['elements']),
post=extend_schema(operation_id="MoveElement", tags=["elements"]),
)
class ElementMove(CreateAPIView):
"""
......@@ -2349,8 +2386,8 @@ class ElementMove(CreateAPIView):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
source = serializer.validated_data['source']
destination = serializer.validated_data['destination']
source = serializer.validated_data["source"]
destination = serializer.validated_data["destination"]
serializer.perform_create_checks(source, destination)
move_element(source=source, destination=destination, user_id=self.request.user.id)
......@@ -2359,7 +2396,7 @@ class ElementMove(CreateAPIView):
@extend_schema_view(
post=extend_schema(operation_id='MoveSelection', tags=['elements'])
post=extend_schema(operation_id="MoveSelection", tags=["elements"])
)
class SelectionMove(SelectionMixin, CorpusACLMixin, CreateAPIView):
"""
......@@ -2370,7 +2407,7 @@ class SelectionMove(SelectionMixin, CorpusACLMixin, CreateAPIView):
@extend_schema_view(
post=extend_schema(operation_id='CreateParentSelection', tags=['elements']),
post=extend_schema(operation_id="CreateParentSelection", tags=["elements"]),
)
class SelectionParentCreate(CreateAPIView):
"""
......
......@@ -3,32 +3,18 @@ from textwrap import dedent
from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import Q
from django.shortcuts import get_object_or_404
from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from rest_framework import permissions, serializers, status
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.generics import CreateAPIView, ListAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from arkindex.documents.models import (
Corpus,
Element,
Entity,
EntityLink,
EntityRole,
EntityType,
Transcription,
TranscriptionEntity,
)
from arkindex.documents.serializers.elements import ElementSlimSerializer
from arkindex.documents.models import Corpus, Element, Entity, EntityType, Transcription, TranscriptionEntity
from arkindex.documents.serializers.elements import ElementTinySerializer
from arkindex.documents.serializers.entities import (
BaseEntitySerializer,
CreateEntityRoleErrorResponseSerializer,
EntityCreateSerializer,
EntityLinkCreateSerializer,
EntityLinkSerializer,
EntityRoleSerializer,
EntitySerializer,
EntityTypeCreateSerializer,
EntityTypeSerializer,
......@@ -44,56 +30,9 @@ from arkindex.project.permissions import IsVerified, IsVerifiedOrReadOnly
from arkindex.users.models import Role
@extend_schema(tags=['entities'])
@extend_schema_view(
get=extend_schema(operation_id='ListCorpusRoles', description='List all roles of a corpus'),
post=extend_schema(
description='Create a new entity role',
responses={
200: EntityRoleSerializer,
400: CreateEntityRoleErrorResponseSerializer
},
examples=[OpenApiExample(
status_codes=['400'],
response_only=True,
name="role-exists",
value={'id': "55cd009d-cd4b-4ec2-a475-b060f98f9138", 'corpus': ["Role already exists in this corpus"]},
description="Role already exists."
)]
)
)
class CorpusRoles(CorpusACLMixin, ListCreateAPIView):
"""
List all roles in a corpus
"""
permission_classes = (IsVerifiedOrReadOnly, )
serializer_class = EntityRoleSerializer
queryset = EntityRole.objects.none()
def get_queryset(self):
return EntityRole.objects \
.filter(corpus=self.get_corpus(self.kwargs['pk'])) \
.order_by('parent_name', 'child_name')
def perform_create(self, serializer):
data = self.request.data
if EntityRole.objects.filter(
parent_name=data['parent_name'],
child_name=data['child_name'],
parent_type=data['parent_type_id'],
child_type=data['child_type_id'],
corpus_id=self.request.parser_context['kwargs']['pk']
).exists():
raise serializers.ValidationError({
'corpus': ['Role already exists in this corpus'],
'id': self.request.parser_context['kwargs']['pk']
})
super().perform_create(serializer)
@extend_schema(tags=['entities'])
@extend_schema(tags=["entities"])
@extend_schema_view(
get=extend_schema(operation_id='ListCorpusEntityTypes', description='List all entity types in a corpus'),
get=extend_schema(operation_id="ListCorpusEntityTypes", description="List all entity types in a corpus"),
)
class CorpusEntityTypes(CorpusACLMixin, ListAPIView):
permission_classes = (IsVerifiedOrReadOnly, )
......@@ -102,14 +41,14 @@ class CorpusEntityTypes(CorpusACLMixin, ListAPIView):
def get_queryset(self):
return EntityType.objects \
.filter(corpus=self.get_corpus(self.kwargs['pk'])) \
.order_by('name')
.filter(corpus=self.get_corpus(self.kwargs["pk"])) \
.order_by("name")
@extend_schema_view(post=extend_schema(
operation_id='CreateEntityType',
operation_id="CreateEntityType",
responses={201: EntityTypeSerializer},
tags=['entities'],
tags=["entities"],
))
class EntityTypeCreate(CreateAPIView):
"""
......@@ -122,7 +61,7 @@ class EntityTypeCreate(CreateAPIView):
@extend_schema_view(
get=extend_schema(
operation_id='RetrieveEntityType',
operation_id="RetrieveEntityType",
description=dedent("""
Retrieve an existing entity type.
......@@ -130,7 +69,7 @@ class EntityTypeCreate(CreateAPIView):
"""),
),
put=extend_schema(
operation_id='UpdateEntityType',
operation_id="UpdateEntityType",
description=dedent("""
Update an existing entity type.
......@@ -138,7 +77,7 @@ class EntityTypeCreate(CreateAPIView):
"""),
),
patch=extend_schema(
operation_id='PartialUpdateEntityType',
operation_id="PartialUpdateEntityType",
description=dedent("""
Update parts of an existing entity type.
......@@ -146,7 +85,7 @@ class EntityTypeCreate(CreateAPIView):
"""),
),
delete=extend_schema(
operation_id='DestroyEntityType',
operation_id="DestroyEntityType",
description=dedent("""
Delete an existing entity type if it has no associated entities.
......@@ -154,7 +93,7 @@ class EntityTypeCreate(CreateAPIView):
""")
)
)
@extend_schema(tags=['entities'])
@extend_schema(tags=["entities"])
class EntityTypeUpdate(ACLMixin, RetrieveUpdateDestroyAPIView):
serializer_class = EntityTypeSerializer
permission_classes = (IsVerifiedOrReadOnly, )
......@@ -168,21 +107,19 @@ class EntityTypeUpdate(ACLMixin, RetrieveUpdateDestroyAPIView):
if request.method in permissions.SAFE_METHODS:
return
if not self.has_access(obj.corpus, Role.Admin.value):
raise PermissionDenied(detail='You do not have admin access to this corpus.')
raise PermissionDenied(detail="You do not have admin access to this corpus.")
def perform_destroy(self, instance):
if instance.entities.exists():
raise ValidationError({'detail': ['Some entities are using this entity type.']})
if EntityRole.objects.filter(Q(parent_type_id=instance.id) | Q(child_type_id=instance.id)).exists():
raise ValidationError({'detail': ['Some entity roles are using this entity type.']})
raise ValidationError({"detail": ["Some entities are using this entity type."]})
super().perform_destroy(instance)
@extend_schema(tags=['entities'])
@extend_schema(tags=["entities"])
@extend_schema_view(
patch=extend_schema(description='Partially update an entity'),
put=extend_schema(description='Update an entity'),
delete=extend_schema(description='Delete an entity')
patch=extend_schema(description="Partially update an entity"),
put=extend_schema(description="Update an entity"),
delete=extend_schema(description="Delete an entity")
)
class EntityDetails(ACLMixin, RetrieveUpdateDestroyAPIView):
"""
......@@ -193,56 +130,48 @@ class EntityDetails(ACLMixin, RetrieveUpdateDestroyAPIView):
def get_queryset(self):
return Entity.objects \
.select_related('corpus', 'type') \
.select_related("corpus", "type") \
.filter(corpus__in=Corpus.objects.readable(self.request.user)) \
.prefetch_related(
'parents__role__parent_type',
'parents__role__child_type',
'children__role__parent_type',
'children__role__child_type',
'parents__child__type',
'parents__parent__type',
'children__parent__type',
'children__child__type',
'corpus',
"corpus",
)
def check_object_permissions(self, request, obj):
super().check_object_permissions(request, obj)
if self.request.method not in permissions.SAFE_METHODS and not self.has_access(obj.corpus, Role.Contributor.value):
raise PermissionDenied(detail='You do not have write access to this corpus.')
raise PermissionDenied(detail="You do not have write access to this corpus.")
@extend_schema_view(get=extend_schema(operation_id='ListEntityElements', tags=['entities']))
@extend_schema_view(get=extend_schema(operation_id="ListEntityElements", tags=["entities"]))
class EntityElements(ListAPIView):
"""
Get all elements that have a link with the entity
"""
serializer_class = ElementSlimSerializer
serializer_class = ElementTinySerializer
# For OpenAPI type discovery: an entity's ID is in the path
queryset = Entity.objects.none()
def get_queryset(self):
pk = self.kwargs['pk']
pk = self.kwargs["pk"]
metadata_elements = Element.objects \
.filter(
corpus__in=Corpus.objects.readable(self.request.user),
metadatas__entity_id=pk
) \
.select_related('type', 'corpus') \
.prefetch_related('metadatas__entity', 'image__server')
.select_related("type", "corpus") \
.prefetch_related("metadatas__entity", "image__server")
transcription_elements = Element.objects \
.filter(
corpus__in=Corpus.objects.readable(self.request.user),
transcriptions__transcription_entities__entity_id=pk
).select_related('type', 'corpus') \
.prefetch_related('metadatas__entity', 'image__server')
).select_related("type", "corpus") \
.prefetch_related("metadatas__entity", "image__server")
return metadata_elements.union(transcription_elements) \
.order_by('name', 'type')
.order_by("name", "type")
@extend_schema_view(post=extend_schema(
operation_id='CreateEntity',
operation_id="CreateEntity",
responses={
201: OpenApiResponse(
response=EntitySerializer,
......@@ -251,12 +180,12 @@ class EntityElements(ListAPIView):
),
200: EntitySerializer
},
tags=['entities'],
tags=["entities"],
parameters=[
OpenApiParameter(
'use_existing',
"use_existing",
type=bool,
description='If an entity with the same name and type already exists in the corpus, '
description="If an entity with the same name and type already exists in the corpus, "
"return this entity's UUID instead of creating a new one.",
required=False,
),
......@@ -274,19 +203,19 @@ class EntityCreate(CreateAPIView):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
name = serializer.validated_data['name']
type = serializer.validated_data['type']
corpus = serializer.validated_data['corpus']
metas = serializer.validated_data.get('metas')
worker_run = serializer.validated_data['worker_run']
name = serializer.validated_data["name"]
type = serializer.validated_data["type"]
corpus = serializer.validated_data["corpus"]
metas = serializer.validated_data.get("metas")
worker_run = serializer.validated_data["worker_run"]
worker_version_id = worker_run.version_id if worker_run else None
# When using the "use_existing" option, we return a 200_OK instead of a 201_CREATED status code
if request.data.get('use_existing'):
if request.data.get("use_existing"):
entity, created = Entity.objects.get_or_create(name=name, corpus=corpus, type=type, defaults={
'metas': metas,
'worker_version_id': worker_version_id,
'worker_run': worker_run
"metas": metas,
"worker_version_id": worker_version_id,
"worker_run": worker_run
})
entity = EntitySerializer(entity)
if created:
......@@ -307,24 +236,15 @@ class EntityCreate(CreateAPIView):
return Response(entity.data, status=status_code, headers=headers)
@extend_schema_view(post=extend_schema(operation_id='CreateEntityLink', tags=['entities']))
class EntityLinkCreate(CreateAPIView):
"""
Create a new link between two entities with a role
"""
permission_classes = (IsVerified, )
serializer_class = EntityLinkCreateSerializer
@extend_schema_view(post=extend_schema(
operation_id='CreateTranscriptionEntity',
tags=['entities'],
operation_id="CreateTranscriptionEntity",
tags=["entities"],
parameters=[
OpenApiParameter(
'id',
"id",
type=UUID,
location=OpenApiParameter.PATH,
description='ID of the transcription to link an entity to.',
description="ID of the transcription to link an entity to.",
required=True,
)
]
......@@ -346,11 +266,11 @@ class TranscriptionEntityCreate(CreateAPIView):
# We need to use the default database to avoid stale read
# when assigning a newly created entity on on a newly created transcription
tr = Transcription.objects.using('default').filter(
id=self.kwargs.get('pk'),
tr = Transcription.objects.using("default").filter(
id=self.kwargs.get("pk"),
element__corpus__in=Corpus.objects.writable(self.request.user)
).select_related('element').only('id', 'text', 'element__corpus_id').first()
return {**context, 'transcription': tr}
).select_related("element").only("id", "text", "element__corpus_id").first()
return {**context, "transcription": tr}
def perform_create(self, serializer):
data = serializer.validated_data
......@@ -363,35 +283,35 @@ class TranscriptionEntityCreate(CreateAPIView):
@extend_schema_view(
get=extend_schema(
operation_id='ListTranscriptionEntities',
tags=['entities'],
operation_id="ListTranscriptionEntities",
tags=["entities"],
parameters=[
OpenApiParameter(
'worker_version',
"worker_version",
type=UUID_OR_FALSE,
description='Only include transcription entities created by a specific worker version. '
'If set to `False`, only include transcription entities created by humans.',
description="Only include transcription entities created by a specific worker version. "
"If set to `False`, only include transcription entities created by humans.",
required=False,
),
OpenApiParameter(
'worker_run',
"worker_run",
type=UUID_OR_FALSE,
description='Only include transcription entities created by a specific worker run. '
'If set to `False`, only include transcription entities created by no worker run.',
description="Only include transcription entities created by a specific worker run. "
"If set to `False`, only include transcription entities created by no worker run.",
required=False,
),
OpenApiParameter(
'entity_worker_version',
"entity_worker_version",
type=UUID_OR_FALSE,
description='Only include transcription entities whose entity was created by a specific worker version. '
'If set to `False`, only include transcription entities whose entity was created by humans.',
description="Only include transcription entities whose entity was created by a specific worker version. "
"If set to `False`, only include transcription entities whose entity was created by humans.",
required=False,
),
OpenApiParameter(
'entity_worker_run',
"entity_worker_run",
type=UUID_OR_FALSE,
description='Only include transcription entities whose entity was created by a specific worker run. '
'If set to `False`, only include transcription entities whose entity was created by no worker run.',
description="Only include transcription entities whose entity was created by a specific worker run. "
"If set to `False`, only include transcription entities whose entity was created by no worker run.",
required=False,
),
]
......@@ -408,16 +328,16 @@ class TranscriptionEntities(ListAPIView):
queryset = Transcription.objects.none()
def parse_model_id(self, model, value):
if value.lower() in ('false', '0'):
if value.lower() in ("false", "0"):
return None
try:
validated = UUID(value)
except (TypeError, ValueError):
raise serializers.ValidationError(['Invalid UUID.'])
raise serializers.ValidationError(["Invalid UUID."])
if not model.objects.filter(id=validated).exists():
raise serializers.ValidationError([f'This {model._meta.verbose_name} does not exist.'])
raise serializers.ValidationError([f"This {model._meta.verbose_name} does not exist."])
return validated
......@@ -428,10 +348,10 @@ class TranscriptionEntities(ListAPIView):
# List of WorkerVersion and WorkerRun filters to handle:
# (query parameter, QuerySet field name, model class)
worker_filters = (
('worker_version', 'worker_version_id', WorkerVersion),
('entity_worker_version', 'entity__worker_version_id', WorkerVersion),
('worker_run', 'worker_run_id', WorkerRun),
('entity_worker_run', 'entity__worker_run_id', WorkerRun),
("worker_version", "worker_version_id", WorkerVersion),
("entity_worker_version", "entity__worker_version_id", WorkerVersion),
("worker_run", "worker_run_id", WorkerRun),
("entity_worker_run", "entity__worker_run_id", WorkerRun),
)
for query_param, field_name, model in worker_filters:
......@@ -448,7 +368,7 @@ class TranscriptionEntities(ListAPIView):
transcription = get_object_or_404(
Transcription.objects
.using("default")
.filter(id=self.kwargs['pk'], element__corpus__in=Corpus.objects.readable(self.request.user))
.filter(id=self.kwargs["pk"], element__corpus__in=Corpus.objects.readable(self.request.user))
.only("id")
)
......@@ -458,27 +378,27 @@ class TranscriptionEntities(ListAPIView):
transcription=transcription,
**filters,
)
.order_by('offset')
.select_related('entity__type', 'worker_run')
.order_by("offset")
.select_related("entity__type", "worker_run")
)
@extend_schema_view(
get=extend_schema(
operation_id='ListCorpusEntities',
tags=['entities'],
operation_id="ListCorpusEntities",
tags=["entities"],
parameters=[
OpenApiParameter(
'parent',
"parent",
type=UUID,
description='Restrict entities to those linked to all transcriptions of an element '
'and all its descendants. Note that links to metadata are ignored.',
description="Restrict entities to those linked to all transcriptions of an element "
"and all its descendants. Note that links to metadata are ignored.",
required=False,
),
OpenApiParameter(
'name',
"name",
type=str,
description='Filter entities by part of their name (case-insensitive)',
description="Filter entities by part of their name (case-insensitive)",
required=False,
)
]
......@@ -491,14 +411,14 @@ class CorpusEntities(CorpusACLMixin, ListAPIView):
serializer_class = BaseEntitySerializer
def get_queryset(self):
corpus = self.get_corpus(self.kwargs['pk'])
queryset = corpus.entities.order_by('name', 'id').select_related('type')
corpus = self.get_corpus(self.kwargs["pk"])
queryset = corpus.entities.order_by("name", "id").select_related("type")
if self.request.query_params.get('parent'):
if self.request.query_params.get("parent"):
try:
parent_id = UUID(self.request.query_params.get('parent'))
parent_id = UUID(self.request.query_params.get("parent"))
except (TypeError, ValueError):
raise serializers.ValidationError({'parent': ['Parent ID is not a valid UUID']})
raise serializers.ValidationError({"parent": ["Parent ID is not a valid UUID"]})
parent_query = corpus.elements.filter(id=parent_id)
if not parent_query.exists():
......@@ -510,54 +430,19 @@ class CorpusEntities(CorpusACLMixin, ListAPIView):
# the union to fail.
# Filtering using Q(element_id=…) | Q(element_id__in=…) is 100 times slower than filtering using a union.
element_ids = parent_query.values('id').union(Element.objects.get_descending(parent_id).order_by())
element_ids = parent_query.values("id").union(Element.objects.get_descending(parent_id).order_by())
queryset = queryset.filter(transcriptions__element_id__in=element_ids)
if self.request.query_params.get('name'):
queryset = queryset.filter(name__icontains=self.request.query_params['name'])
if self.request.query_params.get("name"):
queryset = queryset.filter(name__icontains=self.request.query_params["name"])
return queryset
@extend_schema_view(get=extend_schema(operation_id='ListElementLinks', tags=['entities']))
class ElementLinks(CorpusACLMixin, ListAPIView):
"""
List all links where parent and child are linked to the element.\n\n
Requires a **guest** access to the element corpus
"""
serializer_class = EntityLinkSerializer
def get_queryset(self):
try:
element = Element.objects.select_related('corpus').only('id', 'corpus').get(id=self.kwargs['pk'])
except Element.DoesNotExist:
raise NotFound
if not self.has_read_access(element.corpus):
raise PermissionDenied(detail='You do not have access to this element.')
# Load entities linked by transcriptions
entities_tr = Entity.objects.filter(transcriptions__element_id=element.id).prefetch_related('transcriptions')
# Load entities linked by metadatas
entities_meta = Entity.objects.filter(metadatas__element_id=element.id).prefetch_related('metadatas')
# Now load all links belonging to those entities
# It's several times faster to combine the queries in the final one
# than combining them at the lower level (entities is slower than entities_tr + entities_meta)
# We need to support cross references between transcriptions & metadata entities
return EntityLink.objects.filter(
Q(parent__in=entities_tr, child__in=entities_tr)
| Q(parent__in=entities_tr, child__in=entities_meta)
| Q(parent__in=entities_meta, child__in=entities_tr)
| Q(parent__in=entities_meta, child__in=entities_meta)
).select_related('role', 'child__type', 'parent__type').order_by('parent__name')
@extend_schema_view(
post=extend_schema(
operation_id='CreateTranscriptionEntities',
tags=['entities'],
operation_id="CreateTranscriptionEntities",
tags=["entities"],
)
)
class TranscriptionEntitiesBulk(CorpusACLMixin, CreateAPIView):
......@@ -571,16 +456,16 @@ class TranscriptionEntitiesBulk(CorpusACLMixin, CreateAPIView):
serializer_class = TranscriptionEntitiesBulkSerializer
permission_classes = (IsVerified, )
# We need to use the default database to avoid stale read on a created transcription
queryset = Transcription.objects.select_related("element__corpus").using('default')
queryset = Transcription.objects.select_related("element__corpus").using("default")
def get_object(self):
transcription = super().get_object()
if not self.has_write_access(transcription.element.corpus):
raise PermissionDenied(detail='You do not have a contributor access to the corpus of this transcription.')
raise PermissionDenied(detail="You do not have a contributor access to the corpus of this transcription.")
return transcription
def get_serializer_context(self):
return {
**super().get_serializer_context(),
'transcription': self.get_object(),
"transcription": self.get_object(),
}
......@@ -2,93 +2,119 @@ from datetime import timedelta
from textwrap import dedent
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.functional import cached_property
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import serializers, status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import ListCreateAPIView, RetrieveAPIView
from rest_framework import permissions, serializers, status
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import ListCreateAPIView, RetrieveDestroyAPIView
from rest_framework.response import Response
from arkindex.documents.models import Corpus, CorpusExport, CorpusExportState
from arkindex.documents.serializers.export import CorpusExportSerializer
from arkindex.project.mixins import CorpusACLMixin
from arkindex.project.permissions import IsVerified
from arkindex.users.models import Role
@extend_schema(tags=['exports'])
@extend_schema(tags=["exports"])
@extend_schema_view(
get=extend_schema(
operation_id='ListExports',
operation_id="ListExports",
description=(
'List all exports on a corpus.\n\n'
'Guest access is required on private corpora.'
"List all exports on a corpus.\n\n"
"Guest access is required on private corpora."
),
),
post=extend_schema(
operation_id='StartExport',
request=None,
operation_id="StartExport",
description=dedent(
f"""
Start a corpus export job.
A user must wait for {settings.EXPORT_TTL_SECONDS} seconds after the last successful import
before being able to generate a new export of the same corpus.
before being able to generate a new export of the same corpus from the same source.
Contributor access is required.
"""
),
)
)
class CorpusExportAPIView(CorpusACLMixin, ListCreateAPIView):
class CorpusExportAPIView(ListCreateAPIView):
permission_classes = (IsVerified, )
serializer_class = CorpusExportSerializer
queryset = CorpusExport.objects.none()
@cached_property
def corpus(self):
qs = Corpus.objects.readable(self.request.user)
corpus = get_object_or_404(qs, pk=self.kwargs["pk"])
if self.request.method not in permissions.SAFE_METHODS and not corpus.is_writable(self.request.user):
raise PermissionDenied(detail="You do not have write access to this corpus.")
return corpus
def get_queryset(self):
return CorpusExport \
.objects \
.filter(corpus=self.get_corpus(self.kwargs['pk'])) \
.select_related('user') \
.order_by('-created')
def post(self, *args, **kwargs):
corpus = self.get_corpus(self.kwargs['pk'], role=Role.Contributor)
if corpus.exports.filter(state__in=(CorpusExportState.Created, CorpusExportState.Running)).exists():
raise ValidationError('An export is already running for this corpus.')
.filter(corpus=self.corpus) \
.select_related("user") \
.order_by("-created")
available_exports = corpus.exports.filter(
state=CorpusExportState.Done,
created__gte=timezone.now() - timedelta(seconds=settings.EXPORT_TTL_SECONDS)
)
if available_exports.exists():
raise ValidationError(f'An export has already been made for this corpus in the last {settings.EXPORT_TTL_SECONDS} seconds.')
def get_serializer_context(self):
context = super().get_serializer_context()
context["corpus"] = self.corpus
return context
export = corpus.exports.create(user=self.request.user)
export.start()
return Response(CorpusExportSerializer(export).data, status=status.HTTP_201_CREATED)
@extend_schema(
tags=["exports"],
)
@extend_schema_view(
get=extend_schema(
operation_id="DownloadExport",
description=dedent(
"""
Download a corpus export.
class DownloadExport(RetrieveAPIView):
"""
Download a corpus export.
Guest access is required on private corpora.
"""
),
responses={302: serializers.Serializer},
),
delete=extend_schema(
operation_id="DestroyExport",
description=dedent(
"""
Delete a corpus export.
Guest access is required on private corpora.
"""
Requires either an admin access to the corpus, or for the user to be
the export's creator and have contributor access to the corpus.
"""
)
)
)
class ManageExport(RetrieveDestroyAPIView):
queryset = CorpusExport.objects.none()
permission_classes = (IsVerified, )
serializer_class = CorpusExportSerializer
def get_queryset(self):
return CorpusExport.objects.filter(
states = {CorpusExportState.Done}
if self.request.method not in permissions.SAFE_METHODS:
states.add(CorpusExportState.Running)
return CorpusExport.objects.select_related("corpus").filter(
corpus__in=Corpus.objects.readable(self.request.user),
state=CorpusExportState.Done
).only('id')
state__in=states
)
@extend_schema(
operation_id='DownloadExport',
tags=['exports'],
responses={302: serializers.Serializer},
)
def get(self, *args, **kwargs):
return Response(status=status.HTTP_302_FOUND, headers={'Location': self.get_object().s3_url})
return Response(status=status.HTTP_302_FOUND, headers={"Location": self.get_object().s3_url})
def check_object_permissions(self, request, obj):
super().check_object_permissions(request, obj)
if request.method in permissions.SAFE_METHODS:
return
if not obj.is_deletable(request.user):
raise PermissionDenied(detail="You do not have sufficient rights to delete this export.")
# Allow deleting running exports if they have not been updated in longer than EXPORT_TTL_SECONDS (not actually still running)
if obj.state == CorpusExportState.Running and obj.updated + timedelta(seconds=settings.EXPORT_TTL_SECONDS) > timezone.now():
raise ValidationError("You cannot delete an export that is still running.")
......@@ -21,9 +21,9 @@ class FolderManifest(RetrieveAPIView):
@method_decorator(cache_page(3600))
@extend_schema(
operation_id='RetrieveFolderManifest',
responses={200: {'type': 'object'}},
tags=['iiif'],
operation_id="RetrieveFolderManifest",
responses={200: {"type": "object"}},
tags=["iiif"],
)
def get(self, *args, **kwargs):
return super().get(*args, **kwargs)
......@@ -45,9 +45,9 @@ class ElementAnnotationList(RetrieveAPIView):
@method_decorator(cache_page(3600))
@extend_schema(
operation_id='RetrieveElementAnnotationList',
responses={200: {'type': 'object'}},
tags=['iiif'],
operation_id="RetrieveElementAnnotationList",
responses={200: {"type": "object"}},
tags=["iiif"],
)
def get(self, *args, **kwargs):
return super().get(*args, **kwargs)
......@@ -39,9 +39,9 @@ from arkindex.users.models import Role
@extend_schema_view(
post=extend_schema(
operation_id='CreateTranscription',
operation_id="CreateTranscription",
responses={201: TranscriptionSerializer},
tags=['transcriptions'],
tags=["transcriptions"],
)
)
class TranscriptionCreate(ACLMixin, CreateAPIView):
......@@ -52,7 +52,7 @@ class TranscriptionCreate(ACLMixin, CreateAPIView):
permission_classes = (IsVerified, )
def get_object(self):
if not hasattr(self, 'element'):
if not hasattr(self, "element"):
self.element = super().get_object()
if not self.has_access(self.element.corpus, Role.Contributor.value):
raise PermissionDenied(detail="A write access to the element's corpus is required.")
......@@ -69,15 +69,15 @@ class TranscriptionCreate(ACLMixin, CreateAPIView):
# get 404_NOT_FOUND errors on elements the user has access to.
return (
Element.objects
.using('default')
.using("default")
.filter(corpus__in=Corpus.objects.readable(self.request.user))
.select_related('corpus')
.select_related("corpus")
)
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request:
context['element'] = self.get_object()
context["element"] = self.get_object()
return context
def create(self, request, *args, **kwargs):
......@@ -92,9 +92,9 @@ class TranscriptionCreate(ACLMixin, CreateAPIView):
)
@extend_schema(tags=['transcriptions'])
@extend_schema(tags=["transcriptions"])
@extend_schema_view(
get=extend_schema(description='Retrieve a transcription.'),
get=extend_schema(description="Retrieve a transcription."),
patch=extend_schema(
description="Update a transcription's text. "
"For non-manual transcriptions, this requires an admin role on the corpus."
......@@ -103,7 +103,7 @@ class TranscriptionCreate(ACLMixin, CreateAPIView):
description="Update a transcription's text. "
"For non-manual transcriptions, this requires an admin role on the corpus."
),
delete=extend_schema(description='Delete a transcription.'),
delete=extend_schema(description="Delete a transcription."),
)
class TranscriptionEdit(ACLMixin, RetrieveUpdateDestroyAPIView):
"""
......@@ -118,7 +118,7 @@ class TranscriptionEdit(ACLMixin, RetrieveUpdateDestroyAPIView):
if not self.request:
return Transcription.objects.none()
return Transcription.objects \
.select_related('element__corpus') \
.select_related("element__corpus") \
.filter(element__corpus__in=Corpus.objects.readable(self.request.user))
def check_object_permissions(self, request, transcription):
......@@ -127,25 +127,25 @@ class TranscriptionEdit(ACLMixin, RetrieveUpdateDestroyAPIView):
return
role = Role.Contributor
detail = 'A write access to transcription element corpus is required.'
detail = "A write access to transcription element corpus is required."
if transcription.worker_version_id or transcription.worker_run_id:
role = Role.Admin
detail = 'Only admins can edit non-manual transcription.'
detail = "Only admins can edit non-manual transcription."
if not self.has_access(transcription.element.corpus, role.value):
raise PermissionDenied(detail=detail)
if self.request.method in ('PUT', 'PATCH') and transcription.transcription_entities.exists():
raise PermissionDenied(detail='Transcriptions with entities cannot be modified.')
if self.request.method in ("PUT", "PATCH") and transcription.transcription_entities.exists():
raise PermissionDenied(detail="Transcriptions with entities cannot be modified.")
@extend_schema_view(
post=extend_schema(
operation_id='CreateElementTranscriptions',
tags=['transcriptions'],
operation_id="CreateElementTranscriptions",
tags=["transcriptions"],
# Return different serializers depending on return_elements
responses=PolymorphicProxySerializer(
component_name='ElementTranscriptionsResponse',
resource_type_field_name='return_elements',
component_name="ElementTranscriptionsResponse",
resource_type_field_name="return_elements",
serializers={
True: AnnotatedElementSerializer,
False: ElementTranscriptionsBulkSerializer,
......@@ -161,10 +161,10 @@ class ElementTranscriptionsBulk(CreateAPIView):
permission_classes = (IsVerified, )
def get_object(self):
if not hasattr(self, 'element'):
if not hasattr(self, "element"):
self.element = super().get_object()
if not self.element.image_id:
raise ValidationError({'element': ['Cannot create transcriptions on an element without a zone.']})
raise ValidationError({"element": ["Cannot create transcriptions on an element without a zone."]})
return self.element
def get_queryset(self):
......@@ -175,12 +175,12 @@ class ElementTranscriptionsBulk(CreateAPIView):
# and this endpoint is immediately used after to create transcriptions
return Element.objects.filter(
corpus__in=Corpus.objects.writable(self.request.user)
).using('default').select_related('corpus', 'image')
).using("default").select_related("corpus", "image")
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request:
context['element'] = self.get_object()
context["element"] = self.get_object()
return context
def create(self, request, *args, **kwargs):
......@@ -189,7 +189,7 @@ class ElementTranscriptionsBulk(CreateAPIView):
annotations = self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
if serializer.validated_data['return_elements']:
if serializer.validated_data["return_elements"]:
# Re-serialize the annotated sub-elements
data = AnnotatedElementSerializer(annotations, many=True).data
else:
......@@ -199,9 +199,9 @@ class ElementTranscriptionsBulk(CreateAPIView):
@transaction.atomic
def perform_create(self, serializer):
elt_type = serializer.validated_data['element_type']
worker_run = serializer.validated_data['worker_run']
annotations = serializer.validated_data['transcriptions']
elt_type = serializer.validated_data["element_type"]
worker_run = serializer.validated_data["worker_run"]
annotations = serializer.validated_data["transcriptions"]
# Retrieve or create elements to attach transcriptions to
missing_elements = []
......@@ -212,31 +212,31 @@ class ElementTranscriptionsBulk(CreateAPIView):
for element in Element
.objects
.get_descending(self.element.id)
.using('default')
.using("default")
.filter(
image_id=self.element.image_id,
type=elt_type,
paths__path__overlap=[self.element.id],
paths__path__last=self.element.id
)
.only('id', 'polygon')
.only("id", "polygon")
}
# Load the paths immediately to avoid iterating over them for each element
# Use the default DB to avoid stale reads that could cause the new child elements
# to not be in the parent element's parents
paths = list(self.element.paths.using('default').values_list('path', flat=True))
paths = list(self.element.paths.using("default").values_list("path", flat=True))
if not paths:
# Support top level elements, by adding an empty initial path to trigger loops below
paths = [[]]
next_path_ordering = self.element.get_next_order()
for annotation in annotations:
# Look for a direct children with the right type and zone
annotation['element'] = children.get(annotation['polygon'].wkb)
if not annotation['element']:
annotation['element'] = Element(
annotation["element"] = children.get(annotation["polygon"].wkb)
if not annotation["element"]:
annotation["element"] = Element(
id=uuid.uuid4(),
image_id=self.element.image_id,
polygon=annotation['polygon'],
polygon=annotation["polygon"],
corpus_id=self.element.corpus_id,
type=elt_type,
name=next_path_ordering + 1,
......@@ -244,17 +244,17 @@ class ElementTranscriptionsBulk(CreateAPIView):
mirrored=self.element.mirrored,
worker_version_id=worker_run.version_id,
worker_run=worker_run,
confidence=annotation.get('element_confidence'),
confidence=annotation.get("element_confidence"),
)
# Specify the annotated element has been created
annotation['created'] = True
children[annotation['polygon'].wkb] = annotation['element']
missing_elements.append(annotation['element'])
annotation["created"] = True
children[annotation["polygon"].wkb] = annotation["element"]
missing_elements.append(annotation["element"])
for parent_path in paths:
new_path = parent_path + [self.element.id]
# Add the children to all of its parent paths
missing_paths.append(ElementPath(
element=annotation['element'],
element=annotation["element"],
path=new_path,
ordering=next_path_ordering
))
......@@ -267,14 +267,14 @@ class ElementTranscriptionsBulk(CreateAPIView):
transcriptions = []
for annotation in annotations:
transcription = Transcription(
element=annotation['element'],
element=annotation["element"],
worker_version_id=worker_run.version_id,
worker_run=worker_run,
text=annotation['text'],
confidence=annotation['confidence'],
orientation=annotation['orientation']
text=annotation["text"],
confidence=annotation["confidence"],
orientation=annotation["orientation"]
)
annotation['id'] = transcription.id
annotation["id"] = transcription.id
transcriptions.append(transcription)
# Create missing transcriptions in bulk
Transcription.objects.bulk_create(transcriptions)
......@@ -283,11 +283,11 @@ class ElementTranscriptionsBulk(CreateAPIView):
return annotations
@extend_schema_view(post=extend_schema(operation_id='CreateTranscriptions', tags=['transcriptions']))
@extend_schema_view(post=extend_schema(operation_id="CreateTranscriptions", tags=["transcriptions"]))
class TranscriptionBulk(CreateAPIView):
'''
"""
Create multiple transcriptions at once on existing elements
'''
"""
permission_classes = (IsVerified, )
serializer_class = TranscriptionBulkSerializer
......@@ -296,14 +296,14 @@ class CorpusMLClassPagination(PageNumberPagination):
page_size = 40
@extend_schema(tags=['classifications'])
@extend_schema(tags=["classifications"])
@extend_schema_view(
get=extend_schema(
operation_id='ListCorpusMLClasses',
operation_id="ListCorpusMLClasses",
),
post=extend_schema(
operation_id='CreateMLClass',
description='Create an ML class in a corpus',
operation_id="CreateMLClass",
description="Create an ML class in a corpus",
)
)
class CorpusMLClassList(CorpusACLMixin, ListCreateAPIView):
......@@ -315,15 +315,15 @@ class CorpusMLClassList(CorpusACLMixin, ListCreateAPIView):
# For OpenAPI type discovery: a corpus ID is in the path
queryset = Corpus.objects.none()
filter_backends = [SafeSearchFilter]
search_fields = ['name']
search_fields = ["name"]
permission_classes = (IsVerifiedOrReadOnly, )
@cached_property
def corpus(self):
role = Role.Guest
if self.request.method == 'POST':
if self.request.method == "POST":
role = Role.Contributor
return self.get_corpus(self.kwargs['pk'], role=role)
return self.get_corpus(self.kwargs["pk"], role=role)
def check_permissions(self, *args, **kwargs):
"""
......@@ -346,50 +346,50 @@ class CorpusMLClassList(CorpusACLMixin, ListCreateAPIView):
self.corpus
def get_queryset(self):
return MLClass.objects.filter(corpus=self.corpus).using('default').order_by('name', 'id')
return MLClass.objects.filter(corpus=self.corpus).using("default").order_by("name", "id")
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request.method == 'POST':
context['corpus_id'] = self.corpus
if self.request.method == "POST":
context["corpus_id"] = self.corpus
return context
@extend_schema(tags=['classifications'])
@extend_schema(tags=["classifications"])
@extend_schema_view(
get=extend_schema(description='Retrieve a ML class.'),
patch=extend_schema(description='Rename a ML class.'),
put=extend_schema(description='Rename a ML class.'),
delete=extend_schema(description='Delete a ML class if it is not used by any classification.'),
get=extend_schema(description="Retrieve a ML class."),
patch=extend_schema(description="Rename a ML class."),
put=extend_schema(description="Rename a ML class."),
delete=extend_schema(description="Delete a ML class if it is not used by any classification."),
)
class MLClassRetrieve(CorpusACLMixin, RetrieveUpdateDestroyAPIView):
serializer_class = MLClassSerializer
queryset = MLClass.objects.none()
permission_classes = (IsVerified, )
lookup_url_kwarg = 'mlclass'
lookup_url_kwarg = "mlclass"
@cached_property
def corpus(self):
role = Role.Guest
if self.request and self.request.method != 'GET':
if self.request and self.request.method != "GET":
role = Role.Contributor
return self.get_corpus(self.kwargs['corpus'], role=role)
return self.get_corpus(self.kwargs["corpus"], role=role)
def get_queryset(self):
return self.corpus.ml_classes.all()
def get_serializer_context(self):
context = super().get_serializer_context()
context['corpus_id'] = self.corpus
context["corpus_id"] = self.corpus
return context
def check_object_permissions(self, request, obj):
if self.request and self.request.method == 'DELETE' and obj.classifications.count() != 0:
raise ValidationError(['This ML class is used by some classifications on this corpus.'])
if self.request and self.request.method == "DELETE" and obj.classifications.count() != 0:
raise ValidationError(["This ML class is used by some classifications on this corpus."])
@extend_schema(tags=['classifications'])
@extend_schema(tags=["classifications"])
class ClassificationCreate(CreateAPIView):
"""
Add a single classification on an element. Can be used by end users & machine learning tools.
......@@ -399,7 +399,7 @@ class ClassificationCreate(CreateAPIView):
permission_classes = (IsVerified, )
def perform_create(self, serializer):
if serializer.validated_data['worker_run'] is None:
if serializer.validated_data["worker_run"] is None:
# A manual classification is immediately valid
serializer.save(
moderator=self.request.user,
......@@ -412,7 +412,7 @@ class ClassificationCreate(CreateAPIView):
serializer.save()
@extend_schema(tags=['classifications'])
@extend_schema(tags=["classifications"])
class ClassificationBulk(CreateAPIView):
"""
Create multiple classifications at once on the same element from a single WorkerRun.
......@@ -421,7 +421,7 @@ class ClassificationBulk(CreateAPIView):
permission_classes = (IsVerified, )
@extend_schema(tags=['classifications'])
@extend_schema(tags=["classifications"])
class ManageClassificationsSelection(SelectionMixin, CorpusACLMixin, CreateAPIView):
"""
Manage classifications for a list of selected elements for a specific corpus.
......@@ -433,11 +433,11 @@ class ManageClassificationsSelection(SelectionMixin, CorpusACLMixin, CreateAPIVi
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
corpus = serializer.validated_data['corpus_id']
corpus = serializer.validated_data["corpus_id"]
if not self.has_write_access(corpus):
raise PermissionDenied(detail='You do not have contributor access to this corpus.')
raise PermissionDenied(detail="You do not have contributor access to this corpus.")
mode = serializer.validated_data['mode']
mode = serializer.validated_data["mode"]
if mode == ClassificationMode.Create:
return self.create(corpus, request, *args, **kwargs)
elif mode == ClassificationMode.Validate:
......@@ -451,14 +451,14 @@ class ManageClassificationsSelection(SelectionMixin, CorpusACLMixin, CreateAPIVi
raise NotImplementedError
def create(self, corpus, request, *args, **kwargs):
ml_class = MLClass.objects.filter(id=request.data['ml_class']).first()
ml_class = MLClass.objects.filter(id=request.data["ml_class"]).first()
elements = self.get_selection(corpus.id)
existing_element_ids = set(Classification.objects.filter(
element_id__in=elements,
ml_class_id=ml_class.id,
worker_version_id=None,
).values_list('element_id', flat=True))
).values_list("element_id", flat=True))
classifications = []
for element in elements.exclude(id__in=existing_element_ids):
......@@ -478,7 +478,7 @@ class ManageClassificationsSelection(SelectionMixin, CorpusACLMixin, CreateAPIVi
@extend_schema(
tags=['classifications'],
tags=["classifications"],
request=None,
)
class ClassificationModerationActionsMixin(GenericAPIView):
......@@ -492,12 +492,12 @@ class ClassificationModerationActionsMixin(GenericAPIView):
instance = self.get_object()
instance.moderator = self.request.user
instance.state = self.moderation_action
instance.save(update_fields=['moderator', 'state'])
instance.save(update_fields=["moderator", "state"])
serializer = self.get_serializer(instance)
return Response(serializer.data, status=status.HTTP_200_OK)
@extend_schema_view(put=extend_schema(operation_id='ValidateClassification'))
@extend_schema_view(put=extend_schema(operation_id="ValidateClassification"))
class ClassificationValidate(ClassificationModerationActionsMixin):
"""
Validate an existing classification.
......@@ -514,12 +514,12 @@ class ClassificationReject(ClassificationModerationActionsMixin):
moderation_action = ClassificationState.Rejected
@extend_schema(
operation_id='RejectClassification',
operation_id="RejectClassification",
responses={
200: ClassificationSerializer,
204: OpenApiResponse(
response=None,
description='The classification has been deleted.',
description="The classification has been deleted.",
)
}
)
......@@ -533,6 +533,6 @@ class ClassificationReject(ClassificationModerationActionsMixin):
instance.moderator = self.request.user
instance.state = self.moderation_action
instance.save(update_fields=['moderator', 'state'])
instance.save(update_fields=["moderator", "state"])
serializer = self.get_serializer(instance)
return Response(serializer.data, status=status.HTTP_200_OK)
......@@ -29,14 +29,14 @@ def parse_facet(name, value):
if isinstance(value, (MetaType, EntityType)):
value = value.value
# Escape quotes and backslashes to avoid query injection
value = value.replace('\\', '\\\\').replace('"', '\\"')
value = value.replace("\\", "\\\\").replace('"', '\\"')
return f'{name}:"{value}"'
@extend_schema_view(
get=extend_schema(
operation_id='SearchCorpus',
tags=['search'],
operation_id="SearchCorpus",
tags=["search"],
parameters=[CorpusSearchQuerySerializer],
responses=CorpusSearchResultSerializer
)
......@@ -47,68 +47,68 @@ class CorpusSearch(CorpusACLMixin, RetrieveAPIView):
"""
def build_solr_query(self, query, sources, facets):
sources_query = " OR ".join(f'{source}_text:({query})' for source in sources)
sources_query = " OR ".join(f"{source}_text:({query})" for source in sources)
facets_query = " AND ".join(parse_facet(name, value) for name, value in facets.items())
return f'({sources_query}) AND ({facets_query})' if facets_query else sources_query
return f"({sources_query}) AND ({facets_query})" if facets_query else sources_query
def solr_search(self, collection_name, query, sort, page):
sort_params = {
'relevance': 'score desc',
'element_name': 'element_text asc',
"relevance": "score desc",
"element_name": "element_text asc",
}
if sort not in sort_params:
raise ValueError('Unknown sort parameter')
raise ValueError("Unknown sort parameter")
return solr.query(collection_name, {
'q': query,
'start': (page - 1) * settings.SOLR_PAGINATION_SIZE,
'sort': sort_params[sort],
'rows': settings.SOLR_PAGINATION_SIZE,
'facet': True,
'facet.field': [
'element_type',
'element_worker',
'transcription_worker',
'classification_name',
'classification_worker',
'metadata_name',
'metadata_type',
'metadata_worker',
'entity_type',
'entity_worker'
"q": query,
"start": (page - 1) * settings.SOLR_PAGINATION_SIZE,
"sort": sort_params[sort],
"rows": settings.SOLR_PAGINATION_SIZE,
"facet": True,
"facet.field": [
"element_type",
"element_worker",
"transcription_worker",
"classification_name",
"classification_worker",
"metadata_name",
"metadata_type",
"metadata_worker",
"entity_type",
"entity_worker"
]
})
def build_pagination(self, url, page, nb_results):
nb_page = math.ceil(nb_results / settings.SOLR_PAGINATION_SIZE)
previous_url = replace_query_param(url, 'page', page - 1) if page > 1 else None
next_url = replace_query_param(url, 'page', page + 1) if page < nb_page else None
previous_url = replace_query_param(url, "page", page - 1) if page > 1 else None
next_url = replace_query_param(url, "page", page + 1) if page < nb_page else None
return previous_url, next_url
def get(self, request, *args, **kwargs):
if not settings.ARKINDEX_FEATURES['search']:
raise ValidationError(['Search features are not available on this instance.'])
if not settings.ARKINDEX_FEATURES["search"]:
raise ValidationError(["Search features are not available on this instance."])
corpus = self.get_corpus(kwargs['pk'])
collection_name = f'project-{corpus.id}'
corpus = self.get_corpus(kwargs["pk"])
collection_name = f"project-{corpus.id}"
if not corpus.indexable:
raise ValidationError([f'Corpus {corpus.id} is not indexable.'])
raise ValidationError([f"Corpus {corpus.id} is not indexable."])
if not solr.collections.exists(collection_name):
raise NotFound(f'Corpus index {collection_name} not found.')
raise NotFound(f"Corpus index {collection_name} not found.")
# Serialize params
params = request.query_params.dict()
# Convert the sources string into a valid list
# Support both possible urls
if 'sources' in params or 'sources[]' in params:
params['sources'] = request.query_params.getlist('sources') + request.query_params.getlist('sources[]')
if "sources" in params or "sources[]" in params:
params["sources"] = request.query_params.getlist("sources") + request.query_params.getlist("sources[]")
serializer = CorpusSearchQuerySerializer(data=params)
serializer.is_valid(raise_exception=True)
q, sources, only_facets, sort, page = map(
lambda key: serializer.validated_data.pop(key),
('query', 'sources', 'only_facets', 'sort', 'page')
("query", "sources", "only_facets", "sort", "page")
)
# Paginated Solr search
......@@ -123,16 +123,16 @@ class CorpusSearch(CorpusACLMixin, RetrieveAPIView):
previous_url, next_url = self.build_pagination(request.build_absolute_uri(), page, nb_results)
return Response(CorpusSearchResultSerializer({
'count': nb_results if not only_facets else 0,
'number': page,
'next': next_url,
'previous': previous_url,
'results': results.docs if not only_facets else None,
'facets': results.get_facets()
"count": nb_results if not only_facets else 0,
"number": page,
"next": next_url,
"previous": previous_url,
"results": results.docs if not only_facets else None,
"facets": results.get_facets()
}).data, status=status.HTTP_200_OK)
@extend_schema_view(post=extend_schema(operation_id="BuildSearchIndex", tags=['search']))
@extend_schema_view(post=extend_schema(operation_id="BuildSearchIndex", tags=["search"]))
class SearchIndexBuild(CorpusACLMixin, CreateAPIView):
"""
Starts an indexation task for a specific corpus, ran by RQ
......@@ -142,23 +142,23 @@ class SearchIndexBuild(CorpusACLMixin, CreateAPIView):
@cached_property
def corpus(self):
corpus = self.get_corpus(self.kwargs['pk'], role=Role.Admin)
corpus = self.get_corpus(self.kwargs["pk"], role=Role.Admin)
if not corpus.indexable:
raise ValidationError({'__all__': ['This project is not indexable.']})
raise ValidationError({"__all__": ["This project is not indexable."]})
if not corpus.types.filter(indexable=True).exists():
raise ValidationError({'__all__': ['There are no indexable element types for this project.']})
raise ValidationError({"__all__": ["There are no indexable element types for this project."]})
return corpus
def get_serializer_context(self):
return {
**super().get_serializer_context(),
'corpus_id': self.corpus.id,
'user_id': self.request.user.id,
"corpus_id": self.corpus.id,
"user_id": self.request.user.id,
}
def create(self, request, *args, **kwargs):
if not settings.ARKINDEX_FEATURES['search']:
if not settings.ARKINDEX_FEATURES["search"]:
raise ValidationError({
'__all__': ['Building search index is unavailable due to the search feature being disabled.']
"__all__": ["Building search index is unavailable due to the search feature being disabled."]
})
return super().create(request, *args, **kwargs)
......@@ -2,7 +2,7 @@ from django.apps import AppConfig
class DocumentsConfig(AppConfig):
name = 'arkindex.documents'
name = "arkindex.documents"
def ready(self):
from arkindex.documents import signals # noqa: F401
......