diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..60ebab26ee6f9f599d7c523df5286dbae27c27f4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,63 @@ +FROM ubuntu:latest + +RUN apt-get update +RUN apt-get install python3 python3-pip -y +# FROM ubuntu:22.04 + +# RUN apt update +# RUN apt-get update +# RUN apt install python3.10 python3-pip -y + +# https://stackoverflow.com/questions/75608323/how-do-i-solve-error-externally-managed-environment-every-time-i-use-pip-3 +# https://veronneau.org/python-311-pip-and-breaking-system-packages.html +ENV PIP_BREAK_SYSTEM_PACKAGES 1 + + +################################################## +# Ubuntu setup +################################################## + +RUN apt-get update \ + && apt-get install -y wget \ + && rm -rf /var/lib/apt/lists/* + +RUN apt-get update && apt-get -y upgrade \ + && apt-get install -y --no-install-recommends \ + unzip \ + nano \ + git \ + g++ \ + gcc \ + htop \ + zip \ + ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +################################################## +# ODTP setup +################################################## + +# Set up a new user named "user" with user ID 1000 +#RUN useradd -m -u 1000 user + +# Switch to the "user" user +USER 1000 + +# Set home to the user's home directory +ENV HOME=/home/user \ + PATH=/home/user/.local/bin:$PATH + +# Set the working directory to the user's home directory +WORKDIR $HOME/digiwild + +# Try and run pip command after setting the user with `USER user` to avoid permission issues with Python +RUN pip install --no-cache-dir --upgrade pip + +# Copy the current directory contents into the container at $HOME/app setting the owner to the user +COPY --chown=1000:1000 . $HOME/digiwild + +RUN pip3 install -r $HOME/digiwild/requirements.txt + +#RUN chown -R user:user /digiwild/data /digiwild/app/assets + +ENTRYPOINT ["python3", "/home/user/digiwild/app/main.py"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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/>. diff --git a/app/.DS_Store b/app/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..fbafeea98564ef9a71432e0e3ed8fdcbc07f2c36 Binary files /dev/null and b/app/.DS_Store differ diff --git a/app/.env.dist b/app/.env.dist new file mode 100644 index 0000000000000000000000000000000000000000..aab89b466c36b9c6fdd50b3821a6623f79841a16 --- /dev/null +++ b/app/.env.dist @@ -0,0 +1 @@ +PATH_ASSETS="YOUR_PATH_HERE" \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/__pycache__/__init__.cpython-312.pyc b/app/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c0f2575ef5593f9c9a861b5ec5e4faaa8a43902 Binary files /dev/null and b/app/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/__pycache__/classes.cpython-312.pyc b/app/__pycache__/classes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d9d3304d8dc767c60e93557f0c3bf1ccad8f6d5 Binary files /dev/null and b/app/__pycache__/classes.cpython-312.pyc differ diff --git a/app/__pycache__/dead.cpython-312.pyc b/app/__pycache__/dead.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d4c4981dfddaac94891c67275a43b09ed8ea455 Binary files /dev/null and b/app/__pycache__/dead.cpython-312.pyc differ diff --git a/app/__pycache__/display.cpython-312.pyc b/app/__pycache__/display.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..020a538db97088c4c1229314e6573a9e28dd7e21 Binary files /dev/null and b/app/__pycache__/display.cpython-312.pyc differ diff --git a/app/__pycache__/main.cpython-312.pyc b/app/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45be587bdd8fe2938f527a3c9ec17136179076fa Binary files /dev/null and b/app/__pycache__/main.cpython-312.pyc differ diff --git a/app/__pycache__/wounded.cpython-312.pyc b/app/__pycache__/wounded.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8614b12b94ea06f33e0c7219e2055f24ed633bd4 Binary files /dev/null and b/app/__pycache__/wounded.cpython-312.pyc differ diff --git a/app/assets/.DS_Store b/app/assets/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..710f36ee1d45b564fdc6b79b02a9e63eee6ef7dc Binary files /dev/null and b/app/assets/.DS_Store differ diff --git a/app/assets/config/config_checkbox_behavior.json b/app/assets/config/config_checkbox_behavior.json new file mode 100644 index 0000000000000000000000000000000000000000..73ebacfba6ea4871668d3fc191737a3d821ba179 --- /dev/null +++ b/app/assets/config/config_checkbox_behavior.json @@ -0,0 +1,42 @@ +{ + "Abnormal breathing": + { + "Description": "Problems breathing, breathing sounds" + }, + "Crash, Falling from the sky": + { + "Description": "Suddenly falling from the sky" + }, + "Diarrhea": + { + "Description": "Observed diarrhea" + }, + "Lameness": + { + "Description": "Apparent limping or not able to walk properly" + }, + "Neurological": + { + "Description": "Circling, incoordination, tremors, convulsions, fast eye movements" + }, + "Other abnormal behavior": + { + "Description": "Other than weakness, other than neurologic" + }, + "Unable to fly": + { + "Description": "Animal alert and tries to fly but can not take off" + }, + "Vomiting": + { + "Description": "Throwing up undigested food, regurgitating" + }, + "Weakness": + { + "Description": "Non responsive, does not fly away when approached, lethargy" + }, + "No changes": + { + "Description": "Animal is acting normally" + } +} \ No newline at end of file diff --git a/app/assets/config/config_checkbox_physical.json b/app/assets/config/config_checkbox_physical.json new file mode 100644 index 0000000000000000000000000000000000000000..5533d751f665af16c13b261d2c289c4483f74230 --- /dev/null +++ b/app/assets/config/config_checkbox_physical.json @@ -0,0 +1,68 @@ +{ + "Common": + { + "Blackened/burnt skin": { + "Description": "Burnt/ blackened/ charred skin or feathers"}, + "Blood": { + "Description": "Visible blood"}, + "Foreign body": { + "Description": "Objects in feathers"}, + "Fracture": { + "Description": "Obvious bone fracture"}, + "Injury": { + "Description": "Visible skin injury"}, + "Parasite": { + "Description": "Maggots, fleas, lice, louseflies"}, + "Swelling": { + "Description": "Marked swelling without injury"}, + "Warty or tumor-like growth, crusts": { + "Description": "Unusual growth, crusty tumor-like growth"} + }, + "Beak": + { + "Adhesion": { + "Description": "Material (food, saliva) around/ in the beak" + }, + "Deformation": { + "Description": "Unusual beak growth" + } + }, + "Body": + { + "Emaciation": { + "Description": "Breast muscles are not well developed"}, + "Fluffed up": { + "Description": "Plumage is fluffed up"}, + "Stained feathers": { + "Description": "Feces, dirt, dried blood"} + }, + "Feathers/Wings/Tail": + { + "Fluffed up": { + "Description": "Plumage is fluffed up"}, + "Feather abnormalities": { + "Description": "Discoloration, broken/ missing feathers"}, + "Stained feathers": { + "Description": "Feces, dirt, dried blood"}, + "Abnormal wing posture": { + "Description": "Wing is not used/ hangs on the side"}, + "Missing limb": { + "Description": "Missing limb"} + }, + "Head incl. eyes": + { + "Ear changes": { + "Description": "Swollen, crusts, plugged, discharge"}, + "Eye changes": { + "Description": "Red, swollen, discharge, crusts, eyes shut"}, + "Tilted head": { + "Description": "Wry neck, unusual neck posture, torticollis"} + }, + "Legs": + { + "Missing limb": { + "Description": "Missing limb"}, + "Deformation": { + "Description": "Abnormal form of limbs, toes, legs"} + } +} diff --git a/app/assets/config/config_dropdown_circumstances.json b/app/assets/config/config_dropdown_circumstances.json new file mode 100644 index 0000000000000000000000000000000000000000..8cdf696d322431d5c09d53c205b7245f60760043 --- /dev/null +++ b/app/assets/config/config_dropdown_circumstances.json @@ -0,0 +1,138 @@ +{ + "Collision with a means of transport": + { + "road vehicle": + { + "Options": { + "road_type" : ["highway", "main road", "secondary road", "local road/path/trail", "parking lot", "other road", "unknown road"] + }, + "Open": "Infrastructure_number" + }, + "train": + { + "Open": "Infrastructure_number" + }, + "aircraft": {}, + "boat": {}, + "other transport collision": {}, + "unknown": {} + }, + "Destruction / Deliberatly removed" : + { + "hunting": + { + "Options": { + "method" : ["shooting", "bow", "falconry", + "hounds hunting", "digging up", "other hunting", "unknow hunting"] + } + }, + "trap": + { + "Options": { + "method": ["killing trap", "pole trap", + "trap cage", "corvids nasse", "net", "cage trap", + "fall-trap", "glue trap", "insect trap", "other trap", "unknown trap"] + } + }, + "poisoning": {}, + "removal or direct capture": + { + "Options": {"method": ["gassing", "raptor captured at nest", + "brood destruction", "traffic/trade", "capture accident", + "scientific sample", "other removal", "unknown removal"] + } + }, + "fishing": + { + "Options": {"method" : ["drowned/tangled", "beached with capture indications", + "other fishing", "unknown fishing"] + } + }, + "other destruction": {}, + "unknown": {} + }, + "Indirect destruction": + { + "pylone and electric grid": + { + + "Options": { + "infrastructure" : ["electric line", "pole/pylon", "other structure", "unknown structure"] + }, + "Extra": + { + "Cause": ["collision", "electrocution"] + } + }, + "windfarm": {}, + "other collision": + { + "Options": { + "object": ["window", "building", "lighthouse", "cable", "wire fence/barbed wire", "other crash", "unknown crash"] + } + }, + "fall": + { + "Options": { + "location": ["chimney", "empty pole", "hole/well", "other fall", "unknown fall"] + } + }, + "development work": + { + "Options": { + "work_type" : ["transport infrastructure", "building", "other work", "unknown work"] + } + }, + "pollution / contamination": + { + "Options": { + "pollution_type" : ["oil pollution", "chemical pollution", "heavy metals", + "light", "noise", "plastic ingestion", "other pollution", "unknown pollution"] + }, + "agricultural net protection": {}, + "vegetal / forest work": + { + "Options": { + "work_type" : ["clearing/mowing/plowing", "tree felling/pruning", + "other forest work", "unknown forest work"] + } + } + }, + "other indirect destruction": {}, + "unknown": {} + }, + "Natural cause": + { + "predation": + { + "Options": { + "predator" : ["cat", "dog", "rooster/hen", "other domestic animal", "wild birds", + "wild mammal", "other predator", "unknown predator"] + } + }, + "weather": + { + "Options": { + "condition" : ["cold wave", "drought", "hail", "lightening", "storm", "other weather", "unknown weather"] + } + }, + "natural disaster": + { + "Options": { + "disaster" : ["fire", "avalanche", "rock fall", "mudslide", "volcanic eruption/ashes", "other natural disaster", "unknown natural disaster"] + } + }, + "nest fall": {}, + "stranding due to exhaustion": {}, + "disease/parasite": {}, + "accidental drowing": + { + "Options": { + "drowning_location" : ["drinking trough", "pool", "storm pool", "irrigation pool", "natural pool", "flood", "other location", "unknown location"] + } + }, + "other natural cause": {}, + "unknown": {} + }, + "Unknown": {} +} diff --git a/app/assets/config/config_followup.json b/app/assets/config/config_followup.json new file mode 100644 index 0000000000000000000000000000000000000000..b4de7d85069be7b2fdae89a347e0c4b2826a8527 --- /dev/null +++ b/app/assets/config/config_followup.json @@ -0,0 +1,23 @@ +{ + "Event follow-up": + { + "Animal collected": { + "Options": ["Yes", "No"] + }, + "Recipient": { + "Options": ["Veterinary", "Care center", "Local Museum", "National Museum", "Other"] + }, + "Radiography": { + "Options": ["Yes", "No", "Unknown"] + }, + "Given answer": { + "Options": ["Nothing", "Complaint against X", "Complaint", "Police call", "Discussion with the speaker", "Press release", "Unknown"] + }, + "Name of recipient / museum": { + "Open": {} + }, + "Collection reference": { + "Open": {} + } + } +} \ No newline at end of file diff --git a/app/assets/fonts/LiberationSans-Regular.ttf b/app/assets/fonts/LiberationSans-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..59d2e251b04ce9540c1915c5bd153cd1a709390c Binary files /dev/null and b/app/assets/fonts/LiberationSans-Regular.ttf differ diff --git a/app/assets/images/bird.png b/app/assets/images/bird.png new file mode 100644 index 0000000000000000000000000000000000000000..a559db324d241b852af1afa71affb6d0003bc244 Binary files /dev/null and b/app/assets/images/bird.png differ diff --git a/app/assets/images/bird_boxed.png b/app/assets/images/bird_boxed.png new file mode 100644 index 0000000000000000000000000000000000000000..1459e0263550396bab706f06542b44b8a17879a9 Binary files /dev/null and b/app/assets/images/bird_boxed.png differ diff --git a/app/assets/images/empty_image.jpg b/app/assets/images/empty_image.jpg new file mode 100644 index 0000000000000000000000000000000000000000..afa6733e7f8924bb2d362d15271a9270fa47413c Binary files /dev/null and b/app/assets/images/empty_image.jpg differ diff --git a/app/assets/logos/destruction.png b/app/assets/logos/destruction.png new file mode 100644 index 0000000000000000000000000000000000000000..416cbba762e786c2f060260d7c856d1a5ba6a51e Binary files /dev/null and b/app/assets/logos/destruction.png differ diff --git a/app/assets/logos/indirect.png b/app/assets/logos/indirect.png new file mode 100644 index 0000000000000000000000000000000000000000..26bf942860941d3a48007419225a185306bc91b0 Binary files /dev/null and b/app/assets/logos/indirect.png differ diff --git a/app/assets/logos/natural.png b/app/assets/logos/natural.png new file mode 100644 index 0000000000000000000000000000000000000000..e507e240ab9c55ba4024ac21c5f294474dfc6cc0 Binary files /dev/null and b/app/assets/logos/natural.png differ diff --git a/app/assets/logos/van.png b/app/assets/logos/van.png new file mode 100644 index 0000000000000000000000000000000000000000..1fb05912b28fa578e05ec0fc664b07fc9883e21c Binary files /dev/null and b/app/assets/logos/van.png differ diff --git a/app/assets/tmp_json/.gitkeep b/app/assets/tmp_json/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/assets/tmp_json/tmp_wounded_dead.json b/app/assets/tmp_json/tmp_wounded_dead.json new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/app/assets/tmp_json/tmp_wounded_dead.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/app/behavior/__init__.py b/app/behavior/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/behavior/__pycache__/__init__.cpython-312.pyc b/app/behavior/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..913df0ef6a819ee665ee3738d136ae3d8d66312e Binary files /dev/null and b/app/behavior/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/behavior/__pycache__/behavior_checkbox.cpython-312.pyc b/app/behavior/__pycache__/behavior_checkbox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e210f5d1f0a86117a1f9a2e0b444131d0ac184f Binary files /dev/null and b/app/behavior/__pycache__/behavior_checkbox.cpython-312.pyc differ diff --git a/app/behavior/__pycache__/class_behavior.cpython-312.pyc b/app/behavior/__pycache__/class_behavior.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91743657d467f8e9728be5e98425dcc3da58aa19 Binary files /dev/null and b/app/behavior/__pycache__/class_behavior.cpython-312.pyc differ diff --git a/app/behavior/behavior_checkbox.py b/app/behavior/behavior_checkbox.py new file mode 100644 index 0000000000000000000000000000000000000000..70c4a445314b705f3eed0917803d26d74f60206e --- /dev/null +++ b/app/behavior/behavior_checkbox.py @@ -0,0 +1,30 @@ +import gradio as gr +from utils.utils_config import get_custom_config_dropdowns +from utils.utils_checkbox import create_checkbox +from utils.utils_visible import set_visible +from validation_submission.add_json import add_data_tmp + +def on_select_behavior(behavior_checkbox): + behavior_checkbox = [behavior.lower() for behavior in behavior_checkbox] + add_data_tmp("wounded_dead", "behaviors_type", behavior_checkbox) + +def retrieve_behavior_options_description(): + dropdown_config = get_custom_config_dropdowns("config_checkbox_behavior.json") + options = list(dropdown_config.keys()) + options = [option.title() for option in options] + descriptions =[] + for _,subdict in dropdown_config.items(): + descriptions.append(subdict["Description"]) + return options, descriptions + +def create_behavior_checkbox(section: str, visible): + options, descriptions = retrieve_behavior_options_description() + label_checkbox = "Behavior changes observed" + checkbox, text = create_checkbox("", section, label_checkbox, visible, options, descriptions) + return checkbox, text + +def show_behavior(choice, section: str): + visible = set_visible(choice) + checkbox, text = create_behavior_checkbox(section, visible) + add_data_tmp("wounded_dead", "behaviors_radio", choice) + return checkbox, text \ No newline at end of file diff --git a/app/behavior/class_behavior.py b/app/behavior/class_behavior.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8d89dfec6764108bb4374e44f2a89a5d00b621 --- /dev/null +++ b/app/behavior/class_behavior.py @@ -0,0 +1,66 @@ +from pydantic import BaseModel, Field +from typing import Literal, List, Union, Optional + +class Behavior(BaseModel): + type: str + description: Optional[str] = None # Making the description field optional + +# --- Specific Behavior classes --- +class AbnormalBreathing(Behavior): + type: Literal['abnormal breathing'] + description: Optional[Literal["Problems breathing, breathing sounds"]] = None + +class CrashFalling(Behavior): + type: Literal['crash, falling from the sky'] + description: Optional[Literal["Suddenly falling from the sky"]] = None + +class Diarrhea(Behavior): + type: Literal['diarrhea'] + description: Optional[Literal["Observed diarrhea"]] = None + +class Lameness(Behavior): + type: Literal['lameness'] + description: Optional[Literal["Apparent limping or not able to walk properly"]] = None + +class Neurological(Behavior): + type: Literal['neurological'] + description: Optional[Literal["Circling, incoordination, tremors, convulsions, fast eye movements"]] = None + +class OtherAbnormalBehavior(Behavior): + type: Literal['other abnormal behavior'] + description: Optional[Literal["Other than weakness, other than neurologic"]] = None + +class UnableToFly(Behavior): + type: Literal['unable to fly'] + description: Optional[Literal["Animal alert and tries to fly but can not take off"]] = None + +class Vomiting(Behavior): + type: Literal['vomiting'] + description: Optional[Literal["Throwing up undigested food, regurgitating"]] = None + +class Weakness(Behavior): + type: Literal['weakness'] + description: Optional[Literal["Non responsive, does not fly away when approached, lethargy"]] = None + +class NoChanges(Behavior): + type: Literal['no changes'] + description: Optional[Literal["Animal is acting normally"]] = None + +# Union of all possible behaviors +BehaviorType = Union[ + AbnormalBreathing, + CrashFalling, + Diarrhea, + Lameness, + Neurological, + OtherAbnormalBehavior, + UnableToFly, + Vomiting, + Weakness, + NoChanges +] + +# Main class that logs multiple behaviors +class Behaviors(BaseModel): + behaviors_radio: str # e.g., "Yes" + behaviors_type: Optional[List[BehaviorType]] = None diff --git a/app/circumstances/__init__.py b/app/circumstances/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/circumstances/__pycache__/__init__.cpython-312.pyc b/app/circumstances/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ea055ffc3ae20a2005b5a334fde14ee85e607c Binary files /dev/null and b/app/circumstances/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/circumstances/__pycache__/circumstances.cpython-312.pyc b/app/circumstances/__pycache__/circumstances.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a79b388c48d46655e6ba3e1935d6603e38ec5227 Binary files /dev/null and b/app/circumstances/__pycache__/circumstances.cpython-312.pyc differ diff --git a/app/circumstances/__pycache__/circumstances_dropdowns.cpython-312.pyc b/app/circumstances/__pycache__/circumstances_dropdowns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30348dce971d7822857524d7f07addc57341a11a Binary files /dev/null and b/app/circumstances/__pycache__/circumstances_dropdowns.cpython-312.pyc differ diff --git a/app/circumstances/__pycache__/class_circumstance.cpython-312.pyc b/app/circumstances/__pycache__/class_circumstance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47af52d54738188667ee5275406c6a4d313a59d2 Binary files /dev/null and b/app/circumstances/__pycache__/class_circumstance.cpython-312.pyc differ diff --git a/app/circumstances/circumstances.py b/app/circumstances/circumstances.py new file mode 100644 index 0000000000000000000000000000000000000000..602268d031d2ecd279019adb194e8e438246e71b --- /dev/null +++ b/app/circumstances/circumstances.py @@ -0,0 +1,67 @@ +import gradio as gr +import os +from dotenv import load_dotenv + +from utils.utils_visible import set_visible +from validation_submission.add_json import add_data_tmp + +load_dotenv() +PATH = os.getcwd() + "/" +PATH_ASSETS = os.getenv('PATH_ASSETS') +LOGO_PATH = PATH + PATH_ASSETS + "logos" + +CAUSE_COL_WIDTH = "50px" + + +def show_circumstances(choice): + visible = set_visible(choice) + add_data_tmp("wounded_dead", + "circumstance_radio", + choice) + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 = create_circumstances(visible) + return button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 + +def create_circumstances(visible): + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause = create_circumstances_buttons(visible) + dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 = create_circumstances_dropdown(visible) + return button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 + +def create_circumstances_buttons(visible): + with gr.Row() as image_row: + with gr.Column(scale=1, min_width=CAUSE_COL_WIDTH): + button_collision = gr.Button("Collision with a means of transport", + visible=visible, + icon=LOGO_PATH + '/van.png', + elem_id="buttons-conditions") + + with gr.Column(scale=1, min_width=CAUSE_COL_WIDTH): + button_deliberate_destruction = gr.Button("Destruction / Deliberatly removed", + icon=LOGO_PATH + '/destruction.png', + visible=visible, + elem_id="buttons-conditions") + + with gr.Column(scale=1, min_width=CAUSE_COL_WIDTH): + button_indirect_destruction = gr.Button("Indirect destruction", + icon=LOGO_PATH + '/indirect.png', + visible=visible, + elem_id="buttons-conditions") + + with gr.Column(scale=1, min_width=CAUSE_COL_WIDTH): + button_natural_cause = gr.Button("Natural cause", + icon=LOGO_PATH + '/natural.png', + visible=visible, + elem_id="buttons-conditions") + return button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause + +def create_circumstances_dropdown(visible): + with gr.Row() as dropdown_row: + dropdown = gr.Dropdown(choices=[], + label="Choices will appear here...", + visible=visible, interactive=False, elem_id="dropdown-conditions") + openfield_level2 = gr.Textbox(visible=False, elem_id="dropdown-conditions") + dropdown_level2 = gr.Dropdown(choices=[], visible=False, elem_id="dropdown-conditions") + dropdown_extra_level2 = gr.Dropdown(choices=[], visible=False, elem_id="dropdown-conditions") + return dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 + + + \ No newline at end of file diff --git a/app/circumstances/circumstances_dropdowns.py b/app/circumstances/circumstances_dropdowns.py new file mode 100644 index 0000000000000000000000000000000000000000..a562620a61dae08a3b0392a3faa8cd27b1f6079a --- /dev/null +++ b/app/circumstances/circumstances_dropdowns.py @@ -0,0 +1,112 @@ +import gradio as gr +from utils.utils_config import get_custom_config_dropdowns +from validation_submission.add_json import add_data_tmp + +#--------------------------------------------------------- LEVEL 1 DROPDOWNS +def retrieve_config_options(label, dropdown_config): + options = list(dropdown_config[label].keys()) + options = [option.title() for option in options] + return options + +def reinitialise_level2(): + dropdown_level2 = gr.Dropdown(choices=[], visible=False) + openfield_level2 = gr.Textbox(visible=False) + dropdown_extra_level2 = gr.Dropdown(choices=[], visible=False) + return dropdown_level2, openfield_level2, dropdown_extra_level2 + +def create_dropdown_level1(label): + dropdown_config = get_custom_config_dropdowns("config_dropdown_circumstances.json") + options = retrieve_config_options(label, dropdown_config) + dropdown = gr.Dropdown(choices=options, label=label, interactive=True, visible=True) + dropdown_level2, openfield_level2, dropdown_extra_level2 = reinitialise_level2() + return dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 + +def dropdown_collision(): + label = "Collision with a means of transport" + add_data_tmp("wounded_dead", "circumstance", label.lower()) + return create_dropdown_level1(label) + +def dropdown_deliberate_destruction(): + label = "Destruction / Deliberatly removed" + add_data_tmp("wounded_dead", "circumstance", label.lower()) + return create_dropdown_level1(label) + +def dropdown_indirect_destruction(): + label = "Indirect destruction" + add_data_tmp("wounded_dead", "circumstance", label.lower()) + return create_dropdown_level1(label) + +def dropdown_natural_cause(): + label = "Natural cause" + add_data_tmp("wounded_dead", "circumstance", label.lower()) + return create_dropdown_level1(label) + + +#--------------------------------------------------------- LEVEL 2 DROPDOWNS +def get_options(value): + value = value.lower() + options_label = None + options_dropdown= None + open_field = None + extras = None + extras_label = None + dropdown_config = get_custom_config_dropdowns("config_dropdown_circumstances.json") + for _, sub_dict in dropdown_config.items(): + nested_dict = sub_dict.get(value) + if nested_dict is not None: + if "Options" in nested_dict.keys(): + options_dict = nested_dict["Options"] + options_label = list(options_dict.keys())[0] + options_dropdown = list(options_dict.values())[0] + options_dropdown = [option.title() for option in options_dropdown] + if "Open" in nested_dict.keys(): + open_field = nested_dict["Open"] + open_field = open_field.title() + if "Extra" in nested_dict.keys(): + for key, val in nested_dict["Extra"].items(): + extras_label = key + extras = val + extras = [extra.title() for extra in extras] + return options_label, options_dropdown, open_field, extras, extras_label + + +def on_select(evt: gr.SelectData): # SelectData is a subclass of EventData + options_label, options_dropdown, open_field, extras, extras_label = get_options(evt.value) + add_data_tmp("wounded_dead", + "circumstance_type", + {"type": (evt.value).lower(), + "option_dropdown_label" : options_label.lower() if options_label is not None else 'NA', + "open_field_label" : open_field.lower() if open_field is not None else 'NA', + "extra_label": extras_label.lower() if extras_label is not None else 'NA' + }) + if options_dropdown is not None: + dropdown_level2 = gr.Dropdown(choices=options_dropdown, label=evt.value, interactive=True, visible=True) + else: + dropdown_level2 = gr.Dropdown(choices=[], visible=False) + + if open_field is not None: + openfield_level2 = gr.Textbox(label=open_field, interactive=True, visible=True) + else: + openfield_level2 = gr.Textbox(visible=False) + + if extras is not None: + dropdown_extra_level2 = gr.Dropdown(choices=extras, label=extras_label, interactive=True, visible=True) + else: + dropdown_extra_level2 = gr.Dropdown(choices=[], visible=False) + return dropdown_level2, openfield_level2, dropdown_extra_level2 + +def on_select_dropdown_level2(evt: gr.SelectData): + add_data_tmp("wounded_dead", + "circumstance_option_dropdown", + evt.value.lower()) + +def on_select_dropdown_extra_level2(evt: gr.SelectData): + add_data_tmp("wounded_dead", + "circumstance_extra", + evt.value.lower()) + +def on_change_openfield_level2(openfield_level2_dead): + print("Saving open field") + add_data_tmp("wounded_dead", + "circumstance_open_field", + str(openfield_level2_dead).lower()) \ No newline at end of file diff --git a/app/circumstances/class_circumstance.py b/app/circumstances/class_circumstance.py new file mode 100644 index 0000000000000000000000000000000000000000..935f42a24ddf19c1e8c7047cdad72159e7c778e6 --- /dev/null +++ b/app/circumstances/class_circumstance.py @@ -0,0 +1,205 @@ +from pydantic import BaseModel, Field +from typing import Literal, List, Union, Optional + +# Base class for CircumstanceType with a discriminator field 'type' +class CircumstanceTypeBase(BaseModel): + type: str + +# Collision with means of transport +class RoadVehicleCollision(CircumstanceTypeBase): + type: Literal['road_vehicle'] + infrastructure_number: Optional[str] = None + road_type: Literal['highway', 'main road', + 'secondary road', 'local road/path/trail', + 'parking lot'] + +class TrainCollision(CircumstanceTypeBase): + type: Literal['train'] + infrastructure_number: str + +class AircraftCollision(CircumstanceTypeBase): + type: Literal['aircraft'] + +class BoatCollision(CircumstanceTypeBase): + type: Literal['boat'] + +class OtherTransportCollision(CircumstanceTypeBase): + type: Literal['other transport collision'] + +class UnknownTransportCollision(CircumstanceTypeBase): + type: Literal['unknown transport collision'] + +# Destruction / Deliberately removed +class HuntingDestruction(CircumstanceTypeBase): + type: Literal['hunting'] + method: Literal['shooting', 'bow', 'falconry', + 'hounds hunting', 'digging up', + "other hunting", "unknow hunting"] + +class TrapDestruction(CircumstanceTypeBase): + type: Literal['trap'] + method: Literal['killing trap', 'pole trap', 'trap cage', 'corvids nasse', + 'net', 'cage trap', 'fall-trap', 'glue trap', 'insect trap', + "other trap", "unknown trap"] + +class PoisoningDestruction(CircumstanceTypeBase): + type: Literal['poisoning'] + +class RemovalDestruction(CircumstanceTypeBase): + type: Literal['removal or direct capture'] + method: Literal['gassing', 'raptor captured at nest', 'brood destruction', + 'traffic/trade', 'capture accident', 'scientific sample', + "other removal", "unknown removal"] + +class FishingDestruction(CircumstanceTypeBase): + type: Literal['fishing'] + method: Literal['drowned/tangled', 'beached with capture indications', "other fishing", "unknown fishing"] + +class OtherDestruction(CircumstanceTypeBase): + type: Literal['other destruction'] + +class UnknownDestruction(CircumstanceTypeBase): + type: Literal['unknown destruction'] + +# Indirect destruction +class PylonElectricGridDestruction(CircumstanceTypeBase): + type: Literal['pylone and electric grid'] + infrastructure: Literal['electric line', 'pole/pylon', "other structure", "unknown structure"] + cause: Literal['collision', 'electrocution'] + +class WindfarmDestruction(CircumstanceTypeBase): + type: Literal['windfarm'] + +class OtherCollisionDestruction(CircumstanceTypeBase): + type: Literal['other collision'] + object: Literal['window', 'building', 'lighthouse', + 'cable', 'wire fence/barbed wire', 'other crash', 'unknown crash'] + +class FallDestruction(CircumstanceTypeBase): + type: Literal['fall'] + location: Literal['chimney', 'empty pole', 'hole/well', 'other fall', 'unknown fall'] + +class DevelopmentWorkDestruction(CircumstanceTypeBase): + type: Literal['development work'] + work_type: Literal['transport infrastructure', 'building', 'other work', 'unknown work'] + +class PollutionContaminationDestruction(CircumstanceTypeBase): + type: Literal['pollution / contamination'] + pollution_type: Literal['oil pollution', 'chemical pollution', 'heavy metals', + 'light', 'noise', + 'plastic ingestion', 'other pollution', 'unknown pollution'] + +class AgriculturalNetProtectionDestruction(CircumstanceTypeBase): + type: Literal['agricultural net protection'] + +class VegetalForestWorkDestruction(CircumstanceTypeBase): + type: Literal['vegetal / forest work'] + work_type: Literal['clearing/mowing/plowing', 'tree felling/pruning', + 'other forest work', 'unknown forest work'] + +class OtherIndirectDestruction(CircumstanceTypeBase): + type: Literal['other indirect desctruction'] + +class UnknownIndirectDestruction(CircumstanceTypeBase): + type: Literal['unknown indirect desctruction'] + +# Natural cause +class Predation(CircumstanceTypeBase): + type: Literal['predation'] + predator: Literal['cat', 'dog', 'rooster/hen', + 'other domestic animal', 'wild birds', + 'wild mammal', 'other predator', 'unknown predator'] + +class Weather(CircumstanceTypeBase): + type: Literal['weather'] + condition: Literal['cold wave', 'drought', 'hail', + 'lightening', 'storm', + 'other weather', 'unknown weather'] + +class NaturalDisaster(CircumstanceTypeBase): + type: Literal['natural disaster'] + disaster: Literal['fire', 'avalanche', 'rock fall', + 'mudslide', 'volcanic eruption/ashes', + 'other natural disaster', 'unknown natural disaster'] + +class NestFall(CircumstanceTypeBase): + type: Literal['nest fall'] + +class StrandingExhaustion(CircumstanceTypeBase): + type: Literal['stranding due to exhaustion'] + +class DiseaseParasite(CircumstanceTypeBase): + type: Literal['disease/parasite'] + +class AccidentalDrowning(CircumstanceTypeBase): + type: Literal['accidental drowning'] + drowning_location: Literal['drinking trough', 'pool', + 'storm pool', 'irrigation pool', + 'natural pool', 'flood', + 'other location', 'unknown location'] + +class OtherNaturalCause(CircumstanceTypeBase): + type: Literal['other natural cause'] + +class UnknownNaturalCause(CircumstanceTypeBase): + type: Literal['unknown natural cause'] + +# Unknown cause +class UnknownCircumstance(CircumstanceTypeBase): + type: Literal['unknown'] + +# Union of all possible CircumstanceTypes with 'type' as the discriminator +CircumstanceType = Union[ + RoadVehicleCollision, + TrainCollision, + AircraftCollision, + BoatCollision, + OtherTransportCollision, + UnknownTransportCollision, + HuntingDestruction, + TrapDestruction, + PoisoningDestruction, + RemovalDestruction, + FishingDestruction, + OtherDestruction, + UnknownDestruction, + PylonElectricGridDestruction, + WindfarmDestruction, + OtherCollisionDestruction, + FallDestruction, + DevelopmentWorkDestruction, + PollutionContaminationDestruction, + AgriculturalNetProtectionDestruction, + VegetalForestWorkDestruction, + OtherIndirectDestruction, + UnknownIndirectDestruction, + Predation, + Weather, + NaturalDisaster, + NestFall, + StrandingExhaustion, + DiseaseParasite, + AccidentalDrowning, + OtherNaturalCause, + UnknownNaturalCause, + UnknownCircumstance +] + +# Main Circumstance class +class Circumstances(BaseModel): + circumstance_radio: str # e.g., "Yes" + circumstance: Optional[str] = None # e.g., "COLLISION" + circumstance_type: Optional[CircumstanceType] = Field(None, discriminator='type') + + +# Example usage +# json_data = { +# "circumstance": "COLLISION", +# "circumstance_radio": "Yes", +# "circumstance_type": { +# "type": "Train", +# "infrastructure_number": "56" +# } +# } +# circumstance_instance = Circumstance(**json_data) +# circumstance_schema = Circumstance.schema_json(indent=2) \ No newline at end of file diff --git a/app/classes.py b/app/classes.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a0679acaf1ba556c7efb70008c940ba57524e3 --- /dev/null +++ b/app/classes.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel, Field +from typing import Optional +import numpy as np +from PIL import Image +import io +import base64 +import uuid + +from behavior.class_behavior import Behaviors +from circumstances.class_circumstance import Circumstances +from physical.class_physical import PhysicalAnomalies +from follow_up.class_follow_up import FollowUpEvents +from geolocalisation.class_geolocalisation import Geolocalisation + +class Wounded(BaseModel): + circumstances: Circumstances + behaviors: Behaviors + physical_anomalies: PhysicalAnomalies + follow_up_events: FollowUpEvents + +class Dead(BaseModel): + circumstances: Circumstances + physical_anomalies: PhysicalAnomalies + follow_up_events: FollowUpEvents + +class ImageBase64(BaseModel): + image: str + @classmethod + def to_base64(cls, pixel_data: list): + img_array = np.array(pixel_data, dtype=np.uint8) + img = Image.fromarray(img_array) + # Save the image to a bytes buffer + buffer = io.BytesIO() + img.save(buffer, format="PNG") + buffer.seek(0) + base64_str = base64.b64encode(buffer.read()).decode('utf-8') + return cls(image=base64_str) + +class Report(BaseModel): + identifier: str + image: ImageBase64 + geolocalisation: Geolocalisation + wounded_state: str + wounded: Optional[Wounded] = None + dead_state: str + dead: Optional[Dead] = None diff --git a/app/dead.py b/app/dead.py new file mode 100644 index 0000000000000000000000000000000000000000..20a87ef66536f33834b816eabe83b7a3a694cebc --- /dev/null +++ b/app/dead.py @@ -0,0 +1,40 @@ +import gradio as gr +from circumstances.circumstances import create_circumstances +from physical.physical_select_animal import create_bird_anatomy +from physical.physical_checkbox import process_body_parts +from follow_up.followup_events import create_followup_dropdowns, create_followup_open +from validation_submission.add_json import add_data_to_individual + +def show_section_dead(visible): + if visible==True: + add_data_to_individual("wounded_state", "No") + add_data_to_individual("dead_state", "Yes") + + with gr.Column(visible=visible, elem_id="dead") as section_dead: + gr.Markdown("# Dead Animal") + + gr.Markdown("## Do you know what conditions caused this?", label="description") + radio_cause = gr.Radio(["Yes", "No"], value=None, show_label=False, interactive=True) + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 = create_circumstances(visible=False) + + gr.Markdown("## Are there physical changes on the bird?" , label="description") + radio_physical = gr.Radio(["Yes", "No"], value=None, show_label=False, interactive=True) + with gr.Row(): + physical_boxes = create_bird_anatomy(False, "dead") + with gr.Column(): + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs = process_body_parts("dead", "None") + + gr.Markdown("## Follow-Up Events", label="Title") + gr.Markdown("Please tell us what you did with the animal.", label="description") + with gr.Row(): + fe_collection_dropdown, fe_recepient_dropdown, fe_radio_dropdown, fe_answer_dropdown = create_followup_dropdowns(visible, "dead") + with gr.Row(): + fe_name_recipient, fe_collection_ref = create_followup_open(visible, "dead") + + + return section_dead, radio_cause, radio_physical,\ + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, \ + dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2, \ + physical_boxes, \ + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs, \ + fe_collection_dropdown, fe_recepient_dropdown, fe_radio_dropdown, fe_answer_dropdown, fe_name_recipient, fe_collection_ref diff --git a/app/display.py b/app/display.py new file mode 100644 index 0000000000000000000000000000000000000000..9f1fdf92860e9fd06148504de3b54d892c82b61c --- /dev/null +++ b/app/display.py @@ -0,0 +1,120 @@ +import gradio as gr +import pandas as pd +from gradio_modal import Modal +from PIL import Image +from io import BytesIO +import base64 + +from validation_submission.submission import validate_save_individual +from validation_submission.get_json import get_json_all_individuals + +HEADERS = ["Identifier", "Location", "Wounded", "Dead"] + + +def save_display_individual(gallery, df, error_box): + individual, error_box = validate_save_individual(error_box) + if individual: + all_animals = get_json_all_individuals() + gallery_animals = process_animals_for_gallery(all_animals) + gallery = make_gallery(gallery_animals) + df_animals = process_animals_for_df(all_animals) + df = make_df(df_animals) + return gallery, df, error_box + +# ---------------------------------- +# GALLERY + +def convert_image(image_base64_str): + im = Image.open(BytesIO(base64.b64decode(image_base64_str))) + return im + +def set_gallery_size(len_animals): + if len_animals < 10: + num_cols=5 + num_rows=2 + else: + num_cols = len_animals/2 + num_rows = len_animals/(num_cols) + return num_cols, num_rows + +def process_animals_for_gallery(all_animals): + gallery_animals = [] + for _, animal in all_animals.items(): + image = convert_image(animal["image"]["image"]) + caption = animal["identifier"] + animal = (image, caption) + gallery_animals.append(animal) + return gallery_animals + +def make_gallery(gallery_animals): + num_cols, num_rows = set_gallery_size(len(gallery_animals)) + gallery = gr.Gallery( + label="Gallery of Records", elem_id="gallery", + columns=[num_cols], rows=[num_rows], + value=gallery_animals, + object_fit="contain", height="auto", interactive=False) + return gallery + +def keep_only_values(dict_to_filter): + info_text = "" + values_to_ignore = ["Yes", "No", "NA"] + if dict_to_filter: + for key, val in dict_to_filter.items(): + if type(val) is dict: + subset_text = keep_only_values(val) + info_text += f"{subset_text}" + elif type(val) is list: + for item in val: + if type(item) is dict: + subset_text = keep_only_values(item) + info_text += f"{subset_text}" + elif (val is not None) and (type(val) is not bool) and (val not in values_to_ignore): + info_text += f" {key} : {val} |" + else: + print("Ignoring value: ", val) + print("Associated key: ", key) + else: + info_text = "NaN" + return info_text + +# ---------------------------------- +# DATAFRAME + +def process_animals_for_df(all_animals): + df_animals = {} + identifiers =[] + geo =[] + wounded =[] + dead =[] + for _, animal in all_animals.items(): + identifier_value = animal["identifier"] + identifiers.append(identifier_value) + geo_dict = animal["geolocalisation"] + geo_values = keep_only_values(geo_dict) + geo.append(geo_values) + wounded_dict = animal["wounded"] + wounded_values = keep_only_values(wounded_dict) + wounded.append(wounded_values) + dead_dict = animal["dead"] + dead_values = keep_only_values(dead_dict) + dead.append(dead_values) + df_animals["Identifier"] = identifiers + df_animals["Location"] = geo + df_animals["Wounded"] = wounded + df_animals["Dead"] = dead + return df_animals + + +def make_df(df_animals): + df = pd.DataFrame.from_dict(df_animals) + styled_df = df.style.set_properties(**{ + 'min-width': '25px', + 'max-width': '50px', # Adjust width as needed + 'white-space': 'normal', # Allows text to wrap to the next line + 'word-wrap': 'break-word' # Breaks long words to fit within the width + }) + df_gradio = gr.DataFrame(visible=True, + value=styled_df, + headers=HEADERS, interactive=False) + return df_gradio + diff --git a/app/follow_up/__pycache__/class_follow_up.cpython-312.pyc b/app/follow_up/__pycache__/class_follow_up.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..393c9df40faf230d76c5fcb9d544efeffaf90373 Binary files /dev/null and b/app/follow_up/__pycache__/class_follow_up.cpython-312.pyc differ diff --git a/app/follow_up/__pycache__/followup_events.cpython-312.pyc b/app/follow_up/__pycache__/followup_events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..539f07232de462cfca104f8b8fa8d1288f549950 Binary files /dev/null and b/app/follow_up/__pycache__/followup_events.cpython-312.pyc differ diff --git a/app/follow_up/class_follow_up.py b/app/follow_up/class_follow_up.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff1cfe5769d5ec668b19cdca860450efa113111 --- /dev/null +++ b/app/follow_up/class_follow_up.py @@ -0,0 +1,50 @@ +from pydantic import BaseModel, Field +from typing import Literal, Union, Optional, List + +# --- Event follow-up classes --- + +class AnimalCollectedEvent(BaseModel): + type: Literal['animal collected'] + collected: Literal['yes', 'no'] + +class RecipientEvent(BaseModel): + type: Literal['recipient'] + recipient: Literal['veterinary', 'care center', + 'local museum', 'national museum', + 'other'] + +class RadiographyEvent(BaseModel): + type: Literal['radiography'] + radiography: Literal['yes', 'no', 'unknown'] + +class GivenAnswerEvent(BaseModel): + type: Literal['given answer'] + answer: Literal[ + 'nothing', + 'complaint against x', + 'complaint', + 'police call', + 'discussion with the speaker', + 'press release', + 'unknown' + ] + +class NameOfRecipientEvent(BaseModel): + type: Literal['recipient name'] + name: str + +class CollectionReferenceEvent(BaseModel): + type: Literal['collection reference'] + reference: str + +FollowUpEventType = Union[ + AnimalCollectedEvent, + RecipientEvent, + RadiographyEvent, + GivenAnswerEvent, + NameOfRecipientEvent, + CollectionReferenceEvent +] + +class FollowUpEvents(BaseModel): + follow_up_events: Optional[List[FollowUpEventType]] = None \ No newline at end of file diff --git a/app/follow_up/followup_events.py b/app/follow_up/followup_events.py new file mode 100644 index 0000000000000000000000000000000000000000..11bad2183a6ab8473c3293758a8afe6efa0d989d --- /dev/null +++ b/app/follow_up/followup_events.py @@ -0,0 +1,46 @@ +import gradio as gr +from utils.utils_config import get_custom_config_dropdowns +from validation_submission.add_json import add_data_tmp + +def create_followup_dropdowns(visible, elem_id): + followup_config = get_custom_config_dropdowns("config_followup.json") + followup_config = followup_config["Event follow-up"] + fe_collection_dropdown = create_fe_collection_dropdown(followup_config, visible, elem_id) + fe_recipient_dropdown = create_fe_recipient_dropdown(followup_config, visible, elem_id) + fe_radio_dropdown = create_fe_radio_dropdown(followup_config, visible, elem_id) + fe_answer_dropdown = create_fe_answer_dropdown(followup_config, visible, elem_id) + return fe_collection_dropdown, fe_recipient_dropdown, fe_radio_dropdown, fe_answer_dropdown + +def create_followup_open(visible, elem_id): + fe_name_recipient = gr.Textbox(label="Name of recipient / museum", visible=visible, + elem_id=elem_id, interactive=True) + fe_collection_ref = gr.Textbox(label="Collection reference", visible=visible, + elem_id=elem_id, interactive=True) + return fe_name_recipient, fe_collection_ref + + +def create_fe_collection_dropdown(followup_config, visible, elem_id): + fe_collection_dropdown = gr.Dropdown(choices=followup_config["Animal collected"]["Options"], label="Animal collected", + visible=visible, elem_id=elem_id, interactive=True) + return fe_collection_dropdown + +def create_fe_recipient_dropdown(followup_config, visible, elem_id): + fe_recipient_dropdown = gr.Dropdown(choices=followup_config["Recipient"]["Options"], label="Recipient", + visible=visible, elem_id=elem_id, interactive=True) + return fe_recipient_dropdown + +def create_fe_radio_dropdown(followup_config, visible, elem_id): + fe_radio_dropdown = gr.Dropdown(choices=followup_config["Radiography"]["Options"], label="Radiography", + visible=visible, elem_id=elem_id, interactive=True) + return fe_radio_dropdown + +def create_fe_answer_dropdown(followup_config, visible, elem_id): + fe_answer_dropdown = gr.Dropdown(choices=followup_config["Given answer"]["Options"], label="Given answer", + visible=visible, elem_id=elem_id, interactive=True) + return fe_answer_dropdown + +def save_fe(value, key): + add_data_tmp("wounded_dead", "followup " + key.lower(), value.lower()) + + + \ No newline at end of file diff --git a/app/geolocalisation/__init__.py b/app/geolocalisation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/geolocalisation/__pycache__/__init__.cpython-312.pyc b/app/geolocalisation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..744b6efcac14808b208473d4fbe9afc15617eec5 Binary files /dev/null and b/app/geolocalisation/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/geolocalisation/__pycache__/class_geolocalisation.cpython-312.pyc b/app/geolocalisation/__pycache__/class_geolocalisation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..567e67c0b75f62ab4e7f75db524c2a07d6d52054 Binary files /dev/null and b/app/geolocalisation/__pycache__/class_geolocalisation.cpython-312.pyc differ diff --git a/app/geolocalisation/__pycache__/js_geolocation.cpython-312.pyc b/app/geolocalisation/__pycache__/js_geolocation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c67ea65b7204c4600fc3d53154cb2044e62d98c9 Binary files /dev/null and b/app/geolocalisation/__pycache__/js_geolocation.cpython-312.pyc differ diff --git a/app/geolocalisation/__pycache__/maps.cpython-312.pyc b/app/geolocalisation/__pycache__/maps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c35d1194bea626e876aeefefd8d0e27962b1f36d Binary files /dev/null and b/app/geolocalisation/__pycache__/maps.cpython-312.pyc differ diff --git a/app/geolocalisation/class_geolocalisation.py b/app/geolocalisation/class_geolocalisation.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0f0a5316a51f5314abddcc8bd7970c010932ce --- /dev/null +++ b/app/geolocalisation/class_geolocalisation.py @@ -0,0 +1,16 @@ +from pydantic import BaseModel, Field +from typing import Literal, List, Union + +class Longitude(BaseModel): + type: Literal['longitude'] + value: float + +class Latitude(BaseModel): + type: Literal['latitude'] + value: float + +class Geolocalisation(BaseModel): + longitude: Longitude + latitude: Latitude + name: str + diff --git a/app/geolocalisation/js_geolocation.py b/app/geolocalisation/js_geolocation.py new file mode 100644 index 0000000000000000000000000000000000000000..055ee262a3bdd9b00fc483bc4d0b93381a99164f --- /dev/null +++ b/app/geolocalisation/js_geolocation.py @@ -0,0 +1,35 @@ +# JavaScript code to get location and update hidden_input +js_geocode = """ + function() { + var textbox = document.querySelector('#textbox_id textarea'); + console.log(textbox) + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition( + function(position) { + var data = { + 'latitude': position.coords.latitude, + 'longitude': position.coords.longitude, + 'accuracy': position.coords.accuracy + }; + console.log("Geolocation data:", data); + textbox.value = JSON.stringify(data); + textbox.dispatchEvent(new Event('input', { bubbles: true })); + }, + function(error) { + var data = {'error': error.message}; + console.log("Geolocation error:", data); + textbox.value = JSON.stringify(data); + textbox.dispatchEvent(new Event('input', { bubbles: true })); + } + ); + } else { + var data = {'error': 'Geolocation is not supported by this browser.'}; + console.log("Geolocation unsupported:", data); + textbox.value = JSON.stringify(data); + textbox.dispatchEvent(new Event('input', { bubbles: true })); + } + } +""" + +def display_location(location_json): + return location_json \ No newline at end of file diff --git a/app/geolocalisation/maps.py b/app/geolocalisation/maps.py new file mode 100644 index 0000000000000000000000000000000000000000..70af4eff68830a007b34bb979caa0158a46a6841 --- /dev/null +++ b/app/geolocalisation/maps.py @@ -0,0 +1,50 @@ +from geopy.geocoders import Nominatim +import gradio as gr +from validation_submission.add_json import add_data_to_individual +from geolocalisation.class_geolocalisation import Geolocalisation + + +def create_geolocalisation_object(lat, long, name): + try: + geolocalisation = Geolocalisation( + longitude={"type": "longitude", "value": long}, + latitude={"type": "latitude", "value": lat}, + name=name + ) + except: + print("Pydantic Error for Geolocalisation") + return geolocalisation + +def save_geolocalisation_to_json(geolocalisation): + geo_dict = geolocalisation.dict() + add_data_to_individual("geolocalisation", geo_dict) + +def get_location(address): + try: + # calling the Nominatim tool + loc = Nominatim(user_agent="GetLoc") + + # entering the location name + getLoc = loc.geocode(address) + + # latitude and longitude + lat = getLoc.latitude + lon = getLoc.longitude + + # Save values + geolocalisation = create_geolocalisation_object(lat, lon, address) + save_geolocalisation_to_json(geolocalisation) + + #display location processing + value = "Latitude = " + str(lat) + "\n" + "Longitude = " + str(lon) + identified_location= gr.Textbox(visible=True, interactive=False, + label="Identified GPS Location", + value=value) + return identified_location + + except: + error = "Please try another less precise location." + identified_location= gr.Textbox(visible=True, interactive=False, + label="Identified GPS Location", + value=error) + return identified_location \ No newline at end of file diff --git a/app/gradio_test/test_selectdata_event.py b/app/gradio_test/test_selectdata_event.py new file mode 100644 index 0000000000000000000000000000000000000000..3e6d0e5e935dc4b9cdf4397c65e1a1413126c5bc --- /dev/null +++ b/app/gradio_test/test_selectdata_event.py @@ -0,0 +1,16 @@ +import gradio as gr + +with gr.Blocks() as demo: + table = gr.Dataframe([[1, 2, 3], [4, 5, 6]]) + #gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")]) + textbox = gr.Textbox("Hello World!") + statement = gr.Textbox() + + def on_select(evt: gr.SelectData): + return gr.Textbox(f"You selected {evt.value} at {evt.index} from {evt.target}") + + table.select(on_select, inputs=[table], outputs=[statement]) + #gallery.select(on_select, gallery, statement) + textbox.select(on_select, inputs=[textbox], outputs=[statement]) + +demo.launch(server_name="0.0.0.0", server_port=3131) \ No newline at end of file diff --git a/app/gradio_test/tests_delete_gallery.py b/app/gradio_test/tests_delete_gallery.py new file mode 100644 index 0000000000000000000000000000000000000000..d3cb1f8281e4ed8393e01dc4c60c621bb0749d9a --- /dev/null +++ b/app/gradio_test/tests_delete_gallery.py @@ -0,0 +1,25 @@ +import gradio as gr + +# Example initial image list +images = [ + "https://via.placeholder.com/150/0000FF", + "https://via.placeholder.com/150/FF0000", + "https://via.placeholder.com/150/00FF00" +] + +# Function to remove a selected image from the gallery +def delete_image(selected_image, image_list): + if selected_image in image_list: + image_list.remove(selected_image) # Remove the selected image + return image_list # Return the updated image list + +# Gradio app +with gr.Blocks() as demo: + gallery = gr.Gallery(value=images, label="Gallery") # Gallery of images + selected_image = gr.Dropdown(choices=images, label="Select Image to Delete") # Dropdown for selection + delete_button = gr.Button("Delete Selected Image") # Button to delete + + # When button is clicked, delete the selected image and update gallery + delete_button.click(fn=delete_image, inputs=[selected_image, gallery], outputs=gallery) + +demo.launch(server_name="0.0.0.0", server_port=3232) \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..4be3fade10226fd378ce934fa6f40dd6a1dcc327 --- /dev/null +++ b/app/main.py @@ -0,0 +1,387 @@ +import gradio as gr +from gradio_modal import Modal + +from validation_submission.create_json import create_json_all_individuals, create_json_one_individual, create_tmp, reset_json +from validation_submission.add_json import add_data_to_individual +from validation_submission.validation import reset_error_box +from display import save_display_individual +from geolocalisation.maps import get_location +from functools import partial +from dead import show_section_dead +from wounded import show_section_wounded +from circumstances.circumstances import show_circumstances +from circumstances.circumstances_dropdowns import * +from physical.physical_select_animal import show_physical, find_bounding_box +from physical.physical_checkbox import on_select_body_part, hide_physical +from behavior.behavior_checkbox import show_behavior, on_select_behavior +from follow_up.followup_events import save_fe +from styling.style import * +from styling.theme import css + +from geolocalisation.js_geolocation import js_geocode, display_location + +# with gr.Blocks(theme=theme, css=css) as demo: +with gr.Blocks(theme='shivi/calm_seafoam') as demo: +#with gr.Blocks() as demo: + create_json_all_individuals() + # --------------------------------------------------------- + # Intro Text + with gr.Row(): + with gr.Column(scale=1): + title = gr.Markdown("# Welcome to Digiwild", label="Title") + description = gr.Markdown("Please record your wildlife observations here !", label="description") + with gr.Row(): + show_modal = gr.Button("Add an Animal", scale=3) + submit_button = gr.Button("Submit All Animals", scale=1) + df = gr.Dataframe(headers=["Identifier", "Location", "Wounded", "Dead"], visible=False, interactive=False) + gallery = gr.Gallery( + label="Gallery of Records", elem_id="gallery", + columns=[1], rows=[1], + object_fit="contain", height="auto", interactive=False) + + with Modal(visible=False) as modal: + # --------------------------------------------------------- + # Intro Text + with gr.Row(): + with gr.Column(scale=1): + title = gr.Markdown("# Animal Report", label="Title") + description = gr.Markdown("Please record your observation here.", label="description") + + # --------------------------------------------------------- + # Camera + with gr.Row(): + def save_image(camera): + add_data_to_individual("image", camera.tolist()) + + camera = gr.Image(elem_id="image") + camera.input(save_image, inputs=[camera]) + # --------------------------------------------------------- + # Location + #with gr.Row(): + with gr.Column(scale=1): + gr.Markdown("### Location") + gr.Markdown("#### Location (Using address)") + location = gr.Textbox(visible=True, interactive=True, label="Location of Sighting") + #display location processing + identified_location= gr.Textbox(visible=False, interactive=False, + label="Identified GPS Location") + with gr.Row(): + #to submit it + submit_location = gr.Button("Get Coordinates using address", + visible=True, interactive=True, scale=3) + submit_location.click(get_location, inputs=[location], outputs=[identified_location]) + #to clear it + clear_location = gr.ClearButton(components=[location, identified_location], + visible=True, interactive=True, scale=1 + ) + clear_location.click() + + # Geolocation + gr.Markdown("#### Location (Using GPS)") + location_data = gr.JSON(label="Identified GPS Location") + hidden_input = gr.Textbox(visible=False, elem_id="textbox_id") + btn_gpslocation = gr.Button("Get Coordinates using GPS (Permission required)") + btn_gpslocation.click(None, [], [], js=js_geocode) + hidden_input.change(display_location, inputs=hidden_input, outputs=location_data) + + + # Introducing text_box for Species + gr.Markdown("### General details") + with gr.Row(): + specie = gr.Textbox( + label="Species (if known)", + placeholder="e.g. European Robin, Common Blackbird", + info="Enter the species name if you can identify it. If unsure, provide your best guess or general description (e.g. 'small brown bird')", + visible=True, + interactive=True + ) + + # Number of individuals + with gr.Row(): + num_individuals = gr.Number( + label="Number of Individuals", + value=1, # Default value + minimum=1, + precision=0, # Only whole numbers + info="Enter the number of animals observed", + #placeholder="Enter number...", + visible=True, + interactive=True + ) + + # Introducing text_box for comments + with gr.Row(): + comments = gr.TextArea( + label="Additional Comments", + placeholder="Enter any additional observations or notes about the sighting...", + info="Optional: Add any relevant details about the animal(s) or circumstances", + lines=3, + max_lines=5, + visible=True, + interactive=True + ) + + + # --------------------------------------------------------- + # --------------------------------------------------------- + # Dead and Wounded Buttons + gr.Markdown("## The State of the Animal", label="Title") + gr.Markdown("Please tell us if the animal was wounded / sick or dead.", label="description") + with gr.Row() as block_form: + with gr.Column(scale=1): + butt_wounded = gr.Button("Wounded / Sick", elem_id="wounded") + with gr.Column(scale=1): + butt_dead = gr.Button("Dead", elem_id="dead") + + # --------------------------------------------------------- + # Initiate sections + section_dead, radio_circumstance_dead, radio_physical_dead,\ + button_collision_dead, button_deliberate_destruction_dead, button_indirect_destruction_dead, button_natural_cause_dead, \ + dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead, \ + physical_boxes_dead, \ + checkbox_beak_dead, text_beak_dead, checkbox_body_dead, text_body_dead, checkbox_feathers_dead, text_feathers_dead, checkbox_head_dead, text_head_dead, checkbox_legs_dead, text_legs_dead, \ + fe_collection_dropdown_dead, fe_recepient_dropdown_dead, fe_radio_dropdown_dead, fe_answer_dropdown_dead, \ + fe_name_recipient_dead, fe_collection_ref_dead \ + = show_section_dead(False) + section_wounded, radio_circumstance_wounded, radio_behavior_wounded, radio_physical_wounded, \ + button_collision_wounded, button_deliberate_destruction_wounded, button_indirect_destruction_wounded, button_natural_cause_wounded, \ + dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded, \ + behavior_checkbox, behavior_text, \ + physical_boxes_wounded, \ + checkbox_beak_wounded, text_beak_wounded, checkbox_body_wounded, text_body_wounded, checkbox_feathers_wounded, text_feathers_wounded, checkbox_head_wounded, text_head_wounded, checkbox_legs_wounded, text_legs_wounded, \ + fe_collection_dropdown_wounded, fe_recepient_dropdown_wounded, fe_radio_dropdown_wounded, fe_answer_dropdown_wounded, \ + fe_name_recipient_wounded, fe_collection_ref_wounded \ + = show_section_wounded(False) + + # --------------------------------------------------------- + # --------------------------------------------------------- + # --------------------------------------------------------- + # Dead Button Logic + partial_show_section_dead = partial(show_section_dead, True) + partial_hide_section_wounded = partial(show_section_wounded, False) + butt_dead.click(partial_show_section_dead, + inputs=None, + outputs=[section_dead, + radio_circumstance_dead, radio_physical_dead, + button_collision_dead, button_deliberate_destruction_dead, button_indirect_destruction_dead, button_natural_cause_dead, + dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead, \ + physical_boxes_dead, \ + checkbox_beak_dead, text_beak_dead, checkbox_body_dead, text_body_dead, checkbox_feathers_dead, text_feathers_dead, checkbox_head_dead, text_head_dead, checkbox_legs_dead, text_legs_dead, \ + fe_collection_dropdown_dead, fe_recepient_dropdown_dead, fe_radio_dropdown_dead, fe_answer_dropdown_dead, \ + fe_name_recipient_dead, fe_collection_ref_dead \ + ]) + butt_dead.click(partial_hide_section_wounded, + inputs=None, + outputs=[section_wounded, + radio_circumstance_wounded, radio_behavior_wounded, radio_physical_wounded, + button_collision_wounded, button_deliberate_destruction_wounded, button_indirect_destruction_wounded, button_natural_cause_wounded, + dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded, + behavior_checkbox, behavior_text, + physical_boxes_wounded, \ + checkbox_beak_wounded, text_beak_wounded, checkbox_body_wounded, text_body_wounded, checkbox_feathers_wounded, text_feathers_wounded, checkbox_head_wounded, text_head_wounded, checkbox_legs_wounded, text_legs_wounded, \ + fe_collection_dropdown_wounded, fe_recepient_dropdown_wounded, fe_radio_dropdown_wounded, fe_answer_dropdown_wounded, \ + fe_name_recipient_wounded, fe_collection_ref_wounded \ + ]) + + # --------------------------------------------------------- + # Wounded Button Logic + partial_show_section_wounded = partial(show_section_wounded, True) + partial_hide_section_dead = partial(show_section_dead, False) + + butt_wounded.click(partial_show_section_wounded, + inputs=None, + outputs=[section_wounded, + radio_circumstance_wounded, radio_behavior_wounded, radio_physical_wounded, + button_collision_wounded, button_deliberate_destruction_wounded, button_indirect_destruction_wounded, button_natural_cause_wounded, + dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded, + behavior_checkbox, behavior_text, + physical_boxes_wounded, \ + checkbox_beak_wounded, text_beak_wounded, checkbox_body_wounded, text_body_wounded, checkbox_feathers_wounded, text_feathers_wounded, checkbox_head_wounded, text_head_wounded, checkbox_legs_wounded, text_legs_wounded, \ + fe_collection_dropdown_wounded, fe_recepient_dropdown_wounded, fe_radio_dropdown_wounded, fe_answer_dropdown_wounded, \ + fe_name_recipient_wounded, fe_collection_ref_wounded \ + ]) + butt_wounded.click(partial_hide_section_dead, inputs=None, outputs=[section_dead, + radio_circumstance_dead, radio_physical_dead, + button_collision_dead, button_deliberate_destruction_dead, button_indirect_destruction_dead, button_natural_cause_dead, + dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead, \ + physical_boxes_dead, \ + checkbox_beak_dead, text_beak_dead, checkbox_body_dead, text_body_dead, checkbox_feathers_dead, text_feathers_dead, checkbox_head_dead, text_head_dead, checkbox_legs_dead, text_legs_dead, \ + fe_collection_dropdown_dead, fe_recepient_dropdown_dead, fe_radio_dropdown_dead, fe_answer_dropdown_dead, \ + fe_name_recipient_dead, fe_collection_ref_dead \ + ]) + # --------------------------------------------------------- + # --------------------------------------------------------- + # --------------------------------------------------------- + # --------------------------------------------------------- + # DEAD + # --------------------------------------------------------- + # Radio Circumstance Dead + radio_circumstance_dead.change(fn=show_circumstances, + inputs=[radio_circumstance_dead], + outputs=[button_collision_dead, button_deliberate_destruction_dead, button_indirect_destruction_dead, button_natural_cause_dead, + dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead] + ) + + # Dropdowns Dead + button_collision_dead.click(dropdown_collision, + outputs=[dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead]) + button_deliberate_destruction_dead.click(dropdown_deliberate_destruction, outputs=[dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead]) + button_indirect_destruction_dead.click(dropdown_indirect_destruction, outputs=[dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead]) + button_natural_cause_dead.click(dropdown_natural_cause, outputs=[dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead]) + + dropdown_dead.select(on_select, None, [dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead]) + dropdown_level2_dead.select(on_select_dropdown_level2) + openfield_level2_dead.change(on_change_openfield_level2, inputs=[openfield_level2_dead]) + dropdown_extra_level2_dead.select(on_select_dropdown_extra_level2) + # --------------------------------------------------------- + # Radio Physical Dead + radio_physical_dead.change(fn=show_physical, + inputs=[radio_physical_dead, gr.Text("dead", visible=False)], + outputs=[physical_boxes_dead]) + + # Checkbox Physical Dead + physical_boxes_dead.select(find_bounding_box, + inputs=[physical_boxes_dead, gr.Textbox(value="dead", visible=False)], + outputs=[checkbox_beak_dead, text_beak_dead, + checkbox_body_dead, text_body_dead, + checkbox_feathers_dead, text_feathers_dead, + checkbox_head_dead, text_head_dead, + checkbox_legs_dead, text_legs_dead + ]) + checkbox_beak_dead.select(on_select_body_part, inputs=[checkbox_beak_dead, gr.Text("beak", visible=False)]) + checkbox_body_dead.select(on_select_body_part, inputs=[checkbox_body_dead, gr.Text("body", visible=False)]) + checkbox_feathers_dead.select(on_select_body_part, inputs=[checkbox_feathers_dead, gr.Text("feathers", visible=False)]) + checkbox_head_dead.select(on_select_body_part, inputs=[checkbox_head_dead, gr.Text("head", visible=False)]) + checkbox_legs_dead.select(on_select_body_part, inputs=[checkbox_legs_dead, gr.Text("legs", visible=False)]) + # --------------------------------------------------------- + # --------------------------------------------------------- + # --------------------------------------------------------- + # --------------------------------------------------------- + # WOUNDED + # --------------------------------------------------------- + # Radio Circumstance Wounded + radio_circumstance_wounded.change(fn=show_circumstances, + inputs=[radio_circumstance_wounded], + outputs=[button_collision_wounded, button_deliberate_destruction_wounded, button_indirect_destruction_wounded, button_natural_cause_wounded, + dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded] + ) + + # Dropdowns Circumstance Wounded + button_collision_wounded.click(dropdown_collision, + outputs=[dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded]) + button_deliberate_destruction_wounded.click(dropdown_deliberate_destruction, outputs=[dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded]) + button_indirect_destruction_wounded.click(dropdown_indirect_destruction, outputs=[dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded]) + button_natural_cause_wounded.click(dropdown_natural_cause, outputs=[dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded]) + + dropdown_wounded.select(on_select, None, [dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded]) + dropdown_level2_wounded.select(on_select_dropdown_level2) + openfield_level2_wounded.change(on_change_openfield_level2, inputs=[openfield_level2_wounded]) + dropdown_extra_level2_wounded.select(on_select_dropdown_extra_level2) + # --------------------------------------------------------- + # Radio Behavior Wounded + radio_behavior_wounded.change(fn=show_behavior, + inputs=[radio_behavior_wounded, gr.Text("wounded / sick", visible=False)], + outputs=[behavior_checkbox, behavior_text]) + behavior_checkbox.select(on_select_behavior, + inputs=[behavior_checkbox]) + # --------------------------------------------------------- + # Radio Physical Wounded + radio_physical_wounded.change(fn=show_physical, + inputs=[radio_physical_wounded, gr.Text("wounded / sick", visible=False)], + outputs=[physical_boxes_wounded]) + + # Checkbox Physical Wounded + physical_boxes_wounded.select(find_bounding_box, + inputs=[physical_boxes_wounded, gr.Textbox(value="wounded / sick", visible=False)], + outputs=[checkbox_beak_wounded, text_beak_wounded, + checkbox_body_wounded, text_body_wounded, + checkbox_feathers_wounded, text_feathers_wounded, + checkbox_head_wounded, text_head_wounded, + checkbox_legs_wounded, text_legs_wounded + ]) + checkbox_beak_wounded.select(on_select_body_part, inputs=[checkbox_beak_wounded, gr.Text("beak", visible=False)]) + checkbox_body_wounded.select(on_select_body_part, inputs=[checkbox_body_wounded, gr.Text("body", visible=False)]) + checkbox_feathers_wounded.select(on_select_body_part, inputs=[checkbox_feathers_wounded, gr.Text("feathers", visible=False)]) + checkbox_head_wounded.select(on_select_body_part, inputs=[checkbox_head_wounded, gr.Text("head", visible=False)]) + checkbox_legs_wounded.select(on_select_body_part, inputs=[checkbox_legs_wounded, gr.Text("legs", visible=False)]) + + # --------------------------------------------------------- + # Follow Up Events Wounded + fe_collection_dropdown_wounded.select(save_fe, inputs=[fe_collection_dropdown_wounded, gr.Textbox("animal collected", visible=False)]) + fe_recepient_dropdown_wounded.select(save_fe, inputs=[fe_recepient_dropdown_wounded, gr.Textbox("recipient", visible=False)]) + fe_radio_dropdown_wounded.select(save_fe, inputs=[fe_radio_dropdown_wounded, gr.Textbox("radiography", visible=False)]) + fe_answer_dropdown_wounded.select(save_fe, inputs=[fe_answer_dropdown_wounded, gr.Textbox("given answer", visible=False)]) + fe_name_recipient_wounded.input(save_fe, inputs=[fe_name_recipient_wounded, gr.Textbox("recipient name", visible=False)]) + fe_collection_ref_wounded.input(save_fe, inputs=[fe_collection_ref_wounded, gr.Textbox("collection reference", visible=False)]) + + # --------------------------------------------------------- + # Follow Up Events Dead + fe_collection_dropdown_dead.select(save_fe, inputs=[fe_collection_dropdown_dead, gr.Textbox("animal collected", visible=False)]) + fe_recepient_dropdown_dead.select(save_fe, inputs=[fe_recepient_dropdown_dead, gr.Textbox("recipient", visible=False)]) + fe_radio_dropdown_dead.select(save_fe, inputs=[fe_radio_dropdown_dead, gr.Textbox("radiography", visible=False)]) + fe_answer_dropdown_dead.select(save_fe, inputs=[fe_answer_dropdown_dead, gr.Textbox("given answer", visible=False)]) + fe_name_recipient_dead.input(save_fe, inputs=[fe_name_recipient_dead, gr.Textbox("recipient name", visible=False)]) + fe_collection_ref_dead.input(save_fe, inputs=[fe_collection_ref_dead, gr.Textbox("collection reference", visible=False)]) + + # --------------------------------------------------------- + # Error Box + error_box = gr.Text(value=None, visible=False) + + # --------------------------------------------------------- + # Add One Individual's Data to the Dataframe + # And Allow clearing of all previous output + with gr.Row(): + button_df = gr.Button("Submit Animal Report", scale = 3) + button_clear = gr.ClearButton(scale = 1, + components=[ + camera, + location, identified_location, + #dead reset + radio_circumstance_dead, radio_physical_dead, + button_collision_dead, button_deliberate_destruction_dead, button_indirect_destruction_dead, button_natural_cause_dead, + dropdown_dead, dropdown_level2_dead, openfield_level2_dead, dropdown_extra_level2_dead, + physical_boxes_dead, + checkbox_beak_dead, text_beak_dead, checkbox_body_dead, text_body_dead, checkbox_feathers_dead, text_feathers_dead, checkbox_head_dead, text_head_dead, checkbox_legs_dead, text_legs_dead, + fe_collection_dropdown_dead, fe_recepient_dropdown_dead, fe_radio_dropdown_dead, fe_answer_dropdown_dead, + fe_name_recipient_dead, fe_collection_ref_dead, + #wounded reset + radio_circumstance_wounded, radio_behavior_wounded, radio_physical_wounded, + button_collision_wounded, button_deliberate_destruction_wounded, button_indirect_destruction_wounded, button_natural_cause_wounded, + dropdown_wounded, dropdown_level2_wounded, openfield_level2_wounded, dropdown_extra_level2_wounded, + behavior_checkbox, behavior_text, + physical_boxes_wounded, + checkbox_beak_wounded, text_beak_wounded, checkbox_body_wounded, text_body_wounded, checkbox_feathers_wounded, text_feathers_wounded, checkbox_head_wounded, text_head_wounded, checkbox_legs_wounded, text_legs_wounded, + fe_collection_dropdown_wounded, fe_recepient_dropdown_wounded, fe_radio_dropdown_wounded, fe_answer_dropdown_wounded, + fe_name_recipient_wounded, fe_collection_ref_wounded, + error_box + ]) + button_close = gr.Button("Back to Display", scale = 1) + + + # --------------------------------------------------------- + # Button Click Logic + button_clear.click() + button_clear.click(hide_physical, + outputs=[checkbox_beak_wounded, text_beak_wounded, checkbox_body_wounded, text_body_wounded, checkbox_feathers_wounded, text_feathers_wounded, checkbox_head_wounded, text_head_wounded, checkbox_legs_wounded, text_legs_wounded]) + button_clear.click(hide_physical, + outputs=[checkbox_beak_dead, text_beak_dead, checkbox_body_dead, text_body_dead, checkbox_feathers_dead, text_feathers_dead, checkbox_head_dead, text_head_dead, checkbox_legs_dead, text_legs_dead]) + + button_clear.click(reset_error_box, inputs=[error_box], outputs=[error_box]) + button_clear.click(reset_json) + + button_df.click(save_display_individual, + inputs=[gallery, df, error_box], + outputs=[gallery, df, error_box] + ) + button_close.click(lambda: Modal(visible=False), None, modal) + + # --------------------------------------------------------- + # Event Functions of the landing page buttons + show_modal.click(lambda: Modal(visible=True), None, modal) + show_modal.click(create_json_one_individual) + show_modal.click(create_tmp) + #submit_button.click(save_and_rest_df, inputs=[df], outputs=[df]) + + +if __name__ == "__main__": + demo.launch(server_name="0.0.0.0", server_port=7860) \ No newline at end of file diff --git a/app/physical/__init__.py b/app/physical/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/physical/__pycache__/__init__.cpython-312.pyc b/app/physical/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10ad6a0b458bdd4ef4bd12593554fc076c0fabfa Binary files /dev/null and b/app/physical/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/physical/__pycache__/class_physical.cpython-312.pyc b/app/physical/__pycache__/class_physical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75b9e4b74d09567ffd3907043fbaa9405c5537a Binary files /dev/null and b/app/physical/__pycache__/class_physical.cpython-312.pyc differ diff --git a/app/physical/__pycache__/physical_boxes_define.cpython-312.pyc b/app/physical/__pycache__/physical_boxes_define.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f90c219fdbc66eac5f2503c0e349bd4270572b0b Binary files /dev/null and b/app/physical/__pycache__/physical_boxes_define.cpython-312.pyc differ diff --git a/app/physical/__pycache__/physical_checkbox.cpython-312.pyc b/app/physical/__pycache__/physical_checkbox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace4f1f008fcb6917e956d2aba86a98871a2e33f Binary files /dev/null and b/app/physical/__pycache__/physical_checkbox.cpython-312.pyc differ diff --git a/app/physical/__pycache__/physical_select_animal.cpython-312.pyc b/app/physical/__pycache__/physical_select_animal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0126036c637ed33dd29f8688a848a471aa119b35 Binary files /dev/null and b/app/physical/__pycache__/physical_select_animal.cpython-312.pyc differ diff --git a/app/physical/class_physical.py b/app/physical/class_physical.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e5b45eae97b9d3d93a8563e7e8a8da6b401aa3 --- /dev/null +++ b/app/physical/class_physical.py @@ -0,0 +1,79 @@ +from pydantic import BaseModel, Field +from typing import Literal, List, Union, Optional + +# Define common anomalies as a Literal type +CommonAnomalies = Literal[ + 'blackened/burnt skin', + 'blood', + 'foreign body', + 'fracture', + 'injury', + 'parasite', + 'swelling', + 'warty or tumor-like growth, crusts' +] + +# --- Beak-related Anomalies --- +class BeakAnomaly(BaseModel): + type: Literal['beak'] + anomaly_type: List[Literal[ + 'adhesion', + 'deformation', + CommonAnomalies + ]] + +# --- Body-related Anomalies --- +class BodyAnomaly(BaseModel): + type: Literal['body'] + anomaly_type: List[Literal[ + 'emaciation', + 'fluffed up', + 'stained feathers', + CommonAnomalies + ]] + +# --- Legs-related Anomalies --- +class LegAnomaly(BaseModel): + type: Literal['legs'] + anomaly_type: List[Literal[ + 'missing limb', + 'deformation', + CommonAnomalies + ]] + +# --- Feathers/Wings/Tail-related Anomalies --- +class FeathersWingsTailAnomaly(BaseModel): + type: Literal['feathers/wings/tail'] + anomaly_type: List[Literal[ + 'fluffed up', + 'feather abnormalities', + 'stained feathers', + 'abnormal wing posture', + 'missing limb', + CommonAnomalies + ]] + +# --- Head-related Anomalies (including eyes) --- +class HeadAnomaly(BaseModel): + type: Literal['head incl. eyes'] + anomaly_type: List[Literal[ + 'ear changes', + 'eye changes', + 'tilted head', + CommonAnomalies + ]] + + +# Union of all possible anomaly types for specific body parts +AnomalyType = Union[ + BeakAnomaly, + BodyAnomaly, + LegAnomaly, + FeathersWingsTailAnomaly, + HeadAnomaly +] + +# Main PhysicalAnomaly class that logs anomalies across different body parts +class PhysicalAnomalies(BaseModel): + physical_radio: str + physical_anomalies_type: Optional[List[AnomalyType]] = None diff --git a/app/physical/physical_boxes_define.py b/app/physical/physical_boxes_define.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3bedc6069a744366f6700a4dd5359bf7a7ab93 --- /dev/null +++ b/app/physical/physical_boxes_define.py @@ -0,0 +1,23 @@ +import geopandas as gpd +from shapely.geometry import box + +bounding_boxes = [ + # 'Head incl. eyes', + box(250, 375, 350, 485), + # 'Beak and mouth region', + box(200, 450, 250, 485), + # 'Feathers/Wings/Tail', + box(50, 100, 725, 355), + # 'Legs', + box(325, 585, 450, 675), + # 'Body' + box(275, 510, 500, 565) +] + +# Create a GeoDataFrame from these boxes +gdf = gpd.GeoDataFrame({'geometry': bounding_boxes, + 'name': ['Head incl. eyes', + 'Beak', + 'Feathers/Wings/Tail', + 'Legs', + 'Body']}) diff --git a/app/physical/physical_boxes_map.py b/app/physical/physical_boxes_map.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6f62849fc785c05a803c5eada0063bd5804483 --- /dev/null +++ b/app/physical/physical_boxes_map.py @@ -0,0 +1,33 @@ +from PIL import Image, ImageDraw, ImageFont + +from physical_boxes_define import gdf + +from dotenv import load_dotenv +import os +load_dotenv() +PATH_ASSETS = os.getenv('PATH_ASSETS') + +# Function to draw the bounding boxes on the image +def draw_bounding_boxes(image_path, gdf): + image = Image.open(image_path+'bird.png').convert("RGB") + # Convert the image to an editable format + draw = ImageDraw.Draw(image) + + # Optional: Load a font (requires a TTF file) + # try: + font = ImageFont.truetype(PATH_ASSETS + "fonts/LiberationSans-Regular.ttf", + 20) + # except IOError: + # print("default") + # font = ImageFont.load_default() + + # Draw each bounding box on the image + for _, row in gdf.iterrows(): + xmin, ymin, xmax, ymax = row['geometry'].bounds + draw.rectangle([xmin, ymin, xmax, ymax], outline="purple", width=2) + draw.text((xmin, ymin-22), row['name'], fill="black", font=font) + + image.save(image_path+'bird_boxed.png', "PNG") + +if __name__ == "__main__": + draw_bounding_boxes(PATH_ASSETS + 'images/', gdf) \ No newline at end of file diff --git a/app/physical/physical_checkbox.py b/app/physical/physical_checkbox.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a505350d0a7a28995050c6ee364f0b7fea89f0 --- /dev/null +++ b/app/physical/physical_checkbox.py @@ -0,0 +1,84 @@ +import gradio as gr +from utils.utils_config import get_custom_config_dropdowns +from utils.utils_checkbox import create_checkbox +from validation_submission.add_json import add_data_tmp +#--------------------------------------------------------- +def get_body_parts(): + dropdown_config = get_custom_config_dropdowns("config_checkbox_physical.json") + return list(dropdown_config.keys()) + +def retrieve_config_options(label, dropdown_config): + options = list(dropdown_config[label].keys()) + options = [option.title() for option in options] + return options + +def get_options_description(value): + dropdown_config = get_custom_config_dropdowns("config_checkbox_physical.json") + # get options + options_common = retrieve_config_options("Common", dropdown_config) + options_for_value = retrieve_config_options(value, dropdown_config) + options_common.extend(options_for_value) + options = options_common + # get descriptions + descriptions = [] + for key, sub_dict in dropdown_config.items(): + if key==value or key=="Common": + for _, option_dict in sub_dict.items(): + for description_tag, description in option_dict.items(): + if "Description"==description_tag: + descriptions.append(description) + return options, descriptions + +#--------------------------------------------------------- +def create_checkbox_beak(section, label_checkbox, visible): + body_part="Beak" + options, descriptions = get_options_description(body_part) + return create_checkbox(body_part, section, label_checkbox, visible, options, descriptions) + +def create_checkbox_body(section, label_checkbox, visible): + body_part="Body" + options, descriptions = get_options_description(body_part) + return create_checkbox(body_part, section, label_checkbox, visible, options, descriptions) + +def create_checkbox_feathers(section, label_checkbox, visible): + body_part="Feathers/Wings/Tail" + options, descriptions = get_options_description(body_part) + return create_checkbox(body_part, section, label_checkbox, visible, options, descriptions) + +def create_checkbox_head(section, label_checkbox, visible): + body_part="Head incl. eyes" + options, descriptions = get_options_description(body_part) + return create_checkbox(body_part, section, label_checkbox, visible, options, descriptions) + +def create_checkbox_legs(section, label_checkbox, visible): + body_part="Legs" + options, descriptions = get_options_description(body_part) + return create_checkbox(body_part, section, label_checkbox, visible, options, descriptions) + +#--------------------------------------------------------- +def process_body_parts(section, matched_box): + #take all except "Common" + body_parts = get_body_parts() + body_parts = body_parts[1:] + label_checkbox = "Physical changes to " + visibles = [True if matched_box==body_part else False for body_part in body_parts ] + checkbox_beak, text_beak = create_checkbox_beak(section, label_checkbox, visibles[0]) + checkbox_body, text_body = create_checkbox_body(section, label_checkbox, visibles[1]) + checkbox_feathers, text_feathers = create_checkbox_feathers(section, label_checkbox, visibles[2]) + checkbox_head, text_head = create_checkbox_head(section, label_checkbox, visibles[3]) + checkbox_legs, text_legs = create_checkbox_legs(section, label_checkbox, visibles[4]) + return checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs + +#--------------------------------------------------------- + +def on_select_body_part(body_part_checkbox, body_part): + add_data_tmp("wounded_dead", "physical_type_"+body_part.lower(), body_part.lower()) + body_part_checkbox = [body_part_check.lower() for body_part_check in body_part_checkbox] + add_data_tmp("wounded_dead", "physical_anomaly_"+body_part.lower(), body_part_checkbox) + +#--------------------------------------------------------- + +def hide_physical(): + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs = process_body_parts("wounded", "None") + return checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs + \ No newline at end of file diff --git a/app/physical/physical_select_animal.py b/app/physical/physical_select_animal.py new file mode 100644 index 0000000000000000000000000000000000000000..f78ccd7be3060beac58e91e29b3abeb391c42505 --- /dev/null +++ b/app/physical/physical_select_animal.py @@ -0,0 +1,50 @@ +import gradio as gr +from dotenv import load_dotenv +import os +from typing import List +from shapely.geometry import Point + +from physical.physical_checkbox import * +from physical.physical_boxes_define import gdf +from utils.utils_visible import set_visible + +load_dotenv() +PATH_ASSETS = os.getenv('PATH_ASSETS') + +# Function to find the matching bounding box for a given point and return the image with boxes +def find_bounding_box(evt: gr.SelectData, img, section: str): + x, y = evt.index[0], evt.index[1] + point = Point(x, y) + match = gdf[gdf.contains(point)] + if not match.empty: + matched_box = match.iloc[0]['name'] + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs = process_body_parts(section, matched_box) + else: + matched_box = None + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs = process_body_parts(section, matched_box) + return checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs + + + +# Gradio app +def create_bird_anatomy(visible, section: str): + # Draw bounding boxes on the image + print + img_with_boxes = gr.Image(value=PATH_ASSETS+'images/bird_boxed.png', + show_label=False, + height="600px", + elem_id=section, + visible=visible) + return img_with_boxes + +def show_physical(choice, section: str): + visible = set_visible(choice) + physical_boxes = create_bird_anatomy(visible, section) + add_data_tmp("wounded_dead", "physical_radio", choice) + return physical_boxes + + + + + + diff --git a/app/styling/__init__.py b/app/styling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/styling/__pycache__/__init__.cpython-312.pyc b/app/styling/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..250acfed5298fe15dee82fb799ab06707a745204 Binary files /dev/null and b/app/styling/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/styling/__pycache__/style.cpython-312.pyc b/app/styling/__pycache__/style.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78a4b240822362fbe83b136777a3494f0995cd34 Binary files /dev/null and b/app/styling/__pycache__/style.cpython-312.pyc differ diff --git a/app/styling/__pycache__/theme.cpython-312.pyc b/app/styling/__pycache__/theme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7416af202499b8ac9df2b4aace63d4a2d3876597 Binary files /dev/null and b/app/styling/__pycache__/theme.cpython-312.pyc differ diff --git a/app/styling/style.py b/app/styling/style.py new file mode 100644 index 0000000000000000000000000000000000000000..58d84358e4364a3c19ce3f9b89725a7923972cc5 --- /dev/null +++ b/app/styling/style.py @@ -0,0 +1,37 @@ +import gradio as gr + +gr.HTML(''' + <style> + # .custom-button { + # background-color: #3B4C54; + # border: none; + # color: white; + # padding: 15px 32px; + # text-align: center; + # text-decoration: none; + # display: inline-block; + # font-size: 16px; + # margin: 4px 2px; + # cursor: pointer; + # border-radius: 8px; + # } + </style> + ''') + +# gr.HTML(''' +# <style> +# .custom-button { +# background-color: #4CAF50; /* Green */ +# border: none; +# color: white; +# padding: 15px 32px; +# text-align: center; +# text-decoration: none; +# display: inline-block; +# font-size: 16px; +# margin: 4px 2px; +# cursor: pointer; +# border-radius: 8px; +# } +# </style> +# ''') \ No newline at end of file diff --git a/app/styling/theme.py b/app/styling/theme.py new file mode 100644 index 0000000000000000000000000000000000000000..553e77112fd3c43e10877d69f87e8eafa194e008 --- /dev/null +++ b/app/styling/theme.py @@ -0,0 +1,105 @@ +import gradio as gr + +css= "" +css_old = """ +.gradio-container {background: url(https://openclipart.org/image/2000px/279687)} + +/* Main background */ +body { + background-color: #3B4C54; + color: #ffffff; /* Set default text color for contrast */ +} + +/* Secondary color for headers and panels */ +.gradio-container .card, +.gradio-container h1, +.gradio-container h2, +.gradio-container h3, +.gradio-container h4 { + background-color: #3F543B; + color: #ffffff; /* Ensuring text is readable */ +} + + + + +/* Background color for the wounded section */ +#wounded { + background-color: #503B54; + color: #ffffff; /* Ensures text is readable */ +} + +/* Olive green color for headers within the wounded section */ +#wounded h1, +#wounded h2, +#wounded h3, +#wounded h4, +#wounded h5, +#wounded h6 { + color: #ffffff; /* Olive green color for header text */ + background-color: #503B54; /* No background color for headers */ +} + +/* Styling dropdowns within the wounded section */ +#wounded select { + background-color: #3F543B; /* Olive green background */ + color: #ffffff; /* Ensures text is readable */ + border: 1px solid #3B4C54; /* Optional border for consistency */ +} + +/* Styling checkboxes within the wounded section */ +#wounded input[type="checkbox"] { + accent-color: #3F543B; /* Olive green color for the checkbox */ +} + +/* Additional checkbox label styling if needed */ +#wounded label { + color: #ffffff; /* Ensures labels are readable */ +} + + + + + +/* Background color for the dead section */ +#dead { + background-color: #54433B; + color: #ffffff; /* Ensures text is readable */ +} + +/* Brown color for headers within the dead section */ +#dead h1, +#dead h2, +#dead h3, +#dead h4, +#dead h5, +#dead h6 { + color: #ffffff; /* Olive green color for header text */ + background-color: #54433B; /* No background color for headers */ +} + + +#bird-boxes {background-color: #3B4C54} +#submit {background-color: #abb2bf} +#error {background-color: #e82323} +#valid {background-color: #07e63f} +""" + +# OLD THEME: + +# css = """ +# .gradio-container {background: url(https://openclipart.org/image/2000px/279687)} +# #image {background-color: #73b9ae} +# #dead {background-color: #333333} +# #wounded {background-color: #5e0724} +# #bird-boxes {background-color: #f2f3f3} +# #buttons-conditions {background-color: #b3b3b3} +# #dropdown-conditions {background-color: #b3b3b3} +# #followup {background-color: #38241c} +# #submit {background-color: #abb2bf} +# #error {background-color: #e82323} +# #valid {background-color: #07e63f} +# """ + +# theme = gr.themes.Soft(primary_hue="teal", secondary_hue="teal", neutral_hue="emerald", +# font=[gr.themes.GoogleFont("Inconsolata"), "Arial", "sans-serif"]) diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/utils/__pycache__/__init__.cpython-312.pyc b/app/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ef111412a418a0a92b0de4f65dcc2b950580df Binary files /dev/null and b/app/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/utils/__pycache__/utils_checkbox.cpython-312.pyc b/app/utils/__pycache__/utils_checkbox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f9a41540caf06e785248f6ee945b38b0b40bf6c Binary files /dev/null and b/app/utils/__pycache__/utils_checkbox.cpython-312.pyc differ diff --git a/app/utils/__pycache__/utils_config.cpython-312.pyc b/app/utils/__pycache__/utils_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42432cb3f56d9cfd841db84588adbca91a05cec3 Binary files /dev/null and b/app/utils/__pycache__/utils_config.cpython-312.pyc differ diff --git a/app/utils/__pycache__/utils_visible.cpython-312.pyc b/app/utils/__pycache__/utils_visible.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed2009f9e1e0d50b09f84284b709b9c55196e681 Binary files /dev/null and b/app/utils/__pycache__/utils_visible.cpython-312.pyc differ diff --git a/app/utils/utils_checkbox.py b/app/utils/utils_checkbox.py new file mode 100644 index 0000000000000000000000000000000000000000..155cd6c79b9c948f524f517783b8155b6bcc7c8d --- /dev/null +++ b/app/utils/utils_checkbox.py @@ -0,0 +1,18 @@ +import gradio as gr + +#--------------------------------------------------------- +def create_checkbox(value, section, label_checkbox, visible, options, descriptions): + descriptions_info = "<br><br>".join([f"* **{option}**: {description}" for option, description in zip(options, descriptions)]) + checkbox = gr.CheckboxGroup(options, + label=label_checkbox + f" {value}:", + visible=visible, + interactive=True, + elem_id=section) + text = gr.Markdown(descriptions_info, + label = "Info", + visible=visible, + #interactive=False, + #lines=13, + #max_lines=15, + elem_id=section) + return checkbox, text \ No newline at end of file diff --git a/app/utils/utils_config.py b/app/utils/utils_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c9231df8f6635a21d690dfe4bafb81a14dc6e04b --- /dev/null +++ b/app/utils/utils_config.py @@ -0,0 +1,20 @@ +import json +import os +from dotenv import load_dotenv +import os +load_dotenv() +PATH = os.getcwd() + "/" +PATH_ASSETS = os.getenv('PATH_ASSETS') +PATH_CONFIG = PATH + PATH_ASSETS + "config/" + +def load_config(file_path): + with open(file_path) as f: + config = json.load(f) + return config + +def get_custom_config_dropdowns(config_path): + dropdown_config_path = PATH_CONFIG + config_path + dropdown_config = load_config(dropdown_config_path) + return dropdown_config + + diff --git a/app/utils/utils_visible.py b/app/utils/utils_visible.py new file mode 100644 index 0000000000000000000000000000000000000000..7651bdea0c85315e2a45c4d154dcb9acd5611b97 --- /dev/null +++ b/app/utils/utils_visible.py @@ -0,0 +1,6 @@ +def set_visible(choice): + if choice=="Yes": + visible = True + else: + visible=False + return visible \ No newline at end of file diff --git a/app/validation_submission/__init__.py b/app/validation_submission/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/validation_submission/__pycache__/__init__.cpython-312.pyc b/app/validation_submission/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f2352970e2e9e162bde448b32647f84d7fc9e7e Binary files /dev/null and b/app/validation_submission/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/add_json.cpython-312.pyc b/app/validation_submission/__pycache__/add_json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fc2f923583d656330ac5c3e97ccdc985388b4d3 Binary files /dev/null and b/app/validation_submission/__pycache__/add_json.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/create_json.cpython-312.pyc b/app/validation_submission/__pycache__/create_json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fee1d7e15d629f75d2ebfe80a7265035c4fb5c4 Binary files /dev/null and b/app/validation_submission/__pycache__/create_json.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/get_json.cpython-312.pyc b/app/validation_submission/__pycache__/get_json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..524ab3265e40954b83253c9a0b38c39a59e53ead Binary files /dev/null and b/app/validation_submission/__pycache__/get_json.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/json_data.cpython-312.pyc b/app/validation_submission/__pycache__/json_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..017605bddc7be34178f446f3def75ff4b6599068 Binary files /dev/null and b/app/validation_submission/__pycache__/json_data.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/processing.cpython-312.pyc b/app/validation_submission/__pycache__/processing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e41e54c7462a913d1ace3580dd724f8fd348886 Binary files /dev/null and b/app/validation_submission/__pycache__/processing.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/submission.cpython-312.pyc b/app/validation_submission/__pycache__/submission.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6260c629ab8eb1085841c4888bfcd16a3e763c3e Binary files /dev/null and b/app/validation_submission/__pycache__/submission.cpython-312.pyc differ diff --git a/app/validation_submission/__pycache__/validation.cpython-312.pyc b/app/validation_submission/__pycache__/validation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a32274cf97c6dd158654e2ed6a6ae26d5c6dd6c1 Binary files /dev/null and b/app/validation_submission/__pycache__/validation.cpython-312.pyc differ diff --git a/app/validation_submission/add_json.py b/app/validation_submission/add_json.py new file mode 100644 index 0000000000000000000000000000000000000000..c95f4172b7ebccff9b1a6b8c33e41ca7b462f2ba --- /dev/null +++ b/app/validation_submission/add_json.py @@ -0,0 +1,15 @@ +from validation_submission.create_json import create_json_one_individual, create_tmp +import json + +def add_data_to_individual(key, value): + with open("data/one_individual.json", 'r') as openfile: + one_individual = json.load(openfile) + one_individual[key] = value + create_json_one_individual(one_individual) + +def add_data_tmp(tmp_name, key, value): + with open(f"app/assets/tmp_json/tmp_{tmp_name}.json", 'r') as openfile: + tmp = json.load(openfile) + tmp[key] = value + create_tmp(tmp_name, tmp) + \ No newline at end of file diff --git a/app/validation_submission/create_json.py b/app/validation_submission/create_json.py new file mode 100644 index 0000000000000000000000000000000000000000..a538d6e7dba604f3d1cb7672f0a19629e74e1761 --- /dev/null +++ b/app/validation_submission/create_json.py @@ -0,0 +1,20 @@ +import json + +def create_json_one_individual(one_individual={}): + one_individual = json.dumps(one_individual) + with open("data/one_individual.json", "w") as outfile: + outfile.write(one_individual) + +def create_json_all_individuals(all_individuals={}): + all_individuals = json.dumps(all_individuals) + with open("data/all_individuals.json", "w") as outfile: + outfile.write(all_individuals) + +def create_tmp(tmp_name="wounded_dead", tmp={}): + tmp = json.dumps(tmp) + with open(f"app/assets/tmp_json/tmp_{tmp_name}.json", "w") as outfile: + outfile.write(tmp) + +def reset_json(): + create_json_one_individual() + create_tmp() \ No newline at end of file diff --git a/app/validation_submission/get_json.py b/app/validation_submission/get_json.py new file mode 100644 index 0000000000000000000000000000000000000000..03d77d8d4e8b69eaabdb3e21fafc4fb22a3d458e --- /dev/null +++ b/app/validation_submission/get_json.py @@ -0,0 +1,16 @@ +import json + +def get_json_one_individual(): + with open("data/one_individual.json", 'r') as openfile: + one_individual = json.load(openfile) + return one_individual + +def get_json_all_individuals(): + with open("data/all_individuals.json", "r") as openfile: + all_individuals = json.load(openfile) + return all_individuals + +def get_json_tmp(tmp_name): + with open(f"app/assets/tmp_json/tmp_{tmp_name}.json", "r") as openfile: + tmp_json = json.load(openfile) + return tmp_json \ No newline at end of file diff --git a/app/validation_submission/processing.py b/app/validation_submission/processing.py new file mode 100644 index 0000000000000000000000000000000000000000..a47051bbc6c84a3dafb6031d53553e530d121cf2 --- /dev/null +++ b/app/validation_submission/processing.py @@ -0,0 +1,55 @@ +#### PROCESS FUNCTIONS + +def process_circumstance(data): + fields_to_check = ["option_dropdown", "open_field", "extra"] + if data["circumstance_radio"] == "Yes": + for field in fields_to_check: + if data["circumstance_type"][field+"_label"] == "NA": + data["circumstance_type"].pop(field+"_label") + else : + val = data[f"circumstance_{field}"] + key = data["circumstance_type"][field+"_label"] + data["circumstance_type"][key] = val + data["circumstance_type"].pop(field+"_label") + return data + +def process_behaviors(data): + behaviors =[] + if data["behaviors_radio"] == "Yes": + for type in data["behaviors_type"]: + new_behavior = {} + new_behavior["type"] = type + behaviors.append(new_behavior) + data["behaviors_type"] = behaviors + return data + +def process_physical(data): + body_parts= ["beak", "body", "legs", "feathers/wings/tail", "head incl. eyes"] + anomalies=[] + reformatted = {} + reformatted["physical_radio"] = data["physical_radio"] + if data["physical_radio"] == "Yes": + for body_part in body_parts: + anomaly = {} + for key, val in data.items(): + if "type_"+ body_part in key: + anomaly["type"] = body_part + elif "anomaly_"+ body_part in key: + anomaly["anomaly_type"] = val + if anomaly: + anomalies.append(anomaly) + reformatted["physical_anomalies_type"] = anomalies + return reformatted + +def process_followup(data): + followup_events = [] + for key, val in data.items(): + followup_event={} + type = key.split("followup")[-1] + option = type.split(" ")[-1] + followup_event["type"] = type.strip() + followup_event[option.strip()] = val + followup_events.append(followup_event) + reformatted ={} + reformatted["follow_up_events"] = followup_events + return reformatted \ No newline at end of file diff --git a/app/validation_submission/submission.py b/app/validation_submission/submission.py new file mode 100644 index 0000000000000000000000000000000000000000..313df1e18d0b3bd261f187a6e922f1a333715d9e --- /dev/null +++ b/app/validation_submission/submission.py @@ -0,0 +1,17 @@ +import json +from validation_submission.get_json import get_json_all_individuals +from validation_submission.validation import validate_individual + +def validate_save_individual(error_box): + individual, error_box = validate_individual(error_box) + if individual: + save_to_all_individuals(individual.model_dump()) + return individual, error_box + +def save_to_all_individuals(one_individual): + all_individuals = get_json_all_individuals() + all_individuals[str(len(all_individuals))] = one_individual + all_individuals_for_json = json.dumps(all_individuals) + with open("data/all_individuals.json", "w") as outfile: + outfile.write(all_individuals_for_json) + return all_individuals \ No newline at end of file diff --git a/app/validation_submission/validation.py b/app/validation_submission/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..9e170eabf09df25794f3b0965a62da3855457e6a --- /dev/null +++ b/app/validation_submission/validation.py @@ -0,0 +1,173 @@ +import uuid +from pydantic import ValidationError +import gradio as gr + +from validation_submission.get_json import get_json_tmp, get_json_one_individual +from circumstances.class_circumstance import Circumstances +from behavior.class_behavior import Behaviors +from physical.class_physical import PhysicalAnomalies +from follow_up.class_follow_up import FollowUpEvents +from classes import Report, Wounded, Dead, ImageBase64 +from validation_submission.processing import process_circumstance, process_behaviors, process_physical, process_followup + +def get_fields(data_dict, keyword): + extract = {} + for key, val in data_dict.items(): + if keyword in key: + extract[key] = val + return extract + +def validate_individual(error_box): + error_box = reset_error_box(error_box) + data = get_json_one_individual() + data["identifier"] = str(uuid.uuid4()) + if "image" in data.keys(): + img = ImageBase64.to_base64(data["image"]) + else: + img = None + if "geolocalisation" in data.keys(): + geolocalisation = data["geolocalisation"] + else: + geolocalisation = None + + error_behavior = None + error_circumstance = None + error_followup = None + error_physical = None + error_individual = None + if "wounded_state" not in data or "dead_state" not in data: + data["wounded_state"] = "No" + data["dead_state"] = "No" + if (data["wounded_state"] == "Yes") or (data["dead_state"] == "Yes"): + data_wounded_dead = get_json_tmp("wounded_dead") + circumstance, error_circumstance = validate_circumstance(data_wounded_dead) + physical, error_physical = validate_physical(data_wounded_dead) + followup, error_followup = validate_follow_up(data_wounded_dead) + + if data["wounded_state"]=="Yes": + print(physical) + behavior, error_behavior = validate_behavior(data_wounded_dead) + try : + individual = Report(identifier = data["identifier"], + image = img, + geolocalisation = geolocalisation, + wounded_state = data["wounded_state"], + wounded = Wounded(circumstances = circumstance, + behaviors = behavior, + physical_anomalies = physical, + follow_up_events = followup), + dead_state = data["dead_state"]) + except ValidationError as e: + print(e) + error_individual = e + + elif data["dead_state"]=="Yes": + try: + individual = Report(identifier = data["identifier"], + image = img, + geolocalisation = geolocalisation, + wounded_state = data["wounded_state"], + dead_state = data["dead_state"], + dead = Dead(circumstances = circumstance, + physical_anomalies = physical, + follow_up_events = followup) + ) + except ValidationError as e: + print(e) + error_individual = e + else: + try: + individual = Report(identifier = data["identifier"], + image = img, + geolocalisation = geolocalisation, + wounded_state = data["wounded_state"], + dead_state = data["dead_state"]) + except ValidationError as e: + print(e) + error_individual = e + if error_behavior or error_circumstance or error_followup or error_physical or error_individual: + error_box = show_error(error_box, error_behavior, error_circumstance, error_followup, error_physical, error_individual) + individual = None + else: + error_box= gr.Text(label="ALL VALID.", value="Record Registered. You can return to the Display.", visible=True, elem_id="valid") + return individual, error_box + +def show_error(error_box, error_behavior, error_circumstance, error_followup, error_physical, error_individual): + error_text = "" + if error_circumstance: + error_text += f"Error in circumstance: {error_circumstance}\n" + if error_behavior: + error_text += f"Error in behavior: {error_behavior}\n" + if error_physical: + error_text += f"Error in physical: {error_physical}\n" + if error_followup: + error_text += f"Error in follow-up: {error_followup}\n" + if error_individual: + error_text += f"Error in individual: {error_individual}\n" + error_text += "PLEASE CORRECT THESE ERRORS BEFORE SUBMITTING." + error_box= gr.Text(label="ERROR DETECTED !", value=error_text, visible=True, elem_id="error") + return error_box + +def reset_error_box(error_box): + error_box = gr.Text(value=None, visible=False) + return error_box + +#### VALIDATION FUNCTIONS +def validate_circumstance(data): + circumstance_raw = get_fields(data, "circumstance") + circumstance_formatted = process_circumstance(circumstance_raw) + try: + Circumstances.model_validate(circumstance_formatted) + circumstances = Circumstances(**circumstance_formatted) + error = None + except ValidationError as e: + error = e + print(e) + circumstances = None + return circumstances, error + + +def validate_behavior(data): + behaviors_raw = get_fields(data, "behaviors") + behaviors_formatted = process_behaviors(behaviors_raw) + try: + Behaviors.model_validate(behaviors_formatted) + behavior = Behaviors(**behaviors_formatted) + error = None + except ValidationError as e: + print(e) + print("Validation failed for the behaviors.") + behavior = None + error = e + return behavior, error + + +def validate_physical(data): + physical_raw = get_fields(data, "physical") + physical_formatted = process_physical(physical_raw) + try: + PhysicalAnomalies.model_validate(physical_formatted) + physical = PhysicalAnomalies(**physical_formatted) + error = None + except ValidationError as e: + print(e) + print("Validation failed for the physical anomalies.") + physical = None + error = e + return physical, error + +def validate_follow_up(data): + followup_raw = get_fields(data, "followup") + followup_formatted = process_followup(followup_raw) + try: + FollowUpEvents.model_validate(followup_formatted) + followup = FollowUpEvents(**followup_formatted) + error = None + except ValidationError as e: + print(e) + print("Validation failed for the follow-up events.") + followup = None + return followup, error + + + diff --git a/app/wounded.py b/app/wounded.py new file mode 100644 index 0000000000000000000000000000000000000000..30340ca8601363e12bcfe52c4125fcfabeb2a441 --- /dev/null +++ b/app/wounded.py @@ -0,0 +1,49 @@ +import gradio as gr +from circumstances.circumstances import create_circumstances +from physical.physical_select_animal import create_bird_anatomy +from physical.physical_checkbox import process_body_parts +from behavior.behavior_checkbox import create_behavior_checkbox +from follow_up.followup_events import create_followup_dropdowns, create_followup_open +from validation_submission.add_json import add_data_to_individual + +def show_section_wounded(visible): + if visible==True: + add_data_to_individual("wounded_state", "Yes") + add_data_to_individual("dead_state", "No") + + with gr.Column(visible=visible, elem_id="wounded") as wounded_section: + gr.Markdown("# Wounded / Sick Animal") + + gr.Markdown("## Do you know what conditions caused this?", label="description") + radio_cause = gr.Radio(["Yes", "No"], value=None, show_label=False, interactive=True) + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2 = create_circumstances(visible=False) + + gr.Markdown("## Is the bird displaying behavioural changes?" , label="description") + radio_behaviour = gr.Radio(["Yes", "No"], value=None, show_label=False, interactive=True) + with gr.Row(): + behavior_checkbox, behavior_text = create_behavior_checkbox("wounded", False) + + gr.Markdown("## Are there physical changes on the bird?" , label="description") + radio_physical = gr.Radio(["Yes", "No"], value=None, show_label=False, interactive=True) + with gr.Row(): + physical_boxes = create_bird_anatomy(False, "wounded") + with gr.Column(): + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs = process_body_parts("wounded", "None") + + + gr.Markdown("## Follow-Up Events", label="Title") + gr.Markdown("Please tell us what you did with the animal.", label="description") + with gr.Row(): + fe_collection_dropdown, fe_recepient_dropdown, fe_radio_dropdown, fe_answer_dropdown = create_followup_dropdowns(visible, "wounded") + with gr.Row(): + fe_name_recipient, fe_collection_ref = create_followup_open(visible, "wounded") + + + # Change variables and names + return wounded_section, radio_cause, radio_behaviour, radio_physical, \ + button_collision, button_deliberate_destruction, button_indirect_destruction, button_natural_cause, \ + dropdown, dropdown_level2, openfield_level2, dropdown_extra_level2, \ + behavior_checkbox, behavior_text, \ + physical_boxes, \ + checkbox_beak, text_beak, checkbox_body, text_body, checkbox_feathers, text_feathers, checkbox_head, text_head, checkbox_legs, text_legs, \ + fe_collection_dropdown, fe_recepient_dropdown, fe_radio_dropdown, fe_answer_dropdown, fe_name_recipient, fe_collection_ref diff --git a/data/.gitkeep b/data/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/all_individuals.json b/data/all_individuals.json new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/data/all_individuals.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/data/one_individual.json b/data/one_individual.json new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/data/one_individual.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..65e2914555f44c0328949b4b2bf626f23833737c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +gradio +gradio_modal +geopy +geopandas +pillow +python-dotenv \ No newline at end of file diff --git a/test.py b/test.py new file mode 100644 index 0000000000000000000000000000000000000000..17728a5c334fc0d45d90b4d2683d3a915a14ad1d --- /dev/null +++ b/test.py @@ -0,0 +1,10 @@ +# app.py +import gradio as gr + +def greet(name): + return f"Hello, {name}!" + +demo = gr.Interface(fn=greet, inputs="text", outputs="text") + +if __name__ == "__main__": + demo.launch() \ No newline at end of file