diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..58c8138 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +.vscode +.venv +.ipynb_checkpoints +.idea +.gradle +__pycache__ +scholar.log +geckodriver.log +/resources/config.json +/lastrun.log +/resources/corrected/* +/nime/ +/cache/ +/output/ +/ignore/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 4ef59f1..89f340d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,217 @@ -This repository contains a software to extract and analyze data from the [NIME archive](https://www.nime.org/). +# [NIME](https://www.nime.org/) Proceedings Analyzer + +The NIME Proceedings Analyzer (PA) is a tool written in python to perform a bibliographic analysis of the New Interfaces for Musical Expression (NIME) proceedings archive. + +The tool is includes four scripts: + +1. [pa.py](pa.py) - Generates a rich database from extracted meta-information associated with all [papers published at NIME](https://github.com/NIME-conference/NIME-bibliography/blob/master/paper_proceedings/nime_papers.bib). The database is saved in the file *./output/export.csv*. It also generates plain body-text files associated with all papers inside the *./cache/* folder. + +2. [analysis_meta.py](analysis_meta.py) - Analyzes the metadata stored in *./output/export.csv*. and produces a pair of .txt and .xlsx files in *./output/* with statistics related to papers, authorship, affiliation, travel. + +3. [analysis_topic.py](analysis_topic.py) - Analyzes keywords and topics in the titles and body text of the papers, generates titles and body-text wordclouds, and computes a visualization of topics modeled with the Latent Dirichlet Allocation (LDA) algorithm. Produced files are saved in *./output/*. + +4. [analysis_search.py](analysis_search.py) - Searches specific keywords through the papers and it produces a graph with the search terms over the years in a .xlsx file saved in *./output/*. + +## Description & Usage + +### Requirements + +The NIME PA requires Python 3.7 or higher. + +Install required packages: +``` +pip install -r requirements.txt +``` + +Run the scripts with any additional flags (see below): +``` +python pa.py +python analysis_meta.py +python analysis_topic.py +python analysis_search.py +``` + +## pa.py + +This script produces a database which includes an entry for each published NIME paper. For each paper the database includes: +- information extracted from the [NIME BibTex Archive](https://github.com/NIME-conference/NIME-bibliography/blob/master/paper_proceedings/nime_papers.bib) +- additional information extracted from the PDF file of the papers using [Grobid](https://github.com/kermitt2/grobid) +- location and affiliation of the authors, extracted using a combination methods that minimizes errors +- gender of the authors estimated using a [binary](https://github.com/parthmaul/onomancer) and [non-binary method](https://github.com/lead-ratings/gender-guesser) +- number of citations received by the paper and key citations extracted from [Semantic Scholar](https://www.semanticscholar.org/) +- estimated distance and carbon footprint for authors traveling to the conference. + +All the materials above are automatically downloaded and extracted as publicly available resources and stored in the local *./cache/* folder. Only the conference locations are provided in the file *./resources/conferences.csv*, which contains information up to and including year 2020. Additionally, the script produces a plain text files of the body for all papers which is stored in *./cache/text/*. + +The script accepts the following optional arguments: +- **-h, --help** show this help message and exit +- **-v, --verbose** prints out operations +- **-c, --citations** bypass cache to retrieve new citations +- **-g, --grobid** forces repopulation of Grobid files +- **-r, --redo** deletes cache +- **-n, --nime** uses NIME based corrections + +The first execution of the script will take a significant amount of time, approximately 12 hours. +The most time consuming operations are: downloading of PDF files associated with the papers, generating xml files associated with the papers and stored in *./cache/xml/* through Grobid, and querying Semantic Scholar (due to their public API limit). + +Depending on the arguments, the script may interactively prompt "Yes"/"No" questions to the user in the initial phases of the execution. + +**-v** - This argument prints details of the script's progress. Thanks to the cache, if the script encounters a temporary error (e.g. fail to download a file) or if it gets intentionally interrupted, data computed/downloaded in the previous run will not be lost. When restarted, the script will quickly progress to the point in which it was interrupted. + +**-c** - Citations associated with papers changes very frequently and this argument forces the script to bypass the citation info stored in the cache file and retrieve new ones from Semantic Scholar. The updated citation number is then stored in the cache. + +**-g** - This argument forces the script to regenerate the xml files associated with the papers using Grobid. This may be suitable when a new version of Grobid is released. The script downloads and uses the latest release of Grobid. You can check the used version from the associated cache folder. + +**-r** - This argument deletes all cached files to make a clean start. + +**-n** - This argument enables a few manual corrections of author names and gender specific to NIME authors. Despite an effort to make the tool as generic and robust as possible, there are still a few exceptions, often due to inconsistent recording of data. Their handling is managed by the portions of the script which are executed only if this argument is passed to the script. + +### analysis_meta.py + +If facing consistent problems with one or more specific papers (such as download failing, or failing to extract data to PDF file because corrupted or badly encoded), the user can manually download the paper from another source, name it as specified in the [NIME BibTex Archive](https://github.com/NIME-conference/NIME-bibliography/blob/master/paper_proceedings/nime_papers.bib), and place it in the folder *./resources/corrected/*. + +This script analyzes the metadata stored in *./output/export.csv*. and produces statistics related to 1) papers, 2) authorship, 3) affiliation, 4) travel. This script requires the data generated by the pa.py script. + +The script accepts the following optional arguments: +- **-h, --help** show this help message and exit +- **-v, --verbose** prints out operations +- **-n, --nime** uses NIME based corrections + +**-v** - This argument prints details of the script's progress. + +**-n** - This argument forces a few correction on author names and gender specific to NIME authors. In the current version this argument has no effect. + +The analysis can be restricted to specific years through the [custom.csv](#custom.csv) file in the *./resources/* folder. + +The script interactively prompt "Yes"/"No" questions for computing the statistics associated with the four above-mentioned categories. + +The statistics computed by the script are stored in the following files: +- *./output/papers.txt* +- *./output/papers.xlsx* +- *./output/authors.txt* +- *./output/authors.xlsx* +- *./output/affiliations.txt* +- *./output/affiliations.xlsx* +- *./output/travel.txt* +- *./output/travel.xlsx* + +Overall statistics and are included in the .txt files. Detailed statistic per year, paper, author, institution, country, continent, etc., are included in the .xlsx files. + +In the .xlsx files, sheet names are limited to 31 characters and the following abbreviations are used: +- avg. = average +- num. = number +- cit. = citations +- yr. = year +- norm. = normalized +- auth. = author +- pub. = publication +- dist. = distance +- distr. = distribution +- footp. = footprint +- part. = participant +- cont. = continent +- count. = country +- instit. = institute +- \> = more than +- % = percentage +- \# = number of + +## analysis_topic.py + +This script analyzes topics in the titles and body text of the papers, and it produces 1) statistical and trends on keywords, 2) titles and body-text wordclouds, and 3) a visualization of topics modeled with the Latent Dirichlet Allocation (LDA) algorithm. Produced files are saved in *./output/topics.xlsx*. This script requires the data generated by the pa.py script. + +The script accepts the following optional arguments: +- **-h, --help** show this help message and exit +- **-v, --verbose** prints out operations +- **-n, --nime** uses NIME based corrections + +**-v** - This argument prints details of the script's progress. + +**-n** - This argument forces a few correction on author names and gender specific to NIME authors. In the current version this argument has no effect. + +The analysis can be highly customized through the *custom.csv* file in the *./resources/* folder. + +The script interactively prompt "Yes"/"No" questions for computing the data associated with the three above-mentioned categories. + +In respect to generating LDA model, a user can choose how many topics the algorithm will attempt to categorize from the relative frequencies of words in the corpus. This will require compiling all text from each paper into a large dictionary and corpus. Both the model and the dict. and corpus are saved in the *./cache/lda* folder Thus, four options are available upon running to create a new model, rebuild dictionary and corpus, do both, or load a prebuilt model. + +The script produces the following output files: +- *./output/topics.xlsx* +- *./output/topic_occurrence.png* +- *./output/wordcloud_bodies.png* +- *./output/wordcloud_titles.png* +- *./output/lda.html* + +## analysis_search.py + +This script provides a quick method of searching through the documents with keywords specified in the *./resources/custom.csv*. It produces a graph with the search terms listed over the specified year range. + +The script produces the following output files: +- *./output/keyword_occurrence.png* +- *./output/keyword_occurrence.xlsx* + +### custom.csv + +Through this file, located in the *./resources/* folder, it is possible to customize the metadata and topic analysis. The following entries are allowed: + +- **years**: restrict the analysis to specific years (single cell), or to a a specific range (two adjacent cells). This entry can be repeated across multiple rows for incongruent years. This works with *analysis_meta.py*, *analysis_topic.py*, and *analysis_search.py*. + +- **keywords**: specify words (one in each cell) that can be queried for occurrence frequency using *analysis_search.py*. + +- **ignore**: specify words that will be ignored from word counts tallies. This works only with *analysis_topic.py*. + +- **merge**: specify words that should be merged together, where the left-most cell will be the word that other words (that follow from the right) will be changed to. This works only with *analysis_topic.py*. + +An example of the analysis customization file is available [here](resources/custom_ex.csv). + +## Troubleshooting + +The following tips may help to triubleshoot the execution of pa.py: + +1. A temporary log file *lastrun.log* is generated in the root folder with the details of all operations during the last run of each script. This file is regenerated on each run of each script. It can be used to inspect the results of a last run or if errors had occurred during its execution. + +2. If you encounter an error that interrupts pa.py, restart the execution with the same arguments (with exception of those deleting caches and forcing the regeneration of xml files). The script is able to quickly resume from the point in which it has been interrupted, and if the nature of the error was temporary (e.g. a download failure due to network problems) the script is should be able to continue the process. + +3. If facing consistent problems with one or more specific papers, such as download failing, or failing to extract data from PDF files because corrupted or badly encoded (i.e. associated word count equal to 0 in export.csv), the user can manually download the paper from another source, name it as specified in the [NIME BibTex Archive](https://github.com/NIME-conference/NIME-bibliography/blob/master/paper_proceedings/nime_papers.bib), and place it in the folder *./resources/corrected/*. It is also recommended to remove the associated files with a similar file name that may have been created in *./cache/xml/*, *./cache/text/miner/*, and *./cache/text/grobid/*. + +4. When badly encoded papers are not available elsewhere, it is possible to recover them using [OCRmyPDF](https://github.com/jbarlow83/OCRmyPDF), which is a tool to add an OCR text layer to scanned PDF files, but it also works well to replace the badly encoded original text. Often OCRmyPDF significantly increase file size, but files can be further compressed using a third party tool or using the same script and adding compression options at line 16. A limitation of OCRmyPDF is that the generated text layer also includes text found in images. The folder *./resources/corrected/* in the releases includes all papers we fixed or sourced elsewhere due to download or encoding problems. + +5. At times, the download of the PDF file may fail but a zero-bytes file is still generated in the folder *./cache/pdf/*. As a consequence, incomplete data related to the paper will be stored in export.csv. After a complete execution of pa.py it is recommended to look for zero-bytes PDF in *./cache/pdf/*, remove them and the associated files created in *./cache/xml/*, *./cache/text/miner/*, and *./cache/text/grobid/*. Then restart pa.py with the same arguments (with exception of those deleting caches and forcing the regeneration of xml files), the new export.csv file with complete information will be generated in a fairly short amount of time. + +## Resources The extracted data from 2001 to 2020 is presented in: -S. Fasciani, J. Goode, [20 NIMEs: Twenty Years of New Interfaces for Musical Expression](https://nime.pubpub.org/pub/piegwp66), in proceedings of 2021 International Conference on New Interfaces for Musical Expression, Shanghai, China, 2021. +S. Fasciani, J. Goode, [20 NIMEs: Twenty Years of New Interfaces for Musical Expression](https://nime.pubpub.org/pub/20nimes/), in proceedings of 2021 International Conference on New Interfaces for Musical Expression, Shanghai, China, 2021. + +The data presented in the paper has been further manually polished and arranged in a [spreadsheet]((https://docs.google.com/spreadsheets/d/134zxeEhhXp3o7G_S1oDVjDymPuj2J3Wj3ftEAdOEo8g/edit?usp=sharing).) which includes a large collection of plots and visualizations. + +In the release section, there are versions of of this repository after the the execution of all scripts on a specific date. This include also all output and cache files except for the PDF associated with the papers (due to file size reason). Releases can be used run the meta and topic analysis without waiting for the pa.py script to generate the necessary files, or to force pa.py to update only selected outputs through the available arguments. + +## License + +All code in this repository is licensed under [GNU GPL 3.0](https://www.gnu.org/licenses/gpl-3.0.html). + +``` +NIME Proceedings Analyzer (NIME PA) +Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +The NIME PA is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The NIME PA 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . -This spreadsheet includes data, charts and table presented in the paper is available [here](https://docs.google.com/spreadsheets/d/134zxeEhhXp3o7G_S1oDVjDymPuj2J3Wj3ftEAdOEo8g/edit?usp=sharing). +If you use the NIME Proceedings Analyzer or any part of it in any program or +publication, please acknowledge its authors by adding a reference to: -License: [GNU GPL 3.0](https://www.gnu.org/licenses/gpl-3.0.html). +S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +Expression, in proceedings of 2021 International Conference on New Interfaces +for Musical Expression, Shanghai, China, 2021. +``` diff --git a/analysis_meta.py b/analysis_meta.py new file mode 100644 index 0000000..61051b5 --- /dev/null +++ b/analysis_meta.py @@ -0,0 +1,661 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import sys +if sys.version_info < (3, 7): + print("Please upgrade Python to version 3.7.0 or higher") + sys.exit() +import os +from os import path +import argparse +import ast +from collections import Counter +from itertools import cycle + +# External +import gensim +import unidecode +import re +import pandas as pd +from pandas import DataFrame +import numpy as np +import datetime +from scipy.optimize import curve_fit + +# Helper +import pa_print +from pa_utils import try_index, import_config, boolify + +def load_bib_csv(filepath, selectedyears): + # TODO: This may not be the best solution available + generic = lambda x: ast.literal_eval(x) + # ! Check if these are relevant or if we need to extend + conv = {'author distances': generic, + 'author footprints': generic, + 'author genders': generic, + 'author genders 2': generic, + 'author loc queries': generic, + 'author location info': generic, + 'author names': generic, + 'conference location info': generic, + 'grobid addresses': generic, + 'grobid author names': generic, + 'grobid author unis': generic, + 'grobid emails': generic, + 'grobid organisations': generic, + 'text author unis': generic, + 'countries': generic, + 'continents': generic, + 'institutes': generic} + + try: # accomodate regional delimiters + bib_df = pd.read_csv(filepath, converters=conv) + except: + bib_df = pd.read_csv(filepath, converters=conv, sep=';') + + #remove years not included in custom.csv_save + if selectedyears: + selectedyears = [int(i) for i in selectedyears] + bib_df = bib_df[bib_df['year'].isin(selectedyears)] + + # Convert 'N/A' to NaN so pandas parser will ignore + bib_df['author footprints'] = [pd.to_numeric(footprints, errors='coerce') for footprints in bib_df['author footprints']] + bib_df['author distances'] = [pd.to_numeric(footprints, errors='coerce') for footprints in bib_df['author distances']] + + return bib_df + +def load_conf_csv(filepath): + + try: # accommodate regional delimiters + conf_df = pd.read_csv(filepath) + except: + conf_df = pd.read_csv(filepath, sep=';') + + return conf_df + +def papers_perc_citations(bib_df, perc): + papers_total = len(bib_df.index) + cit_total = bib_df['citation count'].sum() + temp = bib_df['citation count'].sort_values(ascending=False) + i = 0 + while True: + current_perc = temp[0:i].sum() / cit_total + if current_perc > perc: + break + i = i + 1 + + return i, i/papers_total + +def papers_perc_citations_year(bib_df, perc): + years = bib_df['year'].unique() + out = pd.DataFrame(index = years) + out['number of papers'] = '' + out['percentage papers'] = '' + for y in years: + temp1 = bib_df.loc[bib_df['year'] == y] + papers_total = len(temp1.index) + cit_total = temp1['citation count'].sum() + temp2 = temp1['citation count'].sort_values(ascending=False) + i = 0 + while True: + current_perc = temp2[0:i].sum() / cit_total + if current_perc > perc: + out.at[y,'number of papers'] = i + out.at[y,'percentage papers'] = 100*i/papers_total + break + i = i + 1 + + return out + +def papers_top_citations_year(bib_df): + years = bib_df['year'].unique() + out = pd.DataFrame(index = years) + out['title'] = '' + out['citation count'] = '' + out['NIME reader'] = '' + for y in years: + temp = bib_df.loc[bib_df['year'] == y] + max_cit = temp['citation count'].max() + out.at[y,'title'] = temp.loc[bib_df['citation count'] == max_cit]['title'].to_string(index=False) + out.at[y,'citation count'] = temp.loc[bib_df['citation count'] == max_cit]['citation count'].to_string(index=False) + out.at[y,'NIME reader'] = temp.loc[bib_df['citation count'] == max_cit]['NIME reader'].to_string(index=False) + + return out + +def lotka_law(x, n, c): + return c / np.power(x, n) + +# Functions for generating stat-specific metrics +def stats_papers(bib_df): + + pa_print.nprint('\nComputing papers statistics...') + + outtxt = '' + # papers in total and per year + papers_total = len(bib_df.index) + papers_per_year = bib_df['year'].value_counts(sort=False) + outtxt += '\nTotal papers %d' % papers_total + + # growth of NIME papers corpus per year + papers_per_year_cumulative = bib_df['year'].value_counts(sort=False).cumsum() + + # full-short-other papers + temp = bib_df.loc[bib_df['page count'] > 4] + full_papers_per_year = temp['year'].value_counts(sort=False) + full_papers_total = full_papers_per_year.sum() + temp = bib_df.loc[(bib_df['page count'] > 2) & (bib_df['page count'] <= 4)] + short_papers_per_year = temp['year'].value_counts(sort=False) + short_papers_total = short_papers_per_year.sum() + temp = bib_df.loc[(bib_df['page count'] <= 2)] + other_papers_per_year = temp['year'].value_counts(sort=False) + other_papers_total = other_papers_per_year.sum() + outtxt += '\nTotal Full Papers %d' % full_papers_total + outtxt += '\nTotal short papers %d' % short_papers_total + outtxt += '\nTotal Other Papers %d' % other_papers_total + + # pages + papers_by_pages = bib_df['page count'].value_counts(sort=False) + average_paper_length = bib_df['page count'].mean() + max_paper_length = bib_df['page count'].max() + pages_per_year_average = bib_df.groupby(['year'])['page count'].mean() + pages_per_year_total = bib_df.groupby(['year'])['page count'].sum() + longest_papers_pages = bib_df.loc[bib_df['page count'] == max_paper_length]['title'] + outtxt += '\nAverage papers length %f' % average_paper_length + outtxt += '\nMax papers length %d' % max_paper_length + + # word count + words_total = bib_df['word count'].sum() + words_average = bib_df['word count'].mean() + + temp = bib_df.loc[bib_df['page count'] > 4] + words_average_full = temp['word count'].mean() + + temp = bib_df.loc[(bib_df['page count'] > 2) & (bib_df['page count'] <= 4)] + words_average_short = temp['word count'].mean() + + temp = bib_df.loc[bib_df['page count'] <= 2] + words_average_other = temp['word count'].mean() + + temp = bib_df.loc[bib_df['page count'] == 6] + words_average_sixpages = temp['word count'].mean() + + temp = bib_df.loc[bib_df['page count'] == 4] + words_average_fourpages = temp['word count'].mean() + + temp = bib_df.loc[bib_df['page count'] == 2] + words_average_twopages = temp['word count'].mean() + + words_per_year_total = bib_df.groupby(['year'])['word count'].sum() + words_per_year_average = bib_df.groupby(['year'])['word count'].mean() + + max_paper_words = bib_df['word count'].max() + longest_papers_words = bib_df.loc[bib_df['word count'] == max_paper_words]['title'] + + counts, bins = np.histogram(bib_df['word count'], bins=50) + center = (bins[:-1] + bins[1:]) / 2 + papers_by_words = pd.DataFrame(counts, index = center, columns = ['count']) + + outtxt += '\nTotal word count %d' % words_total + outtxt += '\nAverage word count %f' % words_average + outtxt += '\nAverage word count full papers %f' % words_average_full + outtxt += '\nAverage word count short papers %f' % words_average_short + outtxt += '\nAverage word count other papers %f' % words_average_other + outtxt += '\nAverage word count 6 pages %f' % words_average_sixpages + outtxt += '\nAverage word count 4 pages %f' % words_average_fourpages + outtxt += '\nAverage word count 2 pages %f' % words_average_twopages + outtxt += '\nMax papers words %d' % max_paper_words + + # citations + papers_by_citations = bib_df['citation count'].value_counts(sort=False).sort_index() + citations_total = bib_df['citation count'].sum() + citations_per_year = bib_df.groupby(['year'])['citation count'].sum() + citations_per_year_norm_by_numpaper = bib_df.groupby(['year'])['citation count'].mean() + citations_per_year_norm_by_agepapers = bib_df.groupby(['year'])['yearly citations'].mean() + + temp = bib_df.loc[bib_df['citation count'] >= 1] + papers_at_least_1_citation = len(temp.index) + + temp = bib_df.loc[bib_df['citation count'] >= 10] + papers_more_10_citations = len(temp.index) + + citations_50perc = papers_perc_citations(bib_df, 0.5) + citations_90perc = papers_perc_citations(bib_df, 0.9) + + citations_50perc_per_year = papers_perc_citations_year(bib_df, 0.5) + citations_90perc_per_year = papers_perc_citations_year(bib_df, 0.9) + + temp = bib_df.sort_values(by=['citation count'],ascending=False) + temp = temp.head(20) + top_papers_by_citations = temp[['citation count', 'title', 'year', 'NIME reader']] + + temp = bib_df.sort_values(by=['yearly citations'],ascending=False) + temp = temp.head(20) + top_papers_by_yearly_citations = temp[['yearly citations', 'title', 'year', 'NIME reader']] + + most_cited_paper_by_pub_year = papers_top_citations_year(bib_df) + + temp = bib_df.loc[bib_df['citation count'].isnull()] + not_cited_pages = temp['page count'].value_counts(sort=True) + + outtxt += '\nTotal citations %d' % citations_total + outtxt += '\nPapers with at least 1 citation %d equivaent to %f %%' % (papers_at_least_1_citation,100*papers_at_least_1_citation/papers_total) + outtxt += '\nPapers with 10 or more citations %d equivalent to %f %%' % (papers_more_10_citations, 100*papers_more_10_citations/papers_total) + outtxt += '\n50%% citations are from %d papers representing %f %% of the total' % (citations_50perc[0],100*citations_50perc[1]) + outtxt += '\n90%% citations are from %d papers representing %f %% of the total' % (citations_90perc[0],100*citations_90perc[1]) + + with pd.ExcelWriter('./output/papers.xlsx') as writer: + papers_per_year.to_excel(writer, sheet_name='Papers per year', header=False) + papers_per_year_cumulative.to_excel(writer, sheet_name='Cumulative papers per year', header=False) + full_papers_per_year.to_excel(writer, sheet_name='Full papers per year', header=False) + short_papers_per_year.to_excel(writer, sheet_name='Short papers per year', header=False) + other_papers_per_year.to_excel(writer, sheet_name='Other papers per year', header=False) + longest_papers_pages.to_excel(writer, sheet_name='Longest papers in pages', header=False) + pages_per_year_total.to_excel(writer, sheet_name='Pages total per year', header=False) + pages_per_year_average.to_excel(writer, sheet_name='Pages average per year', header=False) + papers_by_pages.to_excel(writer, sheet_name='Papers by page length', header=False) + longest_papers_words.to_excel(writer, sheet_name='Longest papers', header=False) + words_per_year_total.to_excel(writer, sheet_name='Words total per year', header=False) + words_per_year_average.to_excel(writer, sheet_name='Words average per year', header=False) + papers_by_words.to_excel(writer, sheet_name='Papers by page length', header=False) + citations_per_year.to_excel(writer, sheet_name='Cit. per year', header=False) + citations_per_year_norm_by_numpaper.to_excel(writer, sheet_name='Cit. per year norm. by #papers', header=False) + citations_per_year_norm_by_agepapers.to_excel(writer, sheet_name='Cit. pr yr. norm. by #papers&age', header=False) + citations_50perc_per_year.to_excel(writer, sheet_name='50% cit. from papers per year', header=True) + citations_90perc_per_year.to_excel(writer, sheet_name='90% cit. from papers per year', header=True) + top_papers_by_citations.to_excel(writer, sheet_name='Top papers by cit.', header=True) + top_papers_by_yearly_citations.to_excel(writer, sheet_name='Top papers by yearly cit.', header=True) + most_cited_paper_by_pub_year.to_excel(writer, sheet_name='Most cited paper by pub. year', header=True) + papers_by_citations.to_excel(writer, sheet_name='Papers by cit.', header=False) + not_cited_pages.to_excel(writer, sheet_name='Not cited papers by page length', header=False) + + with open('./output/papers.txt', 'w') as text_file: + text_file.write(outtxt) + + print('\nGenerated papers.txt and papers.xlsx in ./output!') + +def stats_authors(bib_df): + + pa_print.nprint('\nComputing authorship statistics...') + + outtxt = '' + + auth_df = pd.DataFrame(index=range(bib_df['author count'].sum()), columns=['year','name','gender1','gender2','citations','first','mixed']) + j = 0 + authfem_df = pd.DataFrame(index=bib_df.index, columns=['year','1F']) + for idx, pub in bib_df.iterrows(): + authfem_df.loc[idx,'year'] = pub['year'] + author_count = pub['author count'] + flag = False + for i in range(author_count): + auth_df.loc[j,'year']= pub['year'] + auth_df.loc[j,'name'] = pub['author names'][i][0] + ' ' + pub['author names'][i][1] + auth_df.loc[j,'gender1'] = pub['author genders'][i] + auth_df.loc[j,'gender2'] = pub['author genders 2'][i] + if pub['author genders 2'][i] == 'F': + flag = True + auth_df.loc[j,'citations'] = pub['citation count'] + if i == 0: + auth_df.loc[j,'first'] = True + else: + auth_df.loc[j,'first'] = False + j = j + 1 + + authfem_df.loc[idx,'1F'] = flag + + # author count and gender + total_authors = bib_df['author count'].sum() + total_male_authors = len(auth_df[auth_df['gender2'] == 'M']) + total_female_authors = len(auth_df[auth_df['gender2'] == 'F']) + total_neutral_authors = len(auth_df[auth_df['gender2'] == 'N']) + + temp = auth_df.drop_duplicates(subset = ['name']) + unique_authors = len(temp.index) + unique_male_authors = len(temp[temp['gender2'] == 'M']) + unique_female_authors = len(temp[temp['gender2'] == 'F']) + unique_neutral_authors = len(temp[temp['gender2'] == 'N']) + + papers_by_numauthors = bib_df['author count'].value_counts(sort=False) + + average_authors = bib_df['author count'].mean() + average_authors_per_year = bib_df.groupby(['year'])['author count'].mean() + total_authors_per_year = bib_df.groupby(['year'])['author count'].sum() + + auth_df_unique = auth_df.drop_duplicates(subset = ['name','year']) + unique_authors_per_year = auth_df_unique.groupby(['year'])['name'].nunique() + authors_by_editions = auth_df_unique['name'].value_counts(sort=True) + authors_with_editions = authors_by_editions.value_counts(sort=False).sort_index() + + temp = auth_df[auth_df['gender2'] == 'M'] + total_male_authors_by_year = temp.groupby(['year']).size() + temp = auth_df[auth_df['gender2'] == 'F'] + total_female_authors_by_year = temp.groupby(['year']).size() + temp = auth_df[auth_df['gender2'] == 'N'] + total_neutral_authors_by_year = temp.groupby(['year']).size() + total_male_percentage_by_year = (100 * total_male_authors_by_year / (total_male_authors_by_year + total_female_authors_by_year)) + + temp = auth_df_unique[auth_df_unique['gender2'] == 'M'] + unique_male_authors_by_year = temp.groupby(['year']).size() + temp = auth_df_unique[auth_df_unique['gender2'] == 'F'] + unique_female_authors_by_year = temp.groupby(['year']).size() + temp = auth_df_unique[auth_df_unique['gender2'] == 'N'] + unique_neutral_authors_by_year = temp.groupby(['year']).size() + unique_male_percentage_by_year = (100 * unique_male_authors_by_year / (unique_male_authors_by_year + unique_female_authors_by_year)) + + papers_by_authors = auth_df['name'].value_counts(sort=True) + authors_with_numpapers = papers_by_authors.value_counts(sort=False).sort_index() + + temp = auth_df_unique[auth_df_unique['first'] == True] + papers_by_authors_first = temp['name'].value_counts(sort=True) + authors_with_numpapers_first = papers_by_authors_first.value_counts(sort=False).sort_index() + + authors_by_citations = auth_df.groupby(['name'])['citations'].sum().sort_values(ascending=False) + authors_with_citations = authors_by_citations.value_counts(sort=False).sort_index(ascending=True) + + gender_by_citations = auth_df.groupby(['gender2'])['citations'].sum() + gender_by_citations_per_year = auth_df.groupby(['gender2','year'])['citations'].sum() + + temp = authfem_df[authfem_df['1F'] == True] + one_fem = len(temp) + one_fem_per_year = 100 * temp.groupby(['year']).size() / authfem_df.groupby(['year']).size() + + years = auth_df['year'].unique() + auth_returning = pd.DataFrame(index = years) + auth_returning['first_time'] = '' + auth_returning['returning_other_years'] = '' + auth_returning['returning_previous_year'] = '' + auth_returning['total_unique'] = '' + poolall = [] + poolprevious = [] + + for y in years: + if y == 2001: + auth_returning.at[y,'returning_previous_year'] = 0 + auth_returning.at[y,'returning_other_years'] = 0 + auth_returning.at[y,'first_time'] = auth_df[auth_df['year'] == y]['name'].nunique() + auth_returning.at[y,'total_unique'] = auth_df[auth_df['year'] == y]['name'].nunique() + poolprevious = auth_df[auth_df['year'] == y]['name'].unique() + poolall = poolprevious + else: + temp = auth_df[auth_df['year'] == y]['name'].unique() + returning = np.intersect1d(temp, poolprevious) + auth_returning.at[y,'returning_previous_year'] = len(returning) + returning = np.intersect1d(temp, poolall) + auth_returning.at[y,'returning_other_years'] = len(returning) - auth_returning.at[y,'returning_previous_year'] + auth_returning.at[y,'first_time'] = len(temp) - auth_returning.at[y,'returning_previous_year'] - auth_returning.at[y,'returning_other_years'] + auth_returning.at[y,'total_unique'] = auth_df[auth_df['year'] == y]['name'].nunique() + poolprevious = auth_df[auth_df['year'] == y]['name'].unique() + poolall = np.unique(np.append(poolall,temp)) + + # lokta's law fitting + xdata = np.array(authors_with_numpapers.index) + ydata = np.array(authors_with_numpapers.values)/(np.array(authors_with_numpapers.values).sum()) + + popt, pcov = curve_fit(lotka_law, xdata, ydata) + residuals = ydata - lotka_law(xdata, *popt) + ss_res = np.sum(residuals**2) + ss_tot = np.sum((ydata-np.mean(ydata))**2) + r_squared = 1 - (ss_res / ss_tot) + #lotka_df = pd.DataFrame(data={'xdata': xdata, 'freq': ydata, 'fit': lotka_law(xdata, *popt)}) + + outtxt += '\nTotal authors %d - males %d - females %d - unknown %d' % (total_authors,total_male_authors,total_female_authors,total_neutral_authors) + outtxt += '\nUnique authors %d - males %d - females %d - unknown %d' % (unique_authors,unique_male_authors,unique_female_authors,unique_neutral_authors) + outtxt += '\nPapers with at least one female author %d' % one_fem + outtxt += '\nAverage authors per paper %f' % average_authors + outtxt += '\nLokta''s law fitting n %f - C %f - R^2 %f' % (popt[0],popt[1],r_squared) + + with pd.ExcelWriter('./output/authors.xlsx') as writer: + total_authors_per_year.to_excel(writer, sheet_name='Total authors per year', header=False) + unique_authors_per_year.to_excel(writer, sheet_name='Unique authors per year', header=False) + auth_returning.to_excel(writer, sheet_name='Returning authors', header=True) + average_authors_per_year.to_excel(writer, sheet_name='Avg. auth. per paper per year', header=False) + total_male_authors_by_year.to_excel(writer, sheet_name='Total male auth. per year', header=False) + total_female_authors_by_year.to_excel(writer, sheet_name='Total female auth. per year', header=False) + total_neutral_authors_by_year.to_excel(writer, sheet_name='Total unknown auth. per year', header=False) + total_male_percentage_by_year.to_excel(writer, sheet_name='Total male auth. % per year', header=False) + unique_male_authors_by_year.to_excel(writer, sheet_name='Unique male auth. per year', header=False) + unique_female_authors_by_year.to_excel(writer, sheet_name='Unique female auth. per year', header=False) + unique_neutral_authors_by_year.to_excel(writer, sheet_name='Unique unknown auth. per year', header=False) + unique_male_percentage_by_year.to_excel(writer, sheet_name='Unique male % per year', header=False) + papers_by_numauthors.to_excel(writer, sheet_name='Distr. papers by num authors', header=False) + papers_by_authors.to_excel(writer, sheet_name='Papers by authors', header=False) + authors_with_numpapers.to_excel(writer, sheet_name='Distr. authors with #papers', header=False) + papers_by_authors_first.to_excel(writer, sheet_name='Papers by authors first', header=False) + authors_with_numpapers_first.to_excel(writer, sheet_name='Authors first with #papers', header=False) + authors_by_editions.to_excel(writer, sheet_name='Authors at #editions', header=False) + authors_with_editions.to_excel(writer, sheet_name='Distr. auth. at #editions', header=False) + authors_by_citations.to_excel(writer, sheet_name='Authors by citations', header=False) + authors_with_citations.to_excel(writer, sheet_name='Distr. auth. with #citations', header=False) + gender_by_citations.to_excel(writer, sheet_name='Cit. males-females', header=False) + gender_by_citations_per_year.to_excel(writer, sheet_name='Cit. males-females per year', header=False) + one_fem_per_year.to_excel(writer, sheet_name='Papers with >1 female per year', header=False) + + with open('./output/authors.txt', 'w') as text_file: + text_file.write(outtxt) + + print('\nGenerated authors.txt and authors.xlsx in ./output!') + +def stats_affiliation(bib_df, conf_df): + + pa_print.nprint('\nComputing affiliation statistics...') + + outtxt = '' + + auth_df = pd.DataFrame(index=range(bib_df['author count'].sum()), columns=['year','name','citations','institute','country','continent']) + mixed_df = pd.DataFrame(index=bib_df.index, columns=['year','institute','country','continent']) + j = 0 + for idx, pub in bib_df.iterrows(): + author_count = pub['author count'] + for i in range(author_count): + auth_df.loc[j,'year']= pub['year'] + auth_df.loc[j,'name'] = pub['author names'][i][0] + ' ' + pub['author names'][i][1] + auth_df.loc[j,'citations'] = pub['citation count'] + auth_df.loc[j,'institute'] = pub['institutes'][i] + auth_df.loc[j,'country'] = pub['countries'][i] + auth_df.loc[j,'continent'] = pub['continents'][i] + j = j + 1 + if len(Counter(pub['institutes']).keys()) > 1: + mixed_df.loc[idx,'institute'] = True + else: + mixed_df.loc[idx,'institute'] = False + if len(Counter(pub['countries']).keys()) > 1: + mixed_df.loc[idx,'country'] = True + else: + mixed_df.loc[idx,'country'] = False + if len(Counter(pub['continents']).keys()) > 1: + mixed_df.loc[idx,'continent'] = True + else: + mixed_df.loc[idx,'continent'] = False + mixed_df.loc[idx,'year'] = pub['year'] + + # when counting - 1 removes the N/A + number_of_institutes = auth_df['institute'].nunique() - 1 + number_of_countries = auth_df['country'].nunique() - 1 + number_of_continents = auth_df['continent'].nunique() - 1 + + number_of_institutes_per_year = auth_df.groupby(['year'])['institute'].nunique() - 1 + number_of_countries_per_year = auth_df.groupby(['year'])['country'].nunique() - 1 + number_of_continents_per_year = auth_df.groupby(['year'])['continent'].nunique() - 1 + + top_institutes_by_authors = auth_df.groupby(['institute']).size().sort_values(ascending=False).head(40) + countries_by_authors = auth_df.groupby(['country']).size().sort_values(ascending=False) + continents_by_authors = auth_df.groupby(['continent']).size().sort_values(ascending=False) + + top_institutes_by_authorcitations = auth_df.groupby(['institute'])['citations'].sum().sort_values(ascending=False).head(40) + countries_by_authorcitations = auth_df.groupby(['country'])['citations'].sum().sort_values(ascending=False) + continents_by_authorcitations = auth_df.groupby(['continent'])['citations'].sum().sort_values(ascending=False) + + perc_mixed_institute_papers_fraction = 100 * mixed_df[mixed_df['institute'] == True].shape[0] / mixed_df.shape[0] + perc_mixed_country_papers_fraction = 100 * mixed_df[mixed_df['country'] == True].shape[0] / mixed_df.shape[0] + perc_mixed_continent_papers_fraction = 100 * mixed_df[mixed_df['continent'] == True].shape[0] / mixed_df.shape[0] + + temp = mixed_df[mixed_df['institute'] == True] + perc_mixed_institute_papers_fraction_per_year = 100 * temp.groupby(['year']).size() / mixed_df.groupby(['year']).size() + temp = mixed_df[mixed_df['country'] == True] + perc_mixed_country_papers_fraction_per_year = 100 * temp.groupby(['year']).size() / mixed_df.groupby(['year']).size() + temp = mixed_df[mixed_df['continent'] == True] + perc_mixed_continent_papers_fraction_per_year = 100 * temp.groupby(['year']).size() / mixed_df.groupby(['year']).size() + + top_institutes_by_year = auth_df.groupby(['year'])['institute'].value_counts() + top_countries_by_year = auth_df.groupby(['year'])['country'].value_counts() + top_continents_by_year = auth_df.groupby(['year'])['continent'].value_counts() + + years = auth_df['year'].unique() + perc_authors_diff_country_continent = pd.DataFrame(index = years, columns=['%_same_country_as_conference','%_same_continent_as_conference']) + for y in years: + same = len(auth_df[(auth_df['year'] == y) & (auth_df['country'] == conf_df[conf_df['year'] == y]['country'].values[0])].index) + tot = len(auth_df[(auth_df['year'] == y)].index) + perc_authors_diff_country_continent.at[y,'%_same_country_as_conference'] = 100 * same/tot + same = len(auth_df[(auth_df['year'] == y) & (auth_df['continent'] == conf_df[conf_df['year'] == y]['continent'].values[0])].index) + tot = len(auth_df[(auth_df['year'] == y)].index) + perc_authors_diff_country_continent.at[y,'%_same_continent_as_conference'] = 100 * same/tot + + outtxt += '\nNumber of institutes %d' % (number_of_institutes - 1) + outtxt += '\nNumber of countries %d' % (number_of_countries - 1) + outtxt += '\nNumber of continents %d' % (number_of_continents - 1) + outtxt += '\nPercentage paper author different institute %f' % perc_mixed_institute_papers_fraction + outtxt += '\nPercentage paper author different country %f' % perc_mixed_country_papers_fraction + outtxt += '\nPercentage paper author different coutinent %f' % perc_mixed_continent_papers_fraction + + with pd.ExcelWriter('./output/affiliations.xlsx') as writer: + number_of_institutes_per_year.to_excel(writer, sheet_name='Num. of auth. instit. per year', header=False) + number_of_countries_per_year.to_excel(writer, sheet_name='Num. of auth. countr. per year', header=False) + number_of_continents_per_year.to_excel(writer, sheet_name='Num. of auth. contin. per year', header=False) + top_institutes_by_authors.to_excel(writer, sheet_name='Top instit. by num authors', header=False) + countries_by_authors.to_excel(writer, sheet_name='Dist. count. by num authors', header=False) + continents_by_authors.to_excel(writer, sheet_name='Dist. contin. by num authors', header=False) + top_institutes_by_authorcitations.to_excel(writer, sheet_name='Top instit. by auth. cit.', header=False) + countries_by_authorcitations.to_excel(writer, sheet_name='Dist. countr. by auth. cit.', header=False) + continents_by_authorcitations.to_excel(writer, sheet_name='Dist. contin. by auth. cit.', header=False) + perc_mixed_institute_papers_fraction_per_year.to_excel(writer, sheet_name='% paper mixed instit. per year', header=False) + perc_mixed_country_papers_fraction_per_year.to_excel(writer, sheet_name='% paper mixed countr. per year', header=False) + perc_mixed_continent_papers_fraction_per_year.to_excel(writer, sheet_name='% paper mixed contin. per year', header=False) + perc_authors_diff_country_continent.to_excel(writer, sheet_name='% auth. from out conf. per year', header=True) + top_institutes_by_year.to_excel(writer, sheet_name='Top instit. by year', header=False) + top_countries_by_year.to_excel(writer, sheet_name='Top count. by year', header=False) + top_continents_by_year.to_excel(writer, sheet_name='Top contin. by year', header=False) + + with open('./output/affiliations.txt', 'w') as text_file: + text_file.write(outtxt) + + print('\nGenerated affiliations.txt and affiliations.xlsx in ./output!') + +def stats_travel(bib_df, conf_df): + + pa_print.nprint('\nComputing travel statistics...') + + outtxt = '' + + trav_df = pd.DataFrame(index=bib_df.index, columns=['year','distance','footprint','country','continent','gender']) + for idx, pub in bib_df.iterrows(): + trav_df.loc[idx,'year'] = pub['year'] + trav_df.loc[idx,'distance'] = pub['author distances'][0] + trav_df.loc[idx,'footprint'] = pub['author footprints'][0] + trav_df.loc[idx,'country'] = pub['countries'][0] + trav_df.loc[idx,'continent'] = pub['continents'][0] + trav_df.loc[idx,'gender'] = pub['author genders 2'][0] + + trav_df = trav_df.convert_dtypes() + + total_distance = trav_df['distance'].sum() + total_footprint = trav_df['footprint'].sum() + average_distance = trav_df['distance'].mean() + average_footprint = trav_df['footprint'].mean() + + total_distance_per_year = trav_df.groupby(['year'])['distance'].sum() + total_footprint_per_year = trav_df.groupby(['year'])['footprint'].sum() + average_distance_per_year = trav_df.groupby(['year'])['distance'].mean() + average_footprint_per_year = trav_df.groupby(['year'])['footprint'].mean() + + average_distance_per_continent = trav_df.groupby(['continent'])['distance'].mean() + average_footprint_per_continent = trav_df.groupby(['continent'])['footprint'].mean() + + average_distance_per_country = trav_df.groupby(['country'])['distance'].mean().sort_values(ascending=False) + average_footprint_per_country = trav_df.groupby(['country'])['footprint'].mean().sort_values(ascending=False) + + average_distance_per_gender = trav_df.groupby(['gender'])['distance'].mean() + average_footprint_per_gender = trav_df.groupby(['gender'])['footprint'].mean() + + participants_by_country = trav_df.groupby(['country'])['footprint'].count().sort_values(ascending=False) + participants_by_country_per_year = trav_df.groupby(['year','country'])['footprint'].count() + + outtxt += '\nTotal distance %f' % total_distance + outtxt += '\nTotal footprint %f' % total_footprint + outtxt += '\nAverage distance per participant %f' % average_distance + outtxt += '\nAverage footprint per participant %f' % average_footprint + + with pd.ExcelWriter('./output/travel.xlsx') as writer: + total_distance_per_year.to_excel(writer, sheet_name='Total dist. per year', header=False) + total_footprint_per_year.to_excel(writer, sheet_name='Total dist. per year', header=False) + average_distance_per_year.to_excel(writer, sheet_name='Avg. dist. per part. per year', header=False) + average_footprint_per_year.to_excel(writer, sheet_name='Avg. footp. per part. per year', header=False) + average_distance_per_continent.to_excel(writer, sheet_name='Avg. dist. per part. by cont.', header=False) + average_footprint_per_continent.to_excel(writer, sheet_name='Avg. footp. per part. by cont.', header=False) + average_distance_per_country.to_excel(writer, sheet_name='Avg. dist. per part. by count.', header=False) + average_footprint_per_country.to_excel(writer, sheet_name='Avg. footp. per part. by count.', header=False) + average_distance_per_gender.to_excel(writer, sheet_name='Avg. dist. per part. by gender', header=False) + average_footprint_per_gender.to_excel(writer, sheet_name='Avg. footp. per part. by gender', header=False) + participants_by_country.to_excel(writer, sheet_name='Participants by count.', header=False) + participants_by_country_per_year.to_excel(writer, sheet_name='Participants by count. per year', header=False) + + with open('./output/travel.txt', 'w') as text_file: + text_file.write(outtxt) + + print('\nGenerated travel.txt and travel.xlsx in ./output!') + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='Analyse the metadata stored in the output/export.csv') + parser.add_argument('-n', '--nime', action='store_true', default=False, + help='uses NIME based corrections') + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='prints out analysis stages results') + args = parser.parse_args() + + # Sets global print command + pa_print.init(args) + + # Print notice + pa_print.lprint() + + os.makedirs('./output', exist_ok=True) + + # Load databases + user_config = import_config('./resources/custom.csv') + conf_df = load_conf_csv('./resources/conferences.csv') + bib_df = load_bib_csv('./output/export.csv',user_config[3]) + + answer = boolify(input("\nGenerate papers statistics (Y/N): ")) + if answer: + stats_papers_out = stats_papers(bib_df) + + answer = boolify(input('\nGenerate authorship statistics (Y/N): ')) + if answer: + stats_authors_out = stats_authors(bib_df) + + answer = boolify(input('\nGenerate affiliation statistics (Y/N): ')) + if answer: + stats_affiliation_out = stats_affiliation(bib_df, conf_df) + + answer = boolify(input('\nGenerate travel statistics (Y/N): ')) + if answer: + stats_travel_out = stats_travel(bib_df, conf_df) diff --git a/analysis_search.py b/analysis_search.py new file mode 100644 index 0000000..5383119 --- /dev/null +++ b/analysis_search.py @@ -0,0 +1,135 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import sys +if sys.version_info < (3, 7): + print("Please upgrade Python to version 3.7.0 or higher") + sys.exit() +import os +import warnings +warnings.filterwarnings("ignore", category=DeprecationWarning) +import pickle +import argparse + +# External +import matplotlib +from matplotlib import pyplot as plt +from scipy.optimize import curve_fit +from scipy.interpolate import UnivariateSpline +import numpy as np +from tqdm import tqdm +import pandas as pd + +# Helper +import pa_print +from pa_utils import import_config + +grobid_text_src = './cache/text/grobid/' +lda_src = './cache/lda/' +num_topics = 5 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='A script for querying search terms occurrence over time') + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='prints out analysis process and results') + args = parser.parse_args() + + # Sets global print command + pa_print.init(args) + + # Print notice + pa_print.lprint() + + keywords, _, _, selected_years = import_config('./resources/custom.csv') # ignore and merge words already processed + if len(keywords) == 0: + print('No keywords found! Please add keywords in ./resources/custom.csv.') + sys.exit() + + if len(selected_years) != 0: + year_range = list(map(int,selected_years)) + year_start, year_end = min(year_range), max(year_range) + 1 + else: + year_start, year_end = 2001, 2021 + year_range = range(year_start, year_end) + + print(f'Searching for {keywords} in years {year_range}') + + print('\nLoading bodies, dict, corpus, and model...') + processed_bodies = pickle.load(open(lda_src+'bodies.pkl', 'rb')) + + # Create list to mark each text with year (will be linked to corpus values) + year_list = [] + for i in os.listdir(grobid_text_src): + if i.startswith('grob_'): + name = i.split('grob_nime')[-1] + year = name.split('_')[0] + year_list.append((int(year), name)) + + keyword_frequency = pd.DataFrame(index = year_range, columns = keywords) + + searched_words = dict() + year_counts = dict() + for i in year_range: + searched_words[i] = {} + year_counts[i] = 0 + + for year, doc in zip(year_list, processed_bodies): + year = year[0] + if year in year_range: + for term in keywords: + if searched_words[year].get(term): + searched_words[year][term] += doc.count(term) # update year total with current count + else: # initial entry + searched_words[year].update({term: doc.count(term)}) + + year_counts[year] += len(doc) # get total words/year + + for year, search in searched_words.items(): + for term in keywords: + search[term] = search[term] / year_counts[year] + keyword_frequency.at[year, term] = search[term] + + # * Show searched words + plt.figure(figsize=(20,10)) + + x = [year for year in searched_words.keys()] + for word in keywords: + y = [search[word] for search in searched_words.values()] + plt.scatter(x, y, label=word) + + # Spline + s = UnivariateSpline(x, y, s=5) + xs = np.linspace(year_start, year_end-1, 100) + ys = s(xs) + plt.plot(xs, ys, label=f'Spline for {word}') + + plt.legend() + plt.xlabel('Year') + plt.ylabel('Frequency of Keyword within Paper') + plt.title('Frequency of Keyword over Publication Year') + plt.savefig('./output/keyword_occurrence.png') + + with pd.ExcelWriter('./output/keyword_occurrence.xlsx') as writer: + keyword_frequency.to_excel(writer, sheet_name='Keyword Occurrence', header=True) diff --git a/analysis_topic.py b/analysis_topic.py new file mode 100644 index 0000000..da68c80 --- /dev/null +++ b/analysis_topic.py @@ -0,0 +1,404 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import sys +if sys.version_info < (3, 7): + print("Please upgrade Python to version 3.7.0 or higher") + sys.exit() +import warnings +warnings.simplefilter("ignore", category=DeprecationWarning) +import imp +import os +from os import path +import io +import re +import pickle +import collections +import argparse +from datetime import datetime + +# External +from matplotlib import pyplot as plt +from scipy.optimize import curve_fit +from scipy.interpolate import UnivariateSpline +import gensim +import gensim.corpora as corpora +from gensim.utils import simple_preprocess +from gensim.models import CoherenceModel, LdaMulticore, LdaModel +import pyLDAvis, pyLDAvis.gensim_models +import pandas as pd +import numpy as np + +import nltk +nltk.download('punkt', download_dir='./cache/nltk_data', quiet=True) +nltk.download('wordnet', download_dir='./cache/nltk_data', quiet=True) +nltk.data.path.append('./cache/nltk_data/') + +# Helper +import pa_print +from pa_extract import clean_text +from pa_utils import import_config, boolify +from pa_load import load_bibtex, extract_bibtex +from tqdm import tqdm + +# Variables +lda = LdaMulticore +grobid_text_src = './cache/text/grobid/' +lda_src = './cache/lda/' + +def gen_model(remodel=True, rebuild=True, model='', num_topics=5, user_config=None): + # * Load model + if path.isfile(lda_src+model) and not (remodel or rebuild): + pa_print.nprint('\nLoading bodies, dict, corpus, and model...') + processed_bodies = pickle.load(open(f'{lda_src}bodies.pkl', 'rb')) + dictionary = gensim.corpora.Dictionary.load(f'{lda_src}dictionary.gensim') + corpus = pickle.load(open(f'{lda_src}corpus.pkl', 'rb')) + lda_model = lda.load(f'{lda_src}{model}') + + else: # Build model afterwards + # Load resources + if path.isfile(f'{lda_src}dictionary.gensim') and path.isfile(f'{lda_src}corpus.pkl') and not rebuild: + pa_print.nprint('\nLoading bodies, dict and corpus...') + processed_bodies = pickle.load(open(f'{lda_src}bodies.pkl', 'rb')) + dictionary = gensim.corpora.Dictionary.load(f'{lda_src}dictionary.gensim') + corpus = pickle.load(open(f'{lda_src}corpus.pkl', 'rb')) + else: + # Remove old + for doc in [f'{lda_src}bodies.pkl', f'{lda_src}dictionary.gensim', f'{lda_src}corpus.pkl']: + try: os.remove(doc) + except FileNotFoundError: pass + + # Build everything from text files + pa_print.nprint('Building dict and corpus...') + doc_list = [] + processed_bodies = [] + + for text_fn in os.listdir(grobid_text_src): + if text_fn.startswith('grob_'): + with open(grobid_text_src+text_fn, 'r') as doc: + doc_list.append(doc.read()) + + for doc in doc_list: + processed_words = clean_text(doc, user_config) # extract only meaningful words, user config! + processed_bodies.append(processed_words) + + # Save processed bodies for coherence score + pickle.dump(processed_bodies, open(f'{lda_src}bodies.pkl', 'wb')) + + # Make and save dict and corpus + dictionary = corpora.Dictionary(processed_bodies) + dictionary.filter_extremes(no_below=3) # remove those with counts fewer than 3 + dictionary.save(f'{lda_src}dictionary.gensim') + + corpus = [dictionary.doc2bow(doc) for doc in processed_bodies] + pickle.dump(corpus, open(f'{lda_src}corpus.pkl', 'wb')) + + # Build LDA model - default settings + if remodel or rebuild or not path.isfile(f'{lda_src}{model}'): + pa_print.nprint('Building model...') + alpha ='asymmetric' + eta = 0.5 + lda_model = lda(corpus, num_topics=num_topics, id2word=dictionary, + random_state=100, passes=10, alpha=alpha, eta=eta, per_word_topics=True) + date = datetime.now().strftime('%Y%m%d') + lda_model.save(f'{lda_src}{date}-{num_topics}-{alpha}-{eta}.model') + pa_print.nprint('Saved model!') + else: lda_model = lda.load(f'{lda_src}{model}') + + return processed_bodies, dictionary, corpus, lda_model + +def gen_titles(user_config): + bib_db = load_bibtex('./cache/bibtex/nime_papers.bib') + bib_db = extract_bibtex(bib_db, args) + processed_titles = [] + + for pub in bib_db: + title = clean_text(pub['title'], user_config) + processed_titles.append(title) + + return processed_titles + +def gen_lda(lda_model, corpus, processed_bodies, dictionary): + # Compute Perplexity + pa_print.nprint(f'Perplexity: {lda_model.log_perplexity(corpus)}') # a measure of how good the model is, lower the better + + # Compute Coherence Score + coherence_model_lda = CoherenceModel(model=lda_model, texts=processed_bodies, dictionary=dictionary, coherence='c_v') + coherence_lda = coherence_model_lda.get_coherence() + pa_print.nprint(f'Coherence Score: {coherence_lda}') + + # Show some visualization of the topics that gathered + lda_display = pyLDAvis.gensim_models.prepare(lda_model, corpus, dictionary) + pyLDAvis.save_html(lda_display, './output/lda.html') + pa_print.nprint('Generated lda.html in ./output!') + +def gen_wordcloud(processed_data): + from wordcloud import WordCloud + + for data in processed_data: + words = [word for doc in data[1] for word in doc] + counter = dict(collections.Counter(words)) + wc = WordCloud(width=1920, height=1444, + background_color="white", max_words=500 + ).generate_from_frequencies(counter) + plt.imshow(wc, interpolation='bilinear') + plt.axis("off") + plt.savefig(f'./output/wordcloud_{data[0]}.png', dpi=300) + pa_print.nprint('Generated .png files in ./output!') + +def gen_topic_plots(corpus, lda_model, year_dict, year_list, year_start, year_end): + year_counts = np.zeros(year_end-year_start) + + # Add topic distribution from each doc into buckets of years + for i in range(len(corpus)): + topics = lda_model.get_document_topics(corpus[i]) + for j in range(year_start, year_end): + if year_list[i][0] == j: + year_counts[j-year_start] += 1 # how many bodies in each year + for k, year_top in enumerate(year_dict[j]): + for top in topics: + if str(year_top[0]) == str(top[0]): + year_top = list(year_top) + year_top[1] = float(year_top[1]) + float(top[1]) + year_dict[j][k] = tuple(year_top) + + # Weight the topic values by numbers of papers submitted each year + for key, val in year_dict.items(): + for index, j in enumerate(val): + j = list(j) + j[1] = float(j[1]) / year_counts[index] + year_dict[key][index] = tuple(j) + + # Create empty dict of lists for year range (n topics each year) + xvals = [ [] for _ in range(num_topics) ] + yvals = [ [] for _ in range(num_topics) ] + plt.figure(figsize=(20,10)) + + for year, topics in year_dict.items(): + for topic in topics: + xvals[topic[0]].append(int(year)) + yvals[topic[0]].append(topic[1]) + + for i in range(num_topics): + plt.scatter(xvals[i], yvals[i], label=f'Topic {i}') + s = UnivariateSpline(xvals[i], yvals[i], s=.1) + xs = np.linspace(year_start, year_end, 50) + ys = s(xs) + plt.plot(xs, ys, label=f'Spline for topic {i}') + + plt.legend() + plt.ylim(bottom=0) + plt.xticks(range(year_start, year_end)) + plt.xlabel('Year') + plt.ylabel('Occurrence of Topic over Yearly Papers)') + plt.title('Occurrence of Topics over Publication Year') + plt.savefig('./output/topic_occurrence.png') + + pa_print.nprint('Generated diagram .png in ./output!') + +def gen_counts(processed_data, year_list): + top_counts_dfs = {} + alt_top_counts_dfs = {} + unique_dfs = {} + abs_unique_dfs = {} + + for data in processed_data: + # * Most popular keywords for each year (100) + yearly_bodies, top_counts = {}, {} + + for year, doc in zip(year_list, data[1]): + year = year[0] + try: + yearly_bodies[year].extend(doc) # accum all words from each year's papers + except: + yearly_bodies[year] = [] + yearly_bodies[year].extend(doc) + + for year in yearly_bodies: + counts = collections.Counter(yearly_bodies[year]) + top_counts[year] = counts.most_common(100) # take most common + + top_counts = collections.OrderedDict(sorted(top_counts.items())) + + # Two columns [year, ('term', count)] - for Google Sheets + top_counts_df = pd.DataFrame([[i,j] for i in top_counts.keys() for j in dict(top_counts[i]).items()]) + top_counts_dfs[data[0]] = top_counts_df + + # Columns by years (20 columns) + alt_top_counts_df = pd.DataFrame.from_dict(top_counts, orient='index') + alt_top_counts_dfs[data[0]] = alt_top_counts_df + + # * Get unique counts by removing last years top 10 (looking backwards) + unique_counts = {} + old_top, old_years = [], [] + + for i, year in enumerate(top_counts): + cur_counts = dict(top_counts[year]) # keep a dict for counts + # cur_words = list(cur_counts) # unpack keys into list + + # new dict, without past year + old_years.append(year) + + # remove words from prior years + for key in old_top: + cur_counts.pop(key, None) + + unique_words = list(dict(cur_counts))[:5] # make list of top 5 words + old_top.extend(unique_words) # add old top to del words + + unique_counts[year] = cur_counts.items() # reassign + # pa_print.nprint(unique_words) + + unique_df = pd.DataFrame.from_dict(unique_counts, orient='index') + unique_dfs[data[0]] = unique_df + + # * Get absolute unique terms per year (not in the top common words of all other years) + # Similar process to above but looks both forward and backward + abs_unique_counts = {} + + for i, year in enumerate(top_counts): + cur_counts = dict(top_counts[year]) # keep a dict for counts + cur_words = list(cur_counts) # unpack keys into list (for a set) + + # new dict, without current year + later_counts = {x: top_counts[x] for x in top_counts if x != year} + + other_words = [] + for later_year in later_counts: + later_words = list(dict(later_counts[later_year])) + other_words.extend(later_words) # extend + + unique_words = set(cur_words) - set(other_words) + del_words = set(cur_words) - set(unique_words) + + for key in del_words: # del words included other years common words + cur_counts.pop(key) + abs_unique_counts[year] = list(cur_counts.items()) + + abs_unique_df = pd.DataFrame.from_dict(abs_unique_counts, orient='index') + abs_unique_dfs[data[0]] = abs_unique_df + + with pd.ExcelWriter('./output/topics.xlsx') as writer: + for name in ['bodies', 'titles']: + top_counts_dfs[name].to_excel(writer, sheet_name=f'Top counts {name}', header=False) + alt_top_counts_dfs[name].to_excel(writer, sheet_name=f'Alt top counts {name}', header=False) + unique_dfs[name].to_excel(writer, sheet_name=f'Unique counts {name}', header=False) + abs_unique_dfs[name].to_excel(writer, sheet_name=f'Absolute unique counts {name}', header=False) + + topic_row = pd.Series(data=lda_model.show_topics(num_words=10), name='Word constituents of topics') + topics_df = pd.DataFrame.from_dict(year_dict, orient='index') + topics_df = topics_df.append(topic_row, ignore_index=False) + topics_df.to_excel(writer, sheet_name='Weighted topics') + + pa_print.nprint('\nGenerated topics.xlsx in ./output!') + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Analyse a publication given a BibTeX and directory of pdf documents') + parser.add_argument('-n', '--nime', action='store_true', default=False, + help='uses NIME based corrections') + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='prints out analysis process and results') + args = parser.parse_args() + + # Sets global print command + pa_print.init(args) + + # Print notice + pa_print.lprint() + + # User config + user_config = import_config('./resources/custom.csv') + selected_years = user_config[3] + if len(selected_years) != 0: # years + int_years = list(map(int,selected_years)) + year_start, year_end = min(int_years), max(int_years)+1 + else: + year_start, year_end = 2001, 2021 + + # Make sure dirs exist + for d in [lda_src,'./output']: + os.makedirs(d, exist_ok=True) + + # Question for load dict, corpus, model for docs + remodel, rebuild = True, True + model = '' + answer = int(input('\nWant to [1] remodel, [2] rebuild dictionary and corpus, [3] both, or [4] load model? (1,2,3,4): ')) + if answer == 1: + rebuild = False + num_topics = int(input('Number of topics?: ')) + elif answer == 2: + remodel = False + elif answer == 3: + num_topics = int(input('Number of topics?: ')) + elif answer == 4: + rebuild, remodel = False, False + pa_print.nprint('\nWhich model?') + models = [mod for mod in os.listdir(lda_src) if mod.endswith('.model')] + for i, mod in enumerate(models): + print(f'{i+1}: {mod}') + answer = int(input('\nSelect an option: ')) - 1 + model = models[answer] + num_topics = int(model.split('-')[1]) + + # Create list to mark each text with year (will be linked to corpus values) + year_list = [] + for i in os.listdir(grobid_text_src): + if i.startswith('grob_'): + name = i.split('grob_nime')[-1] + year = name.split('_')[0] + year_list.append((int(year), name)) + + # Create empty dict of lists for years (n topics each year) + year_dict = dict() + for i in range(year_start, year_end): + year_dict[i] = [] + for j in range (0, num_topics): + year_dict[i].append((j, 0)) + + processed_bodies, dictionary, corpus, lda_model = gen_model(remodel, rebuild, model, num_topics, user_config) + + # Use titles for processed words + processed_titles = gen_titles(user_config) + + processed_data = [('bodies', processed_bodies), ('titles', processed_titles)] + + # * LDA + answer = boolify(input('\nGenerate LDA scores & visualizations? (Y/N): ')) + if answer: + gen_lda(lda_model, corpus, processed_bodies, dictionary) + + # * Wordcloud + answer = boolify(input('\nGenerate wordcloud diagrams? (Y/N): ')) + if answer: + gen_wordcloud(processed_data) + + # * Plot topics + answer = boolify(input('\nGenerate topic plots? (Y/N): ')) + if answer: + gen_topic_plots(corpus, lda_model, year_dict, year_list, year_start, year_end) + + # * Counts + answer = boolify(input('\nGenerate top and unique counts? (Y/N): ')) + if answer: + gen_counts(processed_data, year_list) diff --git a/pa.py b/pa.py new file mode 100755 index 0000000..1025203 --- /dev/null +++ b/pa.py @@ -0,0 +1,123 @@ +# NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import sys +if sys.version_info < (3, 7): + print("Please upgrade Python to version 3.7.0 or higher") + sys.exit() +import io +import os +from os import path +import random +import argparse +import requests + +# External +from tqdm import tqdm +import orjson + +# Helper +import pa_print +from pa_utils import csv_save, calculate_carbon, fill_empty, doc_quality, post_processing, boolify +from pa_request import request_location, request_scholar, request_uni +from pa_extract import extract_text, extract_author_info, extract_grobid +from pa_load import prep, load_unidomains, load_bibtex, extract_bibtex, check_grobid + + +# Variables/paths +bibtex_path = os.getcwd()+'/cache/bibtex/nime_papers.bib' +unidomains_path = os.getcwd()+'/cache/json/unidomains.json' + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='Analyse a publication given a BibTeX and directory of pdf documents') + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='prints out operations') + parser.add_argument('-c', '--citations', action='store_true', default=False, + help='bypass cache to retrieve new citations') + parser.add_argument('-g', '--grobid', action='store_true', default=False, + help='forces repopulation of Grobid files') + parser.add_argument('-r', '--redo', action='store_true', default=False, + help='deletes cache') + parser.add_argument('-n', '--nime', action='store_true', default=False, + help='uses NIME based corrections') + + args = parser.parse_args() + + # * Prepare cache, etc. + prep(args) + + # * Set global print command + pa_print.init(args) + + # Print notice + pa_print.lprint() + + # * Load database for email handle to uni matching + unidomains = load_unidomains(unidomains_path) + + # * Load and extract BibTeX + bib_db = load_bibtex(bibtex_path) + bib_db = extract_bibtex(bib_db, args) + + # * Loop here for Grobid/PDF population + if args.grobid: + check_grobid(bib_db, True) + + # * Parse data through pdfs + print('\nExtracting and parsing publication data...') + iterator = tqdm(bib_db) + for _, pub in enumerate(iterator): + pa_print.tprint(f"\n--- Now on: {pub['title']} ---") + + # Extract text from pdf, regardless + doc = extract_text(pub) + errored = doc_quality(doc, pub, 'text') # check for errors + + # Only extract header meta-data if not errored + if not errored: + author_info = extract_author_info(doc, pub) + else: + author_info = [] + + # Extract doc from Grobid + doc = extract_grobid(pub, bib_db, iterator) + doc_quality(doc, pub, 'grobid') + + # Get university from various sources + request_uni(unidomains, author_info, args, pub) + + # Get location from API and query + request_location(author_info, args, pub) + + # Use location for footprint calculation + calculate_carbon(pub) + + # Get citations from Semantic Scholar + request_scholar(pub, args) + + # Post processing modifications + post_processing(pub) + + # Save for every paper + csv_save(bib_db) \ No newline at end of file diff --git a/pa_extract.py b/pa_extract.py new file mode 100644 index 0000000..12d4698 --- /dev/null +++ b/pa_extract.py @@ -0,0 +1,475 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import os +import io +import re +import requests +from collections import Counter +from unidecode import unidecode +import warnings +import datetime + +# External +from pdfminer.pdfparser import PDFParser +from pdfminer.pdfdocument import PDFDocument +from pdfminer.high_level import extract_text as extract_pdf +from pdfminer.pdfinterp import resolve1 +from pdfminer.layout import LAParams + +import fasttext +fasttext.FastText.eprint = lambda x: None # do not display warning message +import gender_guesser.detector as gender # https://github.com/lead-ratings/gender-guesser +import onomancer as ono # https://github.com/parthmaul/onomancer + +import nltk +#from nltk.corpus import stopwords +from nltk.stem import WordNetLemmatizer +from nltk.stem.porter import PorterStemmer +from nltk.tokenize import sent_tokenize, word_tokenize + +from gensim.parsing.preprocessing import STOPWORDS + +from lxml import etree +from bs4 import BeautifulSoup +from tqdm import tqdm +import orjson + +# Helper +import pa_print +from pa_load import check_grobid + +# Variables +pdf_src = os.getcwd()+'/cache/pdf/' +xml_src = os.getcwd()+'/cache/xml/' +text_src = os.getcwd()+'/cache/text/' +gg = gender.Detector() + +# Compile regular expressions +auth_regex = re.compile(r'(?:^[A-Z |].+$)(?:\s^[\S |].+$)*\s(?:.+@[a-zA-Z0-9-–]+\.[a-zA-Z0-9-–.]+)', re.M) +abst_regex = re.compile(r'^\s*(?:Abstract|ABSTRACT)\s*$', re.M) +intro_regex = re.compile(r'^[0-9]?.?\s*(?:Introduction|INTRODUCTION).*$', re.M) +ackn_regex = re.compile(r'^[0-9]?.?\s*(?:Acknowledg[e]?ment[s]?|ACKNOWLEDG[E]?MENT[S]?)\s*$', re.M) +ref_regex = re.compile(r'^[0-9]?.?\s*(?:References|REFERENCES)\s*$', re.M) +regex_list = (abst_regex, intro_regex, ackn_regex, ref_regex) + +def extract_bib(pub, args): + ''' Extracts and expands data found in bibtex entry + + :publication (article) from database + ''' + # Basic info from authors + authors = pub['author'].split(' and ') + author_count = len(authors) + pub['author count'] = author_count + + bad_names = ['professor', 'dr.'] # names to remove + allowed_names = ['d\'', 'di', 'da', 'de', 'do', 'du', 'des', 'af', 'von', 'van', 'los', 'mc', 'of', 'zu'] + regexname = re.compile(r'[^a-zA-Z- ]') + + for _, author in enumerate(authors): # break up names + first = unidecode(author.split(', ', 1)[-1] if ', ' in author else author.split(' ', 1)[0]) + last = unidecode(author.split(', ', 1)[0] if ', ' in author else author.split(' ', 1)[-1]) + + # First name + first = [part for part in first.split(' ') \ + if not ((len(part) > 2 and '.' in part) \ + or part.lower() in bad_names)] # remove names with length > 2 followed by full stop, and bad names + if not first: + first = '' # if list is empty + else: + first = first[0] # only one first name + + first = regexname.sub('', first) + + # Last name + if last[:2].lower() != 'd\'': + last = [part for part in last.split(' ') if not part.lower() in bad_names] + if str.lower(last[0]) in allowed_names: + last = ' '.join(last) + elif ('.' in last[-1]) or (len(last[-1])==1): # if initial, remove + last = last[0] + else: + last = last[-1] + + last = regexname.sub('', last) + + # Capitalize + # check for length, exclude if first letter cap, but not whole word cap + if len(first) > 0: + if not first[0].isupper() or first.isupper(): + first = first.title() + if len(last) > 0: + if not last[0].isupper() or last.isupper(): + last = last.title() + + if args.nime: + # Unique names + if (first == 'Woon' and last == 'Seung Yeo') or (first == 'Woon' and last == 'Yeo'): + first = 'Woonseung' + last = 'Yeo' + elif (first == 'R' and last == 'Knapp'): + first = 'Benjamin' + last = 'Knapp' + elif (first == 'Joe' and last == 'Paradiso'): + first = 'Joseph' + last = 'Paradiso' + elif (first == 'Martin' and last == 'Naef'): + last = 'Naf' + elif (first == 'Cornelius' and last == 'Poepel'): + last = 'Popel' + elif (first == 'Misra' and last == 'Ananya'): + last = 'Misra' + + pub['author names'].append((first, last)) + + # Guess gender by first name + gender_1 = gg.get_gender(first) + gender_2 = next(iter(ono.predict(first).values())) + + if args.nime: + # Manual amend gender for NIME authors with gender 2 = N + if (first == 'Tone' and last == 'Ase') or \ + (first == 'Ye' and last == 'Pan') or \ + (first == 'Rumi' and last == 'Hiraga') or \ + (first == 'Quinn' and last == 'Holland') or \ + (first == 'Eri' and last == 'Kitamura'): + gender_1 = 'female' + gender_2 = 'F' + + if (first == 'Woonseung' and last == 'Yeo') or \ + (first == 'Yu' and last == 'Nishibori') or \ + (first == 'Jimin' and last == 'Jeon') or \ + (first == 'Leshao' and last == 'Zhang') or \ + (first == 'Michal' and last == 'Seta') or \ + (first == 'Joung' and last == 'Han') or \ + (first == 'Kuljit' and last == 'Bhamra'): + gender_1 = 'male' + gender_2 = 'M' + + pub['author genders'].append(gender_1) # gender_guesser (m, mostly_m, andy, mostly_f, f, unknown) + pub['author genders 2'].append(gender_2) # onomancer (m, f) + + # Page count + page_count = pub.get('pages') + try: + page_count = page_count.split('--') + page_count = int(page_count[1]) - int(page_count[0]) + 1 + pub['page count'] = int(page_count) + except: + pub['page count'] = 'N/A' + + # Check if in NIME Reader + with open('./resources/nime_reader.txt','r') as f: + nime_reader = f.readlines() + nime_reader = [line.strip() for line in nime_reader] + pub['NIME reader'] = 'No' + for i in nime_reader: + if i == pub['title']: + pub['NIME reader'] = 'Yes' + + # Age of papers + pub['age'] = datetime.datetime.now().year - int(pub['year']) + +def download_pdf(pdf_path, pub): + pa_print.tprint('\nLocal PDF not found - downloading...') + r = requests.get(pub['url'], allow_redirects=True) + open(pdf_path, 'wb').write(r.content) + +def extract_text(pub): + '''Extracts text content from pdf using pdfminer.six, downloads pdf if non-existant + + :publication (article) from database + ''' + pdf_name = pub['url'].split('/')[-1] + pdf_path = pdf_src + pdf_name + + # Allows for override of corrupted pdfs + if os.path.isfile(pdf_path): + pass + else: # doesnt exist - download + download_pdf(pdf_path, pub) + + file_name = pdf_name.split('.')[0] + miner_text_file = f'{text_src}miner/miner_{file_name}.txt' + + # Page count for those without + if pub['page count'] == 'N/A': + pdf = open(pdf_path, 'rb') + parser = PDFParser(pdf) + document = PDFDocument(parser) + pub['page count'] = resolve1(document.catalog['Pages'])['Count'] + + # Read miner text if exists + if os.path.isfile(miner_text_file): + with open(miner_text_file, 'r') as f: + doc = f.read() + return doc + + else: # if not, make them + pa_print.tprint(f'\n Extracting: {pdf_name}') + + laparams = LAParams() + setattr(laparams, 'all_texts', True) + doc = extract_pdf(pdf_path, laparams=laparams) + + with open(miner_text_file, 'w') as f: + f.write(doc) + + return doc + +def extract_grobid(pub, bib_db, iterator): + '''Parse xml files output from Grobid service (3rd party utility needed to generate files) + + :publication (article) from database + ''' + def elem_text(elem, fill='N/A'): # to get element text w/o error + if elem: + return elem.getText(separator=' ', strip=True) + else: + return fill + + file_name = pub['url'].split('/')[-1].split('.')[0] + xml_name = file_name + '.tei.xml' + xml_path = xml_src + xml_name + + if os.path.exists(xml_path): + with open(xml_path, 'r') as tei: + soup = BeautifulSoup(tei, 'lxml') + + if soup.analytic is None: + pa_print.tprint(f'\n{xml_name} is empty!') + return + + pa_print.tprint(f'\nParsing through grobid XML of {xml_name}') + + grob_names, grob_emails, grob_orgs, grob_addrs = [], [], [], [] + + # Begin with parsing author info + authors = soup.analytic.find_all('author') + + for author in authors: + persname = author.persname + if persname: + firstname = elem_text(persname.find("forename", type="first"), '') + middlename = elem_text(persname.find("forename", type="middle"), '') + surname = elem_text(persname.surname, '') # *** should this be find? *** + name = (firstname, middlename, surname) + grob_names.append(name) + + grob_emails.append(elem_text(author.email)) + + # There's an issue where affils can be within an alongside an author or independently + # authors = [author for author in authors if not author.affiliation] + affils = [author for author in authors if author.affiliation] + for affil in affils: + grob_orgs.append(elem_text(affil.orgname)) + grob_addrs.append(elem_text(affil.address)) + + grob_info = [grob_names, grob_emails, grob_orgs, grob_addrs] + + # Fill in missing data with 'N/A' + author_count = pub['author count'] + for author in range(author_count): + for info in grob_info: + try: info[author] + except IndexError: info.append('N/A') + + # Add info to df - merge everything! + pub['grobid author names'].extend(grob_names) # to check who appeared in grobid info + pub['grobid emails'].extend(grob_emails) + pub['grobid organisations'].extend(grob_orgs) + pub['grobid addresses'].extend(grob_addrs) + + # Extract meaningful text using grobid tags (within p tags) and save to txt + grob_text_file = f'{text_src}grobid/grob_{file_name}.txt' + if os.path.isfile(grob_text_file): # check if txt already exists + with open(grob_text_file, 'r') as f: + grob_text = f.read() + else: + grob_text = [] + grob_body = soup.body.find_all('p') + for p in grob_body: + grob_text.append(elem_text(p)) + grob_text = str(grob_text) + with open(grob_text_file, 'w') as f: + f.write(grob_text) + + return grob_text + + else: # No XML - populate + pa_print.tprint('\nGrobid file does not exist for paper!') + iterator.clear() + check_grobid(bib_db) + iterator.refresh() + +def extract_author_info(doc, pub): + ''' Searches through pdf text for author block using regex (no Grobid needed) + + :document from text extraction (miner) or xml extraction (grobid) + :publication (article) from database + ''' + pa_print.tprint('\nExtracting authors from paper...') + + author_info = [] + author_count = pub['author count'] + + # * Method 1 - Look for block with email tail (bibtex not needed, more robust) + author_info = auth_regex.findall(doc)[:author_count] # grab only up to total authors + + if len(author_info) != 0: + pa_print.tprint(f'✓ - Found by block') + + # * Method 2 - Look for block starting with author name (bibtex needed) + else: + for author in range(author_count): # only look up to i authors + author_first = pub['author names'][author][0] + author_last = pub['author names'][author][1] + pa_print.tprint(f'\nLooking for: {author_first} {author_last}') + + author_first = author_first.replace('\\', '') # fixes issues with regex + author_last = author_last.replace('\\', '') + + name_regex = r'(?:^.*'+author_first+r'.+'+author_last+r'.*$)(?:\s^[\S |].+$)*' + author_search = re.search(name_regex, doc, re.M) + try: + author_info.append(author_search.group(0)) + pa_print.tprint('✓ - Found by name') + except: + pa_print.tprint('x - No match by name') + + pa_print.tprint(f'\n✓ - Found {len(author_info)} author(s) in paper of {author_count} total') + + # If there were a different number of authors from text block + if len(author_info) < author_count: + pub['author block mismatch'] = 'Too few' + elif len(author_info) > author_count: + pub['author block mismatch'] = 'Too many' + + # Add 'N/A' for missing authors # ! Note: Author block will not correspond in order to authors + authors_missed = author_count - len(author_info) + pub['author block missed'] = authors_missed + for author in range(authors_missed): + author_info.append('N/A') + + # Add for visibility with csv - # ! but may not be the best idea if processing afterwards + pub['author infos'] = '\n\n'.join(author_info) + + return author_info + +def trim_headfoot(doc, pub=None): + ''' Trim the header and footer from extracted text (unused and inferior to Grobid service) + + :document from text extraction (miner) or xml extraction (grobid) + ''' + # Function for trimming header and footer + # Remove until abstract or introduction + pdf_trimmed = abst_regex.split(doc, 1) + if len(pdf_trimmed) == 1: + pdf_trimmed = intro_regex.split(pdf_trimmed[0], 1) # if no abstract, use 'introduction' + if len(pdf_trimmed) == 1: + pdf_trimmed = pdf_trimmed[0] + if pub is not None: pub['header fail'] = 'X' + pa_print.tprint('Could not split header during parsing!') + else: + pdf_trimmed = pdf_trimmed[1] + # pa_print.tprint('Split header at intro') + else: + pdf_trimmed = pdf_trimmed[1] + # pa_print.tprint('Split header at abstract') + # return pdf_trimmed + + # Remove after references or acknowledgements + pdf_slimmed = ackn_regex.split(pdf_trimmed, 1) + if len(pdf_slimmed) == 1: + pdf_slimmed = ref_regex.split(pdf_slimmed[0], 1) + if len(pdf_slimmed) == 1: + if pub is not None: pub['footer fail'] = 'X' + pa_print.tprint('Could not split footer during parsing!') + else: + pdf_slimmed = pdf_slimmed[0] + # pa_print.tprint('Split footer at references') + else: + pdf_slimmed = pdf_slimmed[0] + # pa_print.tprint('Split footer at acknowledgements') + + return pdf_slimmed + +def clean_text(doc, user_config=None, miner=False): + '''Pre-process essential text into word counts (or other models). + Optional inputs for use in modelling. + + :document from text extraction (miner) or xml extraction (grobid) + ''' + # print('\nCleaning text...') + + if user_config is not None: + keywords = user_config[0] + ignore_words = user_config[1] + merge_words = user_config[2] + # selected_years = user_config[3] + + if miner is True: # no need to trim with grobid text + doc_trimmed = trim_headfoot(doc) + + else: + doc_trimmed = doc + + # Check for decoding errors (does not catch all) # ! REPLACE WITH QUALITY_CHECK + pre_cid = len(doc_trimmed) + doc_trimmed = re.sub(r'\(cid:[0-9]+\)','', doc_trimmed, re.M) # when font cannot be decoded, (cid:#) is returned, remove these + post_cid = len(doc_trimmed) + if pre_cid > 5*post_cid: # if most of content was undecodable, skip + print("File cannot be decoded well, skipping!") + return + + # Normalize text and tokenize + doc_processed = doc_trimmed.lower() # lowercase + doc_processed = re.sub(r'(?:[^a-zA-Z]+)|(?:\s+)', ' ', doc_processed) # remove non-alpha and line breaks + words = word_tokenize(doc_processed) # tokenize + words = [word for word in words if word.isalpha() and len(word) > 3] # alpha only and over 3 chars + stop_words = STOPWORDS + + # porter = PorterStemmer() + # processed_words = [porter.stem(word) for word in words] # stem words + + lemmatizer = WordNetLemmatizer() # lemmatizing for semantic relevance + words = [lemmatizer.lemmatize(word) for word in words] # lemmatize words + + if user_config is not None: + try: # Remove ignore words from all words + stop_words = stop_words.union(set(ignore_words)) # custom.csv + except NameError: + pass + try: # Change words that should be merged to first cell in merge group + for merge_group in merge_words: + for i, w in enumerate(words): + if w in merge_group[1:]: + words[i] = merge_group[0] + except NameError: + pass + + processed_words = [w for w in words if not w in stop_words] # prune stop words + + return processed_words diff --git a/pa_load.py b/pa_load.py new file mode 100644 index 0000000..e9c69da --- /dev/null +++ b/pa_load.py @@ -0,0 +1,221 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import os +import requests +from collections import defaultdict +import zipfile +import urllib +import subprocess +import time +import socket +import signal +import shutil + +# External +from tqdm import tqdm +import orjson +import bibtexparser +import oschmod +from grobid_client.grobid_client import GrobidClient + +# Helper +import pa_print +import pa_extract +from pa_utils import doc_check, fill_empty, boolify + +# Variables +bibtex_url = 'https://raw.githubusercontent.com/NIME-conference/NIME-bibliography/master/paper_proceedings/nime_papers.bib' +unidomains_url = 'https://raw.githubusercontent.com/Hipo/university-domains-list/master/world_universities_and_domains.json' +unused_cols = ['ID', 'ENTRYTYPE', 'doi', 'annote', 'booktitle', 'editor', 'date', 'date-modified', + 'editor', 'isbn', 'issn', 'month', 'publisher', 'rating', 'series', 'track', 'pages', + 'presentation-video', 'urlsuppl1', 'urlsuppl2', 'urlsuppl3', 'volume'] +pdf_src = os.getcwd()+'/cache/pdf/' +xml_src = os.getcwd()+'/cache/xml/' + +def prep(args): + # Delete cache + if args.redo: + answer = boolify(input('Do you want to delete PDFs as well? (Y/N): ')) + if answer: + shutil.rmtree('./cache') + else: + for p in ['text','xml','bibtex','json']: + shutil.rmtree(f'./cache/{p}') + + # Generate cache folders + for folder in [ './cache/pdf/', './cache/xml/', + './cache/text/grobid/', './cache/text/miner/', + './cache/bibtex/', './cache/json/', + './output/', './resources/corrected/']: + os.makedirs(os.path.dirname(f'{folder}'), exist_ok=True) + + # Copy corrected into pdf + for f in [f for f in os.listdir('./resources/corrected') if f.endswith('.pdf')]: + shutil.copy(os.path.join('./resources/corrected',f),'./cache/pdf') + + # Config load + if not os.path.exists('./resources/config.json'): + with open('./resources/config.json', 'w') as fp: + config ='''{"grobid_server":"localhost","grobid_port":"8070", + "batch_size":1000,"sleep_time":5,"coordinates":["persName", + "figure","ref","biblStruct","formula"]} + ''' + fp.write(config) + + # Restart log + if os.path.isfile('./lastrun.log'): + os.remove('./lastrun.log') + +def load_unidomains(path): + ''' Loads unidomain file from json or downloads if not found + + :path of unisomains.json file + ''' + if not os.path.isfile(path): # if not, download + pa_print.tprint('\nDownloading unidomains database...') + r = requests.get(unidomains_url, allow_redirects=True) + open(path, 'wb').write(r.content) + + with open(path,'rb') as fp: + unidomains = orjson.loads(fp.read()) + + return unidomains + +def load_bibtex(path): + ''' Loads BibTeX file into object or downloads if not found + + :path of BibTeX file + ''' + if not os.path.isfile(path): # if not, download + pa_print.tprint('\nDownloading bibtex database...') + r = requests.get(bibtex_url, allow_redirects=True) + open(path, 'wb').write(r.content) + + with open(path) as bib_file: + parser = bibtexparser.bparser.BibTexParser() + parser.customization = bibtexparser.customization.convert_to_unicode + bib_db = bibtexparser.load(bib_file, parser=parser) + bib_db = bib_db.entries + + return bib_db + +def extract_bibtex(bib_db, args): + print('\nExtracting BibTeX...') + for index, pub in enumerate(tqdm(bib_db)): + pub = defaultdict(lambda: [], pub) # ? needed? + pa_extract.extract_bib(pub, args) + + for col in unused_cols: + if col in pub: + del pub[col] + + bib_db[index] = pub # reinsert trimmed pub + return bib_db + +def check_grobid(bib_db, overwrite=False): + ''' Repopulate Grobid files, downloads PDFs if needed + + :bib_db from bibtex file +''' + # Check for pdfs + print('Checking PDFs and converting to XML!') + xmls = os.listdir(xml_src) + pdfs = os.listdir(pdf_src) + bad_xmls = [] + + for _, pub in enumerate(bib_db): + pdf_name = pub['url'].split('/')[-1] + xml = pdf_name.split('.')[0]+'.tei.xml' + + # Check if PDF exists - download PDFs if necessary + if not (pdf_name in pdfs): # this assumes override PDFs will have same name + print(f'Downloading {pdf_name}...') + try: + r = requests.get(pub['url'], allow_redirects=True) + except: + url = pub['url'] + title = pub['title'] + print(f'Failed to download from {url} the paper: {title}') + print('Run the script again to attempt re-downloading the file.') + print(f'If the problem persist, download the file manually and save it in resources/corrected as {pdf_name}') + quit() + + open(pdf_src + pdf_name, 'wb').write(r.content) + + # Check if XML exists + if xml not in xmls: + bad_xmls.append(xml) + + if len(bad_xmls) > 0: + print(f'Found {len(bad_xmls)} PDFs unconverted - converting!') + generate_grobid(overwrite) + else: + answer = boolify(input(f'All XMLs exist - convert anyway? (Y/N): ')) + if answer: + generate_grobid(True) + +def generate_grobid(overwrite=False): + ''' Convert a pdf to a .tei.xml file via Grobid + + ''' + base = 'https://github.com/kermitt2/grobid/' + version = requests.get(base+'releases/latest').url.split('/')[-1] # get latest Grobid release + + if not os.path.exists(f'./cache/grobid-{version}'): + print('\nInstalling Grobid!') + try: + print('Downloading and extracting...') + zip_path, _ = urllib.request.urlretrieve(f'{base}archive/refs/tags/{version}.zip') + with zipfile.ZipFile(zip_path, 'r') as f: + f.extractall('./cache') + + print('Installing...') + oschmod.set_mode(f'./cache/grobid-{version}/gradlew', '+x') + subprocess.run(f'cd ./cache/grobid-{version} ' + '&& ./gradlew clean install', shell=True) + + for root, _, files in os.walk(f'./cache/grobid-{version}/grobid-home/pdf2xml'): + for f in files: + oschmod.set_mode(os.path.join(root, f), '+x') + + except Exception as e: + print(e) + print('\nFailed to install Grobid!') + + print('\nConverting PDFs to XMLs via Grobid - this may take some time...') + + # Kill untracked server if exists + subprocess.run(['./gradlew', '--stop'], cwd=f'./cache/grobid-{version}') + + p = subprocess.Popen(['./gradlew', 'run'], cwd=f'./cache/grobid-{version}', stdout=subprocess.DEVNULL) + for _ in tqdm(range(20), desc='Initiating Grobid server'): + time.sleep(1) # wait for Grodid to run, might need to be longer + client = GrobidClient(config_path='./resources/config.json') + + if overwrite: + shutil.rmtree('./cache/xml') + + client.process('processFulltextDocument', pdf_src, output=xml_src, force=overwrite) + p.terminate() diff --git a/pa_print.py b/pa_print.py new file mode 100644 index 0000000..b7f3ef7 --- /dev/null +++ b/pa_print.py @@ -0,0 +1,59 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +from tqdm import tqdm +import logging + +notice = '\nNIME Proceedings Analyzer\n\ +Copyright (C) 2021 Jackson Goode, Stefano Fasciani\n\ +This program comes with ABSOLUTELY NO WARRANTY;\n\ +This is free software, and you are welcome to redistribute it\n\ +under certain conditions; for details check the LICENSE file.\n' + +# Allows a verbose toggle to switch on/off prints to console +def init(args): + global tprint + global nprint + global lprint + + logging.basicConfig(filename='./lastrun.log', level=logging.INFO) + + def tqdm_out(msg): + # Remove formatting of display + logging.info(' '.join(msg.strip().splitlines())) + + if args.verbose: + tqdm.write(msg) + + def normal_out(msg): + logging.info(msg) + + if args.verbose: + print(msg) + + def licence_out(): + print(notice) + + tprint = tqdm_out + nprint = normal_out + lprint = licence_out diff --git a/pa_request.py b/pa_request.py new file mode 100644 index 0000000..72a15bb --- /dev/null +++ b/pa_request.py @@ -0,0 +1,330 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import time +import random +import re +import datetime +import itertools +import requests + +# External +import orjson +import unidecode +from opencage.geocoder import OpenCageGeocode +from tqdm import tqdm + +# Helper +import pa_print +from pa_utils import try_index + +geocoder = OpenCageGeocode('c55bcffbb38246aab6e54c136a5fac75') +email_regex = re.compile(r'@[a-zA-Z0-9-–]+\.[a-zA-Z0-9-–.]+') + +def scholar_api(data): + query_result = requests.post('https://www.semanticscholar.org/api/1/search', json=data).json() + time.sleep(3) # max 100 requests per 5 minute + return query_result + +def request_scholar(pub, args): + ''' Queries citations from Semantic Scholar + + :publication from bibtex file + ''' + try: + with open('./cache/json/scholar_cache.json','rb') as fp: + scholar_cache = orjson.loads(fp.read()) + except FileNotFoundError: + pa_print.tprint('\nCreating new Semantic Scholar cache!') + scholar_cache = {} + + semantic_scholar_data = { + "queryString": [], + "page": 1, + "pageSize": 1, + "sort": "relevance", + "authors": [], + "coAuthors": [], + "venues": [], + "yearFilter": None, + "requireViewablePdf": False, + "publicationTypes": [], + "externalContentTypes": [] + } + + # Fix names for searching + regextitle = re.compile(r'[^a-zA-Z0-9 ]') + regexname = re.compile(r'[^a-zA-Z- ]') + author_last_list = [] + + for _, (_, last) in enumerate(pub['author names']): + last = last.split('-')[-1] + author_last_list.append(last) + + title = unidecode.unidecode(pub['title']) + + if args.nime: + if title == 'Now': # title is too short, this return other paper, trying to filter it out by forcing full author name without chaning the code below + author_last_list[0] = 'GarthPaine' + + pub['citation count'] = 'N/A' + pub['key citation count'] = 'N/A' + + # Make query title, name and year lists + query_title = list(dict.fromkeys([title, regextitle.sub('', title), ' '.join([w for w in title.split() if len(w)>1])])) + if len(author_last_list) > 1: + query_name = [' '.join(author_last_list), author_last_list[0], ''] + else: + query_name = [author_last_list[0], ''] + query_year = ['', pub['year']] + + # Save query to be used for cache + full_query = f"{title} {' '.join(author_last_list)} {pub['year']}" + pub['scholar query'] = full_query + + if full_query not in scholar_cache or args.citations: + pa_print.tprint(f'\nQuerying Semantic Scholar...') + for temp in list(itertools.product(query_title, query_name, query_year)): + + # Generate new query from combination + temp_title, temp_author, temp_year = temp[0], temp[1], temp[2] + scholar_query = f'{temp_title} {temp_author} {temp_year}' + semantic_scholar_data['queryString'] = scholar_query + + # Try query + pa_print.tprint(f"Trying query: '{scholar_query}'") + try: + query_result = scholar_api(semantic_scholar_data) + + except Exception as e: + query_result = {'results' : {}} + err_info = 'x - While querying Semantic Scholar an exception of type {0} occurred.\nArguments:\n{1!r}.' + err_msg = err_info.format(type(e).__name__, e.args) + pa_print.tprint(err_msg) + + if not 'error' in query_result.keys(): + if bool(query_result['results']) and \ + bool(query_result['results'][0]['scorecardStats']) and \ + len(query_result['results'][0]['authors']) <= (len(author_last_list) + 1): + result_author = ' '.join([t[0]['name'] for t in query_result['results'][0]['authors']]) + result_author = regexname.sub('', unidecode.unidecode(result_author)).lower() + query_author = regexname.sub('', author_last_list[0].lower().split(' ')[-1]) + if result_author.find(query_author) != -1: + pub['scholar query'] = scholar_query + pub['citation count'] = query_result['results'][0]['scorecardStats'][0]['citationCount'] + pub['key citation count'] = query_result['results'][0]['scorecardStats'][0]['keyCitationCount'] + scholar_cache[full_query] = query_result['results'][0]['scorecardStats'] + pa_print.tprint(f"✓ - Paper has been cited {pub['citation count']} times") + break + + if pub['citation count'] == 'N/A': + pa_print.tprint('x - Cannot find citations for paper in Semantic Scholar') + scholar_cache[full_query] = 'N/A' + + with open('./cache/json/scholar_cache.json','wb') as fp: + fp.write(orjson.dumps(scholar_cache)) + + else: + if scholar_cache[full_query] != 'N/A': + pub['citation count'] = scholar_cache[full_query][0]['citationCount'] + pub['key citation count'] = scholar_cache[full_query][0]['keyCitationCount'] + else: + pub['citation count'] = 'N/A' + pub['key citation count'] = 'N/A' + + pa_print.tprint(f"\no - Retrieved from cache: {pub['citation count']} citations") + + # Average citations per year of age + if pub['citation count'] != 'N/A': + pub['yearly citations'] = int(pub['citation count']) / pub['age'] + else: pub['yearly citations'] = 'N/A' + +def request_location(author_info, args, pub): + ''' Extracts location from author blocks or universities and queries OpenCageGeocode + + :publication from bibtex file + ''' + author_count = pub['author count'] + + # Conference location lookup + cnf_query = pub['address'] + query_type = 'conference' + query_location(cnf_query, query_type, pub) # *** creates unneeded columns *** + + # Author location lookup + for author in range(author_count): # length of usable locations + query_type = 'author' + + # Assign one query (in order of priority) + # 1) If there is a university address from grobid + if pub['grobid author unis'][author] != 'N/A': # uni address + location_query = ', '.join(pub['grobid author unis'][author]) # (uni name, country) + query_origin = 'grobid uni' + + # 2) If grobid was used to add address (while 'location' is api derived) + elif pub['grobid addresses'][author] != 'N/A': + location_query = pub['grobid addresses'][author] + query_origin = 'grobid address' + + # 3) If theres a uni address from text block + elif pub['text author unis'][author] != 'N/A': + location_query = ', '.join(pub['text author unis'][author]) # (uni name, country) + query_origin = 'text uni' + + # 4) Else, scrape from raw author block (which may or may not have email) + elif author < len(author_info) and author_info[author] != 'N/A': # check if author_info contains author 'i' and is non-empty + auth_block = author_info[author] + cut_line = -1 if '@' in auth_block else 0 # one line above if email present + info_lines = auth_block.split('\n') + location_query = ' '.join(info_lines[cut_line-1:cut_line]) + if len([line for line in location_query if line.isdigit()]) > 8: # look for tele # + location_query = ' '.join(info_lines[cut_line-2:cut_line-1]) # take line higher if telephone + + query_origin = 'raw author block' + + else: + location_query = 'N/A' + query_origin = 'No query' + pa_print.tprint("\nCouldn't find a location to use!") + + pa_print.tprint(f'\nLooking for: {location_query}') + pub['author loc queries'].append(location_query) + pub['author query origins'].append(query_origin) + + query_location(location_query, query_type, pub) + +def query_location(location_query, query_type, pub): # 'query_type is now only used to print status + # Load cache + try: + with open('./cache/json/location_cache.json','rb') as fp: + location_cache = orjson.loads(fp.read()) + except FileNotFoundError: + pa_print.tprint('\nCreating new location cache!') + location_cache = {} + + # Not cached + if location_query not in location_cache: + try: + # location = geolocator.geocode(location_query, language="en") # Nominatim fallback + # OpenCageGeocode: 2,500 req/day, 1 req/s - https://github.com/OpenCageData/python-opencage-geocoder + location = geocoder.geocode(location_query, language='en', limit=1, no_annotations=1, no_record=1)[0] + + # Format result + geometry = location['geometry'] # lat/long + components = location['components'] # fine loc info + location_info = (location['formatted'], + (components['country'], components['continent']), + (geometry['lat'], geometry['lng']), + location['confidence']) # 1 (>25km) to 10 (<0.25km) + + location_cache[location_query] = location_info + pub[f'{query_type} location info'].append(location_info[:3]) # add all location into one column + pub[f'{query_type} location confidence'].append(location_info[3]) # confidence in separate column + pa_print.tprint(f'✓ - Parsed {query_type} location: {location_info[0]}') + time.sleep(1+random.random()) + + except: # API fails + location_cache[location_query] = 'N/A' + pub[f'{query_type} location info'].append('N/A') + pub[f'{query_type} location confidence'].append('N/A') + pa_print.tprint(f'x - Could not parse {query_type} location: {location_query}') + + # Save changes to cache + with open('./cache/json/location_cache.json','wb') as fp: + fp.write(orjson.dumps(location_cache)) + + # Cached + else: + if location_cache[location_query] != 'N/A' and not (location_query == 'N/A'): + location_info = location_cache[location_query] + pub[f'{query_type} location info'].append(location_info[:3]) + pub[f'{query_type} location confidence'].append(location_info[3]) + pa_print.tprint(f'o - Cached {query_type} location: {location_info[0]}') + + else: + location_info = 'N/A' + pub[f'{query_type} location info'].append('N/A') + pub[f'{query_type} location confidence'].append('N/A') + pa_print.tprint(f'o - Null {query_type} location: {location_info}') + +def request_uni(unidomains, author_info, args, pub): + ''' Extract university from email handle + + :publication from bibtex file + ''' + pub_matches = 0 + grob_matches = 0 + text_matches = 0 + + author_count = pub['author count'] + + # Internal functions for lookup in unidomains.json + def lookup_uni (handle, email_type, pub): + nonlocal pub_matches + for uni in unidomains: + if handle in uni['domains']: + pub[f'{email_type} author unis'].append((uni['name'], uni['country'])) + pub_matches += 1 + uni_match = True + break + + def handle_check(email, email_type, pub): + handle = email.split("@")[-1].strip() + + # Look for handle in json, split once by dot and retry if not found + uni_match = False + lookup_uni(handle, email_type, pub) + while uni_match == False and handle.count('.') > 1: + handle = handle.split('.', 1)[-1] + lookup_uni(handle, email_type, pub) + + # 1) Using grobid derived emails to choose handle + email_type = 'grobid' + for author in range(author_count): + email = pub['grobid emails'][author] + if email != 'N/A': # check for valid email + handle_check(email, email_type, pub) + + grob_matches = pub_matches + + # 2) Using scraped author info block from header if not enough emails + if len(author_info) > 0 and (grob_matches < author_count): + email_type = 'text' + for author in author_info: # ! could be more authors than exit + info_emails = email_regex.findall(author) # look for '@handle.tld' in block + for _, email in enumerate(info_emails): # case: multiple emails are within an author block #! (will overwrite) + if email != 'N/A': + handle_check(email, email_type, pub) + + # Fill in missing unis with 'N/A' # ! author block not linked in order with authors + for type, author in [(type, author) for type in ['grobid', 'text'] for author in range(author_count)]: + try: + pub[f'{type} author unis'][author] + except IndexError: + pub[f'{type} author unis'].append('N/A') + + text_matches = pub_matches - grob_matches + pub_matches = max(text_matches, grob_matches) + + pa_print.tprint(f'o - Found {pub_matches} uni\'s from email handles\n') diff --git a/pa_utils.py b/pa_utils.py new file mode 100644 index 0000000..5298dc3 --- /dev/null +++ b/pa_utils.py @@ -0,0 +1,249 @@ +# This file is part of the NIME Proceedings Analyzer (NIME PA) +# Copyright (C) 2021 Jackson Goode, Stefano Fasciani + +# The NIME PA is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# The NIME PA 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# If you use the NIME Proceedings Analyzer or any part of it in any program or +# publication, please acknowledge its authors by adding a reference to: + +# S. Fasciani, J. Goode, 20 NIMEs: Twenty Years of New Interfaces for Musical +# Expression, in proceedings of 2021 International Conference on New Interfaces +# for Musical Expression, Shanghai, China, 2021. + +# Native +import os +import csv +import socket +import requests +from collections import Counter + +# External +import pandas as pd +import numpy as np +import re +from geopy.distance import geodesic +from tqdm import tqdm + +# Helper +import pa_print + +def csv_save(bib_db): + ''' Saves current dataframe into a csv + + :database from constructed from bibtex file + ''' + df = pd.DataFrame(bib_db) + df = df.sort_index(axis=1) + df.to_csv('./output/export.csv', index=False) + +def calculate_carbon(pub): + ''' Calculate the carbon emissions from travel + + :publication (article) from database + ''' + author_count = pub['author count'] + + pa_print.tprint('\nCalculating carbon footprint...') + for author in range(author_count): + if pub['author location info'][author] != 'N/A': + distance = geodesic(pub['author location info'][author][2], pub['conference location info'][0][2]).km + pub['author distances'].append(distance) + + # * Calculate C02 emissions, more details here: https://github.com/milankl/CarbonFootprintAGU + carbon = 0.0 # kgCO2e + + if distance < 400: # bus / train / car at 60gCO2e / km / person + carbon = distance * 2 * 0.06 + elif distance < 1500: # short flight at 200gCO2e / km / person + carbon = distance * 2 * 0.2 + elif distance < 8000: # long flight at 250gCO2e / km / person + carbon = distance * 2 * 0.25 + else: # super long flight at 300gCO2e / km / person + carbon = distance * 2 * 0.3 + + pub['author footprints'].append(carbon / 1000) + pa_print.tprint(f'✓ - CO2 emissions for author {int(author + 1)}: {(carbon / 1000):.3f} tCO2e') + else: + pub['author distances'].append('N/A') + pub['author footprints'].append('N/A') + +def fill_empty(pub): + '''In case there is an errored pdf or grobid doc, fill in the fields with 'N/A' + + :publication (article) from database + ''' + author_count = pub['author count'] + + # * citation numer and conference location info should be filled regardless + # * author distances, author footprints, author loc queries, and author location info are filled elsewhere - issue #10 + # ? even if file is corrupt there may be some relevant info + for entry in ['author infos', 'grobid addresses', 'grobid author names', 'grobid author unis', 'grobid emails', 'grobid organisations', 'text author unis']: + pub[entry] = ['N/A' for author in range(author_count)] + +def doc_check(doc, pub, type): + ''' Check for common decoding errors (does not catch all) # ! more intelligent method? + + :document from text extraction (miner) or xml extraction (grobid) + :publication (article) from database + :type of doc (either 'text' or 'grobid') + ''' + errored = False + + alphas = re.compile('[^a-zA-Z]') + doc_alphas = alphas.sub('', doc) + if len(doc) > 2 * len(doc_alphas) : # more symbols than 2x letters + pub[f'{type} non alpha'] = 'X' + pa_print.tprint('\nFile was not decoded well - non-alpha') + errored = True + + cids = re.compile(r'\(cid:[0-9]+\)') + doc_cidless = cids.sub('', doc, re.M) # when font cannot be decoded, (cid:#) is returned, remove these + if len(doc) > 2 * len(doc_cidless): # if most of content was undecodable, skip + pub[f'{type} poor decoding'] = 'X' + pa_print.tprint('\nFile was not decoded well - cid: present') + errored = True + + return errored + +def doc_quality(doc, pub, type): + ''' Check for document quality + + :document from text extraction (miner) or xml extraction (grobid) + :publication (article) from database + :type of doc (either 'text' or 'grobid') + ''' + errored = False + + if not (doc and doc.strip()): # if doc is clearly errored or empty + fill_empty(pub) + pub[f'{type} fail'] = 'X' + errored = True + else: + errored = doc_check(doc, pub, type) # issues with decoding + + return errored + +def try_index(something, index, fail): + try: + return eval(f'{something}{index}') + except: + return fail + +def import_config(filepath): + ''' Imports a custom configuration for filter words and years + + :filepath the file path + ''' + user_config = pd.read_csv(filepath, header=0, delimiter=',') + user_config = user_config.fillna('') + + keywords = [] + ignore_words = [] + merge_words = [] + selected_years = [] + + for config_tuple in user_config.itertuples(index=False): + if config_tuple[0] == 'keywords': # single list + for i in config_tuple[1:]: + keywords.append(i) + elif config_tuple[0] == 'ignore': # single list + for i in config_tuple[1:]: + ignore_words.append(i) + elif config_tuple[0] == 'merge': # list of lists + merge_group = list(filter(None, config_tuple[1:])) + merge_words.append(merge_group) + elif config_tuple[0] == 'years': # single list + year_num = [i for i in config_tuple if i != ''] + if len(year_num) == 2: + selected_years.append(str(int(config_tuple[1]))) + else: + year_span = int(config_tuple[2]) - int(config_tuple[1]) + for i in range(year_span + 1): + selected_years.append(str(int(config_tuple[1]) + i)) + + keywords = list(filter(None, keywords)) + ignore_words = list(filter(None, ignore_words)) + + pa_print.tprint('\nParameters from custom.csv:') + if selected_years: + pa_print.tprint(f'Selected years: {selected_years}') + if keywords: + pa_print.tprint(f'Search words: {keywords}') + if ignore_words: + pa_print.tprint(f'Ignored words: {ignore_words}') + if merge_words: + pa_print.tprint(f'Merged words: {merge_words}') + + return (keywords, ignore_words, merge_words, selected_years) + +def boolify(ans, default=False): + ''' Takes a question letter and converts it to a bool + + :ans as a letter (ex. y, b) + :default bool if user types something else + ''' + if ans in ['Y','y','yes']: + ans = True + elif ans in ['N','n','no']: + ans = False + else: + ans = default + return ans + +def post_processing(pub): + col_countries, col_continents, col_institutes = [], [], [] + empty = [float('nan'), 'N/A'] + full_text = '' + + for author in range(pub['author count']): + + # Countries and continents + countries = [try_index(country, '[1][0]', 'N/A') for country in pub['author location info']] + for i, n in enumerate(countries): + if 'Korea' in n: + countries[i] = 'Republic of Korea' + elif 'The Netherlands' in n: + countries[i] = 'Netherlands' + + continents = [try_index(continent, '[1][1]', 'N/A') for continent in pub['author location info']] + + pub['countries'] = countries + pub['continents'] = continents + + # Check for unis and organisations + institutes = [] + for _, (uni, org) in enumerate(zip(pub['grobid author unis'], pub['grobid organisations'])): + if uni in empty: # if uni is absent and there is an org present for that index + institutes.append(org) + else: + institutes.append(', '.join(uni)) # make unique string from (uni, location) + pub['institutes'] = institutes # this is a union list to derive location using uni or organisation + + # Iterate through article and get raw text + file_name = pub['url'].split('/')[-1].split('.')[0] + grob_text_file = f'./cache/text/grobid/grob_{file_name}.txt' + + if os.path.isfile(grob_text_file): # check if txt already exists + with open(grob_text_file, 'r') as f: + full_text = f.read() + + if len(full_text.split(' ')) < 10: # body text missing in grobid file - check for miner + miner_text_file = f'./cache/text/miner/miner_{file_name}.txt' + + if os.path.isfile(grob_text_file): # check if txt already exists + with open(miner_text_file, 'r') as f: + full_text = f.read() + + # adding word count + pub['word count'] = len(full_text.split()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..da7e31f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +bibtexparser +gender-guesser +gensim +geopy +lxml +nltk +numpy +onomancer +opencage +orjson +pandas +pdfminer.six +BeautifulSoup4 +pyLDAvis +regex +requests +tqdm +unidecode +wordcloud +openpyxl +oschmod +python-Levenshtein +https://github.com/kermitt2/grobid_client_python/archive/refs/heads/master.zip diff --git a/resources/conferences.csv b/resources/conferences.csv new file mode 100644 index 0000000..5ad0077 --- /dev/null +++ b/resources/conferences.csv @@ -0,0 +1,21 @@ +year,place,geocoordinates,country,country_iso3,continent,organizer,reviewers,keynotes,keynote_1_first,keynote_1_last,keynote_1_sex,keynote_2_first,keynote_2_last,keynote_2_sex,keynote_3_first,keynote_3_last,keynote_3_sex,keynote_4_first,keynote_4_last,keynote_4_sex +2001,"Seattle, Washington","47.6062° N, 122.3321° W",United States of America,USA,North America,Conference on Human Factors in Computing Systems,14,1,Max,Matthews,M,,,,,,,,, +2002,Dublin,"53.3498° N, 6.2603° W",Ireland,IRL,Europe,Media Lab Europe,28,2,Tod,Machover,M,Joel,Chadabe,M,,,,,, +2003,Montreal,"45.5017° N, 73.5673° W",Canada,CAN,North America,McGill University,63,3,Joseph,Paradiso,M,Claude,Cadoz,M,Michel,Waiswisz,M,,, +2004,Hamamatsu,"34.7103° N, 137.7274° E",Japan,JPN,Asia,Shizuoka University of Art and Culture,41,2,Robert,Moog,M,Toshio,Iwai,M,,,,,, +2005,Vancouver,"49.2827° N, 123.1207° W",Canada,CAN,North America,University of British Columbia,55,3,Don,Buchla,M,Golan,Levin,M,Bill,Buxton,M,,, +2006,Paris,"48.8566° N, 2.3522° E",France,FRA,Europe,IRCAM,126,2,George,Lewis,M,William,Gaver,M,,,,,, +2007,"New York City, New York","40.7128° N, 74.0060° W",United States of America,USA,North America,New York University,147,3,Perry,Cook,M,Gerhard,Trimpin,M,Teresa Marrin,Nakra,F,,, +2008,Genova,"44.4056° N, 8.9463° E",Italy,ITA,Europe,University of Genova,142,2,Andrew,Gerzso,M,Xavier,Serra,M,,,,,, +2009,"Pittsburgh, Pennsylvania","40.4406° N, 79.9959° W",United States of America,USA,North America,Carnegie Mellon School of Music,103,1,Paul,DeMarinis,M,,,,,,,,, +2010,Sydney,"33.8688° S, 151.2093° E",Australia,AUS,Oceania,University of Technology Sydney,155,2,Nicolas,Collins,M,,Stelarc,M,,,,,, +2011,Oslo,"59.9139° N, 10.7522° E",Norway,NOR,Europe,University of Oslo,173,3,Tellef,Kvifte,M,David,Rokeby,M,Sergi,Jorga,M,,, +2012,"Ann Arbor, Michigan","42.2808° N, 83.7430° W",United States of America,USA,North America,University of Michigan,160,2,David,Wessel,M,David,Huron,M,,,,,, +2013,Daejeon,"36.3504° N, 127.3845° E",Republic of Korea,PRK,Asia,Korea Advanced Institute of Science and Technology,106,2,Bill,Verplank,M,Ajay,Kapur,M,,,,,, +2014,London,"51.5074° N, 0.1278° W",United Kingdom,GBR,Europe,Goldsmiths University,237,2,Hiroshi,Ishii,M,Laetitia,Sonami,F,,,,,, +2015,"Baton Rouge, Louisiana","30.4515° N, 91.1871° W",United States of America,USA,North America,Louisiana State University,201,2,Roger Luke ,DuBois,M,Sile,O’Modhrain,F,,,,,, +2016,Brisbane,"27.4698° S, 153.0251° E",Australia,AUS,Oceania,Griffith University,150,2,Miya,Masaoka,F,Garth,Paine,M,,,,,, +2017,Copenhagen,"55.6761° N, 12.5683° E",Denmark,DNK,Europe,Aalborg University Copenhagen,148,3,Ge,Wang,M,Dorit,Chrysler,F,Chris,Chafe,M,,, +2018,"Blacksburg, Virginia","37.2296° N, 80.4139° W",United States of America,USA,North America,Virginia Tech,211,4,Onyx,Ashanti,M,R. Benjamin,Knapp ,M,Ikue,Mori,F,Pamela,Z,F +2019,Porto Alegre,"30.0346° S, 51.2177° W",Brazil,BRA,South America,Federal University of Rio Grande do Sul,260,3,Marcelo Mortensen,Wanderley,M,Eduardo Reck,Miranda,M,Ana María Romano,Gomez,F,,, +2020,Birmingham,"52.4862° N, 1.8904° W",United Kingdom,GBR,Europe,Royal Birmingham Conservatoire,235,4,,Drake Music Labs,M & F,,Crewdson & Cevanne,M & F,,Dunning & Underwood,M,Lilja Maria ,Asmundsdottir,F diff --git a/resources/custom.csv b/resources/custom.csv new file mode 100644 index 0000000..a56c0ab --- /dev/null +++ b/resources/custom.csv @@ -0,0 +1 @@ +entry type diff --git a/resources/custom_ex.csv b/resources/custom_ex.csv new file mode 100644 index 0000000..bbb70fd --- /dev/null +++ b/resources/custom_ex.csv @@ -0,0 +1,10 @@ +entry type,,,, +years,2011,,, +years,2014,2016,, +keywords,movement,skill,attention, +ignore,music,midi,technology, +merge,movement,motion,gesture,dance +merge,control,controller,, +merge,sound,audio,, +merge,performance,performer,, +merge,play,playing,, \ No newline at end of file diff --git a/resources/nime_reader.txt b/resources/nime_reader.txt new file mode 100644 index 0000000..af5e5ad --- /dev/null +++ b/resources/nime_reader.txt @@ -0,0 +1,30 @@ +Principles for Designing Computer Music Controllers +Problems and Prospects for Intimate Musical Control of Computers +The Importance of Parameter Mapping in Electronic Instrument Design +Multimodal Interaction in Music Using the Electromyogram and Relative Position Sensing +The Plank: Designing a Simple Haptic Controller +Contexts of Collaborative Musical Experiences +Sonigraphical Instruments: From FMOL to the reacTable* +Designing, Playing, and Performing with a Vision-Based Mouth Interface +Open Sound Control: State of the Art 2003 +The Electronic Sitar Controller +PebbleBox and CrumbleBag: Tactile Interfaces for Granular Synthesis +Toward a Generalized Friction Controller: From the Bowed String to Unusual Musical Instruments +On-the-Fly Programming: Using Code as an Expressive Musical Instrument +Towards a Dimension Space for Musical Devices +The Overtone Violin +Sensemble: A Wireless, Compact, Multi-user Sensor System for Interactive Dance +Mobile Music Technology: Report on an Emerging Community +Wireless Sensor Interface and Gesture-Follower for Music Pedagogy +Don’t Forget the Laptop: Using Native Input Capabilities for Expressive Musical Control +Expression and Its Discontents: Toward an Ecology of Musical Creation +The Acoustic, the Digital and the Body: ASurveyonMusicalInstruments +Eight Years of Practice on the Hyper-Flute: Technological and Musical Perspectives +A History of Hemispherical Speakers at Princeton, Plus a DIY Guide +Satellite CCRMA: A Musical Interaction and Sound Synthesis Platform +The Fingerphone: A Case Study of Sustainable Instrument Redesign +To Be Inside Someone Else’s Dream: Music for Sleeping and Waking Minds +TouchKeys: Capacitive Multi-touch Sensing on a Physical Keyboard +The Web Browser as Synthesizer and Interface +To Gesture or Not? An Analysis of Terminology in NIME Proceedings 2001–2013 +Fourteen Years of NIME: The Value and Meaning of ‘Community’ in Interactive Music Research \ No newline at end of file