diff --git a/build_conventional/LICENSE b/build_conventional/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/build_conventional/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/build_conventional/README.md b/build_conventional/README.md new file mode 100644 index 0000000..2e2068f --- /dev/null +++ b/build_conventional/README.md @@ -0,0 +1,98 @@ +# MAGIST-Algorithm +Multi-Agent Generally Intelligent Simultaneous Training Algorithm for Project Zeta! +![Github Banner(1)](https://user-images.githubusercontent.com/85193239/171949594-50a1f380-de26-4cd1-94d8-769a4c032455.png) + +## Working Principal +Here is a flow diagram with the entire system drawn: +https://lucid.app/documents/embeddedchart/6d04c807-0b77-495e-9b84-3abf38f32630 + +### Data +The data is the most important element as the entire intelligence works around it. That is why it is important for the +AI to process it and provide reasonable assumptions. There is another condition however: the algorithm, in its finished +state, MUST be strictly Python code. This means no pretrained models or presets. It must find its own data and process it unsupervised. This structure is called a "semi-supervised" structure. Here, the data wil assume the following structure: + +``` +Object -> Common Associated Verbs, Synonyms, Events, Timestamps of usage, Nearby Objects, etc. +``` + +This is the "Who, What, When, Where, Why, How" of the data. This data can later be filtered and called apon when +inferences are needed. To get here, however, the data must first be extacted from a single image. Since no pretrained +models are allowed, here is the process to follow: + +``` +1. K-Means Clustering(find key objects in image) -> Discriminator for integrity check(see if clustering was performed well) +2. Reverse Image Search and Google Scraping(find label of image) -> Data Downloader(find dataset from large datasets) +3. Transfer Learn Model -> Object Detector +``` + +### Natural Language Processing +Another key stage of this AGI(Artificial General Intelligence) is the huaman interaction and understanding. MAGIST will +use a Transformer chatbot to listen to conversations and simultaneously train on them. When it is queried, it will collect information from the database, and use the transformer to fit a response. This will be done by using a GAN system infused into the transformer. The transformer will act as the discriminator to perform an integrity check. + +*** + +## Usage +This project is still under development. Please contact me at [deepshiftlabs@outlook.com]() if you want immediate access +to MAGIST. Once the algorithm is in a stable state, I will release a Python Package on PYPI and Github for access. There +will also be a wiki with more instructions. + +*** + +## Installation +This project has many dependencies. Most can be installed using `pip`. Some require OS-level package managers. This is +going to work best in Linux-based systems. + +### Linux (Ubuntu-based Systems) +First install `Python 3` and `pip`: +```commandline +sudo apt python3 python3-dev python3-pip +``` +Next, we need to install Firefox and its corresponding `geckodriver` for headless Selenium searches: +```commandline +sudo apt install firefox firefox-geckodriver +``` +Next, create a Python environment. There are 2 ways to do this: Anaconda or VEnv. + +#### Anaconda +First install Anaconda from https://www.anaconda.com/. + +Make the Anaconda environment: +```commandline +conda create --name myenv +``` +Activate the environment in your current console. Note: You will have to do this every time you want to run MAGIST. +```commandline +conda activate myenv +``` +Install all the packages. +```commandline +pip3 install -r requirments.txt +``` + +#### VEnv +Make the environment in a designated location. +```commandline +python3 -m venv /path/to/new/virtual/environment +``` +To activate it, you must travel to that `path/bin/` and then run: +```commandline +source activate +``` +Install all the packages. +```commandline +pip3 install -r requirments.txt +``` + +**Congratulations! You are all setup to script and use MAGIST** + +*** + +## Contributing +Your contribution, monetary or programmatically, is crucial for the rapid development of the algorithm and its training. +Please consider contributing. Even the smallest change to my README will be greatly appreciated. + +*** + +# Disclaimer +Artificial Intelligence is a powerful field of research and study, and it should be kept that way. Unethical use of the AI can have severe repercussions to society and to the perpetrator. DeepShift Labs is strictly a research company and all of our programs follow. Hence, all of our products, MAGIST included, are to be used **strictly** for research purposes. Misuse of this program can lead to heavy fines and prosecution. +Furthermore, to retitle, rebrand, or redistribute without **explicitly** crediting DeepShift Labs is illegal. diff --git a/build_conventional/pyproject.toml b/build_conventional/pyproject.toml new file mode 100644 index 0000000..fa7093a --- /dev/null +++ b/build_conventional/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools>=42"] +build-backend = "setuptools.build_meta" \ No newline at end of file diff --git a/build_conventional/setup.py b/build_conventional/setup.py new file mode 100644 index 0000000..375da32 --- /dev/null +++ b/build_conventional/setup.py @@ -0,0 +1,45 @@ +import setuptools + +with open("README.md", "r", encoding="utf-8") as fh: + long_description = fh.read() + +setuptools.setup( + name="MAGIST-Algorithm", + version="0.1.0", + author="DeepShift Labs", + author_email="krishna.shah@deepshift.dev", + description="A powerful library for high-power, generally intelligent models.", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/DeepShift-Labs/MAGIST-Algorithm", + project_urls={ + "Bug Tracker": "https://github.com/DeepShift-Labs/MAGIST-Algorithm/issues", + }, + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: GNU GPL v3 License", + "Operating System :: OS Independent", + ], + package_dir={"": "src"}, + packages=setuptools.find_packages(where="src"), + python_requires=">=3.6", + install_requires=[ + "beautifulsoup4==4.11.1", + "Google_Images_Search==1.4.2", + "matplotlib==3.5.1", + "numpy==1.22.3", + "pandas==1.4.1", + "Pillow==9.1.1", + "pymongo==3.12.3", + "requests", + "urllib3", + "scikit_image==0.19.2", + "scikit_learn==1.1.1", + "selenium==4.2.0", + "SpeechRecognition==3.8.1", + "tensorflow==2.9.1", + "tqdm==4.63.0", + "wikipedia", + "elasticsearch", + ], +) diff --git a/build_conventional/src/MAGIST/NLP/AudioTranscriber.py b/build_conventional/src/MAGIST/NLP/AudioTranscriber.py new file mode 100644 index 0000000..6b139de --- /dev/null +++ b/build_conventional/src/MAGIST/NLP/AudioTranscriber.py @@ -0,0 +1,82 @@ +"""This has classes to process audio files and microphone data and transcribe them. + +This main class uses the Google Speech API to transcribe audio files. It contains 2 main functions for microphone and +audio file processing respectively. +""" + +import speech_recognition as sr +import time +import pathlib + +from ..Utils.LogMaster.log_init import MainLogger + +class GoogleAudioTranscriber(): + """Google Audio Transcriber Class.""" + + def __init__(self, config): + """Initialize the Google Audio Transcriber and Microphone object. + + :param config: The config file(config.json). + """ + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("GoogleAudioTranscriber") # Create a script specific logging instance + + self.log.info("GoogleAudioTranscriber Recognizer Initialized Successfully") + + def microphone_listener(self): + """Listen to the microphone and transcribe the audio. + + :return: The transcription of the audio as a string. + """ + + self.r = sr.Recognizer() + self.m = sr.Microphone() + + with self.m as source: + self.log.info("GoogleAudioTranscriber Listening...") + audio = self.r.listen(source) + self.log.info("GoogleAudioTranscriber Listening Complete") + try: + start = time.time() + transcription = self.r.recognize_google(audio) + self.log.info("Transcribed Prediction: " + transcription) + end = time.time() + except sr.UnknownValueError: + self.log.warning("Google could not understand audio") + + self.log.info("Time taken: " + str(end - start)) + return transcription + + def file_transcriber(self, file): + """Transcribe an audio file. + + :param file: The file to be transcribed. + + :return: The transcription of the audio as a string. + """ + + self.r = sr.Recognizer() + self.m = sr.Microphone() + + file = pathlib.Path(file) + file = file.resolve() # Find absolute path from a relative one. + file = str(file) + + audio = sr.AudioFile(file) + + with audio as source: + self.log.info("GoogleAudioTranscriber Processing...") + audio = self.r.record(source) + self.log.info("GoogleAudioTranscriber Processing Complete") + try: + start = time.time() + transcription = self.r.recognize_google(audio) + self.log.info("Transcribed Prediction: " + transcription) + end = time.time() + except sr.UnknownValueError: + self.log.warning("Google could not understand audio") + + self.log.info("Time taken: " + str(end - start)) + + return transcription \ No newline at end of file diff --git a/build_conventional/src/MAGIST/NLP/SelfAttention.py b/build_conventional/src/MAGIST/NLP/SelfAttention.py new file mode 100644 index 0000000..d93b713 --- /dev/null +++ b/build_conventional/src/MAGIST/NLP/SelfAttention.py @@ -0,0 +1,246 @@ +"""Contains all necessary functions to train and use unsupervised text prioritization. + +This class has numerous functions to run the text prioritization algorithm. You can simply call the class instance to +run the entire algorithm. +""" + + +import tensorflow as tf +import numpy as np +from ..Utils.LogMaster.log_init import MainLogger + +class TextPreprocessing(): + def __init__(self, config): + """Initializes the TextPreprocessing class and config. + + :param config: The config file containing all necessary parameters(config.json). + """ + root_log = MainLogger(config) + self.log = root_log.StandardLogger("TextPreprocessing") # Create a script specific logging instance + + def __format_data(self, in_text): + """Formats the input text to be compatible with the model. + + :param in_text: The text(string) to be formatted. + + :return: The formatted text. + """ + punctuation = [".", ",", ";", ":", "!", "?", "\"", "'", "`", "~", "`", "´", "’", "‘", "“", "”", "„", "‟", "‹", "›", + "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", + "„", + "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", + "’", + "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", + "‹", + "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", + "›", + "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", + "„", + "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’"] + def __remove_puctuation(text): + """Removes punctuation from the text. + + :param text: The text to be formatted. + + :return: The formatted text. + """ + for i in punctuation: + text = text.replace(i, "") + return text + + def __lowercase(text): + """Converts the text to lowercase. + + :param text: The text to be formatted. + + :return: The formatted text. + """ + return text.lower() + + in_text = __remove_puctuation(in_text) + in_text = __lowercase(in_text) + return in_text + + def __tokenize(self, input_text): + """Splits the input text into tokens. + + :param input_text: The text to be split. + + :return: The tokens. + """ + input_text = self.__format_data(input_text) + return input_text.split(" ") + + def split_positional_encodings(self, input_text): + """Splits the input text into positional encodings. + + :param input_text: The text to be split. + + :return: The positional encodings. + """ + input_text = self.__format_data(input_text) + split_text = self.__tokenize(input_text) + + position_dict = [] + count = 1 + for s in split_text: + position_dict.append([count, s]) + count += 1 + + return position_dict + + def vectorize_text(self, raw_input_text): + """Vectorizes the input text. + + :param raw_input_text: The text to be vectorized. + + :return: The vectorized text. + """ + input_text = self.__format_data(raw_input_text) + self.vectorize_layer = tf.keras.layers.TextVectorization() + self.vectorize_layer.adapt([raw_input_text]) + vec = self.vectorize_layer(raw_input_text) + + return np.array(vec) + + def __positional_embedding_function(self, n, scale=0.1, scalar=1): + """Computes the positional embedding. + + :param n: The position to be computed. + :param scale: The scale of the positional embedding function. + :param scalar: The scalar multiplier to the output of the positional embedding. + + :return: The positional embedding. + """ + x = np.multiply(n, scale) + part1 = np.sin(np.multiply(n, x)) + part2 = np.sin(np.divide(1, x)) + return np.multiply(np.abs(np.multiply(part1, part2)), scalar) + + def positional_embedding(self, split_positional_encodings, vectorized_text, scalar=3): + """Computes the positional embedding. + + :param split_positional_encodings: The positional encodings to be computed. + :param vectorized_text: The vectorized text. + :param scalar: The scalar multiplier to the output of the positional embedding. + + :return: The positional embedding. + """ + position_computed = [] + for i in split_positional_encodings: + pos = self.__positional_embedding_function(i[0], scalar=scalar) + position_computed.append(pos) + + final_position_embedding = [] + + for i in range(len(position_computed)): + final_position_embedding.append(int(vectorized_text[i]) + position_computed[i]) + + return final_position_embedding + + def SelfAttention(self, value, query, key, in_len): + """Computes the self attention. + + :param value: The value to be computed. + :param query: The query to be computed. + :param key: The key to be computed. + :param in_len: The length of the input. + + Note: The value, query, and key must be the same length and are the same thing usually for self-attention. + """ + value_mod = tf.keras.models.Sequential() + value_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + + key_mod = tf.keras.models.Sequential() + key_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + + query_mod = tf.keras.models.Sequential() + query_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + + # value = value_mod.predict(value) + # key = key_mod.predict(key) + # query = query_mod.predict(query) + + value = np.array(value).astype(np.float64) + key = np.array(key).astype(np.float64) + query = np.array(query).astype(np.float64) + + value = np.squeeze(value) + key = np.squeeze(key) + query = np.squeeze(query) + + val_mag = np.sqrt(np.dot(value, value)) + key_mag = np.sqrt(np.dot(key, key)) + query_mag = np.sqrt(np.dot(query, query)) + + matmul = key_mag * query_mag + theta = np.dot(value, query) / matmul + + # theta = np.arccos(theta) + + softmax = 1 / ((np.e) ** (-theta) + 1) + + out = softmax * value + + return out + + def compute_theshold(self, attention_weights): + """Computes the threshold for relevant and irrelevant text. + + :param attention_weights: The attention weights to be computed. + + :return: The threshold(int). + """ + threshold = 0 + for b in attention_weights: + if b != 0: + threshold += b + return threshold / len(attention_weights) + + def print_results(self, attention_weights, threshold, vectorized_text, show_only_important=False): + """Prints the results. + """ + for i in range(len(attention_weights)): + stat = "" + if attention_weights[i] > threshold: + stat = "Good" + elif attention_weights[i] == threshold: + stat = "Meh" + elif attention_weights[i] < threshold: + stat = "Not" + if show_only_important: + if attention_weights[i] >= threshold: + self.log.info(f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") + else: + self.log.info( + f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") + + def __call__(self, input_text): + """Computes everything and returns the importance matrix. + + :param input_text: The text to be computed. + + :return: The simplified importance matrix. + """ + s = self.split_positional_encodings(input_text) + vec = self.vectorize_text(input_text) + + out_fin = self.positional_embedding(s, vec) + + attention_weights = self.SelfAttention(out_fin, out_fin, out_fin, len(out_fin)) + threshold = self.compute_theshold(attention_weights) + + final_output_array = [] + + for i in range(len(attention_weights)): + stat = "" + if attention_weights[i] > threshold: + stat = "Good" + elif attention_weights[i] == threshold: + stat = "Meh" + elif attention_weights[i] < threshold: + stat = "Not" + + final_output_array.append([attention_weights[i], self.vectorize_layer.get_vocabulary()[vec[i]], stat]) + + return final_output_array diff --git a/build_conventional/src/MAGIST/NLP/WordScraper.py b/build_conventional/src/MAGIST/NLP/WordScraper.py new file mode 100644 index 0000000..11165ef --- /dev/null +++ b/build_conventional/src/MAGIST/NLP/WordScraper.py @@ -0,0 +1,107 @@ +import requests, json + +from ..Utils.LogMaster.log_init import MainLogger + + +class ClassDeprecated(Exception): + pass + + +class UrbanDictionary(): + def __init__(self, config): + """Initialize the Urban Dictionary API. + :param config: The config file(config.json). + """ + + raise ClassDeprecated("This class is deprecated") + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("UrbanDictionary") + + self.url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define" + + def define(self, word): + """Define a word. + :param word: The word to be defined. + :return: The definition of the word. + """ + + querystring = {"term": word} + + headers = { + "X-RapidAPI-Key": "xxx", + "X-RapidAPI-Host": "mashape-community-urban-dictionary.p.rapidapi.com" + } + + response = requests.request("GET", self.url, headers=headers, params=querystring) + + json_data = json.loads(response.text) + + definition = json_data["list"][0]["definition"] + + self.log.info(f"Definition of {word}: " + definition) + + return definition + +class DicitonaryAPIDev(): + def __init__(self, config): + """Initialize the Dictionary API.. + + :param config: The config file(config.json). + """ + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("DisctionaryAPI") + + self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + + def define(self, word): + """Define a word. + + :param word: The word to be defined. + + :return: The definition of the word. + """ + + querystring = {"term": word} + + self.url = self.url + word + + response = requests.request("GET", self.url, params=querystring) + + json_data = json.loads(response.text) + + definition = json_data + try: + definition = definition[0]["meanings"][0]["definitions"][0]["definition"] + except KeyError: + definition = "No definition found" + + self.log.info(f"Definition of {word}: " + definition) + + self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + + return definition + + + +class FullDictionarySearch(): + def __init__(self, config): + """Initialize the Dictionary API.. + + :param config: The config file(config.json). + """ + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("FullDictionarySearch") + + self.dictdev = DicitonaryAPIDev(config) + + def define(self, word): + definition = self.dictdev.define(word) + + if definition == "No definition found": + self.log.info("No definition found in DictionaryAPI.dev.") + definition = None + + return definition \ No newline at end of file diff --git a/build_conventional/src/MAGIST/NLP/__init__.py b/build_conventional/src/MAGIST/NLP/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/NeuralDB/MongoUtils.py b/build_conventional/src/MAGIST/NeuralDB/MongoUtils.py new file mode 100644 index 0000000..bf4427d --- /dev/null +++ b/build_conventional/src/MAGIST/NeuralDB/MongoUtils.py @@ -0,0 +1,92 @@ +"""Mongo Utils file that manages and initializes the MongoDB connection. + +This file contains the main Admin functions and the rest is done using the PrimaryNeuralDB file. +""" + +import json +import os +import pathlib + +import pymongo as mongo + +from ..Utils.LogMaster.log_init import MainLogger + + +class AdminUtils(): + """Class that manages the MongoDB connection.""" + + def __init__(self, config): + """Initialize the AdminUtils class. + + :param config: The config file(string). + """ + root_log = MainLogger(config) + self.log = root_log.StandardLogger("MongoAdminUtils") # Create a script specific logging instance + + self.log.info("Firing up MongoDB Neural Database! Standby...") + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['system_administration']: + try: + self.passcode = i["sudo_password"] + except KeyError: + pass + + for j in config['neural_db']: + try: + self.mgsocket = j["mongo_socket"] + except KeyError: + pass + + def initialize_neuraldb(self): + """Initialize the MongoDB connection. + + :return: The MongoDB client. + """ + + command = 'systemctl start mongod' + p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) + self.log.info("NeuralDB Launched Successfully! Attempting to connect to local socket...") + + self.db_client = mongo.MongoClient(self.mgsocket) + + if self.db_client: + self.log.info("Mongo client linked successfully. Local DB Agent is running.") + else: + self.log.error("Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " + "something like this: mongodb://localhost:27017/") + + return self.db_client + + def stop_db(self): + """Stop the MongoDB connection. + """ + + self.log.info("Shutting down MongoDB Neural Database! Standby...") + command = 'systemctl stop mongod' + p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) + self.log.info("NeuralDB Closed Successfully!") + + def restart_db(self): + """Restart the MongoDB connection. + """ + + self.log.info("Restarting MongoDB Neural Database! Standby...") + + command = 'systemctl restart mongod' + p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) + self.log.info("NeuralDB Re-Launched Successfully! Attempting to connect to local socket...") + + self.db_client = mongo.MongoClient(self.mgsocket) + + if self.db_client: + self.log.info("Mongo client linked successfully. Local DB Agent is running.") + else: + self.log.error("Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " + "something like this: mongodb://localhost:27017/") + + return self.db_client diff --git a/build_conventional/src/MAGIST/NeuralDB/PrimaryNeuralDB.py b/build_conventional/src/MAGIST/NeuralDB/PrimaryNeuralDB.py new file mode 100644 index 0000000..42b8e78 --- /dev/null +++ b/build_conventional/src/MAGIST/NeuralDB/PrimaryNeuralDB.py @@ -0,0 +1,426 @@ +"""Main NeuralDB updating and querying class + +This class contains functions necessary to add information to the NeuralDB as well as query it for information upon +request. This requires the instantiated client from MongoUtils. +""" + +import json +import pathlib +import time +import re + +from ..Utils.LogMaster.log_init import MainLogger + + +class NeuralDB(): + """Main NeuralDB class""" + def __init__(self, config, db_client): + """Initialize NeuralDB class, parse config.json, and receive MongoDB client + + :param config: The config(config.json) file as a string. + :param db_client: The MongoDB client from MongoUtils. + """ + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("NeuralDB") # Create a script specific logging instance + self.client = db_client + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['neural_db']: + try: + self.db_string = i["db_search_zone"] + except KeyError: + pass + + def recreate_db(self): + """Recreate the databases and collections + """ + + self.log.warning("NeuralDB is about to reset and recreate all Databases and tables. Proceeding in 5 seconds...") + + for i in range(5): + self.log.warning("{}...".format(5 - i)) + time.sleep(1) + self.log.warning("Resetting and recreating all databases and tables...") + + self.dbs = [] + self.collections = [] + + for d in self.db_string: + if d == "vision": + self.vision = self.client['VisionDB'] + + self.obj_desc = self.vision["ObjectDesc"] + self.obj_location = self.vision["ObjectLocation"] + self.obj_obj_relation = self.vision["ObjectObjectRelation"] + self.obj_users = self.vision["ObjectUsers"] + + self.log.info("Vision database is included in NeuralDB search.") + + self.dbs.append(self.vision) + + self.collections.append(self.obj_desc) + self.collections.append(self.obj_location) + self.collections.append(self.obj_obj_relation) + self.collections.append(self.obj_users) + if d == "nlp": + self.nlp = self.client["NLP"] + + self.word_desc = self.nlp["WordDesc"] + self.word_location = self.nlp["WordLocation"] + + self.log.info("NLP database is included in NeuralDB search.") + + self.dbs.append(self.nlp) + + self.collections.append(self.word_desc) + self.collections.append(self.word_location) + if d == "common": + self.common = self.client["Common"] + + self.word_obj_relation = self.common["WordObjectRelation"] + + self.log.info("Common database is included in NeuralDB search.") + + self.dbs.append(self.common) + + self.collections.append(self.word_obj_relation) + + try: + if self.vision is None: + self.log.warning("Vision database was not included from NeuralDB search.") + except AttributeError: + self.log.warning("Vision database was not included from NeuralDB search.") + + try: + if self.nlp is None: + self.log.warning("NLP database was not included from NeuralDB search.") + except AttributeError: + self.log.warning("NLP database was not included from NeuralDB search.") + + try: + if self.common is None: + self.log.warning("Common database was not included from NeuralDB search.") + except AttributeError: + self.log.warning("Common database was not included from NeuralDB search.") + + def insert_obj_desc(self, obj_name, obj_desc): + """Insert object and its description into the Vision database. + + :param obj_name: The name of the object(string). + :param obj_desc: The description of the object(string). + """ + + self.log.info(f"Inserting object description: {obj_name} - {obj_desc}") + self.obj_desc.insert_one({"obj_name": obj_name, "obj_desc": obj_desc}) + def insert_obj_location(self, obj_name, obj_location): + """Insert object and its location into the Vision database. + + :param obj_name: The name of the object(string). + :param obj_location: The location of the object(string). + """ + self.log.info(f"Inserting object location: {obj_name} - {obj_location}") + self.obj_location.insert_one({"obj_name": obj_name, "obj_location": obj_location}) + def insert_obj_obj_relation(self, obj_name, second_obj_name): + """Insert object and its relation to another object into the Vision database. + + :param obj_name: The name of the object(string). + :param second_obj_name: The name of the second object(string). + """ + + self.log.info(f"Inserting object object relation: {obj_name} - {second_obj_name}") + self.obj_obj_relation.insert_one({"obj_name": obj_name, "second_obj_name": second_obj_name}) + def insert_obj_users(self, obj_name, user_name): + """Insert object and its users into the Vision database. + + :param obj_name: The name of the object(string). + :param user_name: The name of the user(string). + """ + + self.log.info(f"Inserting object users: {obj_name} - {user_name}") + self.obj_users.insert_one({"obj_name": obj_name, "user_name": user_name}) + + def insert_word_desc(self, word_name, word_desc): + """Insert word and its description into the NLP database. + + :param word_name: The name of the word(string). + :param word_desc: The description of the word(string). + """ + if word_desc != None: + self.log.info(f"Inserting word description: {word_name} - {word_desc}") + self.word_desc.insert_one({"word_name": word_name, "word_desc": word_desc}) + def insert_word_location(self, word_name, word_location): + """Insert word and its location into the NLP database. + + :param word_name: The name of the word(string). + :param word_location: The location of the word(string). + """ + + self.log.info(f"Inserting word location: {word_name} - {word_location}") + self.word_location.insert_one({"word_name": word_name, "word_location": word_location}) + def insert_word_obj_relation(self, word_name, obj_name): + """Insert word and its relation to an object into the NLP database. + + :param word_name: The name of the word(string). + :param obj_name: The name of the object(string). + """ + + self.log.info(f"Inserting word object relation: {word_name} - {obj_name}") + self.word_obj_relation.insert_one({"word_name": word_name, "word_relation": obj_name}) + + def search_obj_details(self, obj_name): + """Search for object all details in the Vision database. + + :param obj_name: The name of the object(string). + + :return: A dictionary containing the object details. + """ + + data = [] + self.log.info(f"Searching object details: {obj_name}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"obj_name": re.compile(rf"\b{obj_name}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_obj_desc(self, keyword): + """Search for object descriptions by keyword in the Vision database. + + :param keyword: The keyword to search for(string). + + :return: A dictionary containing the object descriptions. + """ + + data = [] + self.log.info(f"Searching object details by keyword: {keyword}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"obj_desc" : re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_obj_location(self, location): + """Search for object locations by location in the Vision database. + + :param location: The location to search for(string). + + :return: A dictionary containing the object locations. + """ + + data = [] + self.log.info(f"Searching object details by location: {location}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"obj_location" : re.compile(rf"\b{location}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_obj_user(self, user): + """Search for object users by user in the Vision database. + + :param user: The user to search for(string). + + :return: A dictionary containing the object users. + """ + + data = [] + self.log.info(f"Searching object details by user: {user}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"user_name" : re.compile(rf"\b{user}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + + + + + def search_word_details(self, word): + """Search for word details in the NLP database. + + :param word: The word to search for(string). + + :return: A dictionary containing the word details. + """ + + data = [] + self.log.info(f"Searching word details: {word}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"word_name" : re.compile(rf"\b{word}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_word_desc(self, keyword): + """Search for word descriptions by keyword in the NLP database. + + :param keyword: The keyword to search for(string). + + :return: A dictionary containing the word descriptions. + """ + + data = [] + self.log.info(f"Searching word details by keyword: {keyword}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"word_desc" : re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_word_location(self, location): + """Search for word locations by location in the NLP database. + + :param location: The location to search for(string). + + :return: A dictionary containing the word locations. + """ + + data = [] + self.log.info(f"Searching word details by location: {location}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"word_location" : re.compile(rf"\b{location}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_word_relation(self, relation): + """Search for word relations by relation in the NLP database. + + :param relation: The relation to search for(string). + + :return: A dictionary containing the word relations. + """ + + data = [] + self.log.info(f"Searching word details by relation: {relation}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find({"word_relation" : re.compile(rf"\b{relation}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + + def search_entire_db(self, term): + """Search for entire database by term in the NLP database. + + :param term: The term to search for(string). + + :return: A dictionary containing the entire database. + """ + + self._locals_search = locals() + + results = [] + + self.log.info(f"Searching entire database for: {term}") + + final_results = [] + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + for c in d.list_collection_names(): + self.log.info(f" ===> Collection: {c}") + exec(f"db_col_search = self.client.{d.name}.{c}", self._locals_search) + db_col_search = self._locals_search['db_col_search'] + + cursor = d[c].find({}) + keys = list(cursor.next().keys()) + + for key in keys: + self.log.info(f" ===> Key: {c}") + search = db_col_search.find({key : re.compile(rf"\b{term}\b", re.IGNORECASE)}) + results.append(search) + try: + a = search.next() + self.log.info(f" ===> Found: {a}") + final_results.append(a) + except: + self.log.info(f" ===> Found: None") + + return final_results + + + + def remove_duplicates(self): + """Remove duplicates from the Vision database. + """ + + self._locals = locals() + print(self.vision.ObjectDesc) + for d in self.dbs: + for i in d.list_collection_names(): + exec(f"db_col = self.client.{d.name}.{i}", self._locals) + db_col = self._locals['db_col'] + + repeated_val = "" + + if "vision" in d.name.lower(): + repeated_val = "obj_name" + print("vision") + if "nlp" in d.name.lower(): + repeated_val = "word_name" + print("nlp") + + replic = db_col.aggregate([ # Cursor with all duplicated documents + {'$group': { + '_id': {repeated_val: f'${repeated_val}'}, # Duplicated field + 'uniqueIDs': {'$addToSet': '$_id'}, + 'total': {'$sum': 1} + } + }, + {'$match': { + 'total': {'$gt': 1} # Holds how many duplicates for each group, if you need it. + } + } + ]) + # Result is a list of lists of ObjectsIds + for i in replic: + for idx, j in enumerate(i['uniqueIDs']): # It holds the ids of all duplicates + if idx != 0: # Jump over first element to keep it + db_col.delete_one({'_id': j}) + diff --git a/build_conventional/src/MAGIST/NeuralDB/__init__.py b/build_conventional/src/MAGIST/NeuralDB/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/TaskManagment/ThreadedQueue.py b/build_conventional/src/MAGIST/TaskManagment/ThreadedQueue.py new file mode 100644 index 0000000..5d879b0 --- /dev/null +++ b/build_conventional/src/MAGIST/TaskManagment/ThreadedQueue.py @@ -0,0 +1,123 @@ +"""Threaded Queue contains all necessary functions for a priority queue. + +The queue class contains methods to add, execute, thread, and process tasks in a queue based on a priority system. +""" + +import queue +import threading +import uuid +import numpy as np +import pathlib +import json + +from ..Utils.LogMaster.log_init import MainLogger + + +class MainPriorityQueue(): + """Main Priority Queue Class.""" + + def __init__(self, config): + """Initialize the queue. + + :param config: The config file(config.json). + """ + + self.q = queue.PriorityQueue() + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("QueueController") # Create a script specific logging instance + + self.function_returns = [] + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['task_management']: + try: + self.worker_threads = i["num_of_worker_threads"] + except KeyError: + pass + + def __worker(self): + """The worker thread. This actually executes the tasks in the queue. + """ + + while True: + items = self.q.get() + items = items[1] + func = items[0] + args = items[1:] + # print(f'Working on {args}') + + last_item = args[-1] # name + second_last_item = args[-2] # priority + third_last_item = args[-3] # guid + + args = args[:len(args) - 3] + + self.log.info(f'Received task: {last_item} with priority {second_last_item}. Unique ID assigned: {third_last_item}. Executing...') + [*returns] = [func(*args)] + self.log.info(f'Finished {last_item} successfully.') + self.q.task_done() + returns = np.array(returns) + self.function_returns.append([third_last_item, returns]) + # self.function_returns = np.squeeze(self.function_returns) + + def put_queue(self, function, *args, name="Unnamed", priority=None): + """Add a task to the queue. + + :param function: The function to be executed. NOTE: This must be in the form of Class.put_queue(function...), + not Class.put_queue(function()...). + :param args: The arguments to be passed to the function. This can be any number of args. + :param name: The name of the task. + :param priority: The priority of the task. + + :return: The unique ID of the task. + """ + + args = list(args) + + self.guid = uuid.uuid4() + + for i in args: + if i == name or i == priority: + raise ValueError( + "Name or priority cannot be used as argument. Please use priority= and name= in the function call.") + + self.q.put((priority, (function, *args, self.guid, priority, name))) + + return self.guid + + def detach_thread(self): + """Detach the thread from the main thread. + """ + + # Turn-on the worker thread. + for i in range(self.worker_threads): + threading.Thread(target=self.__worker, daemon=True).start() + self.log.info("Thread created and daemonized. Queue started...") + + def join_thread(self): + """Join the queue thread with main. + """ + + self.log.info("Attempting to join main thread...") + self.q.join() + self.log.info("Queue merge finished.") + + def search_results(self, query): + """Search the results for a specific task by ID. + + :param query: The unique ID of the task. NOTE: This must be a UUID object. + + :return: The results of the task. + """ + + r = self.function_returns + r = np.array(r) + r = r[r[:, 0] == query] + r = np.squeeze(r) + + return np.squeeze(r[1]) diff --git a/build_conventional/src/MAGIST/TaskManagment/__init__.py b/build_conventional/src/MAGIST/TaskManagment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/Utils/LogMaster/__init__.py b/build_conventional/src/MAGIST/Utils/LogMaster/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/Utils/LogMaster/log_init.py b/build_conventional/src/MAGIST/Utils/LogMaster/log_init.py new file mode 100644 index 0000000..051eb3f --- /dev/null +++ b/build_conventional/src/MAGIST/Utils/LogMaster/log_init.py @@ -0,0 +1,67 @@ +"""Establish major logger functions for individual scripts. + +MainLogger is the main class containing 1 main function that provides a unique logging instance to each script. +""" + +import logging +import json +import os, pathlib + +class MainLogger(): + # Logging Class + + def __init__(self, config): + """Initialize class and parse config + + :param config: A relative or absolute path to master config JSON file. + """ + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['paths']: + try: + self.log_dir = i["log_dir"] + except KeyError: + pass + for j in config['basic_variables']: + try: + self.verbose = j["verbose"] + except KeyError: + pass + + self.log_dir = pathlib.Path(self.log_dir) + self.log_dir = self.log_dir.resolve() # Find absolute path from a relative one. + self.log_dir = str(self.log_dir) + + def StandardLogger(self, name): + logger = logging.getLogger(name) + if not self.verbose: # Enable verbose depending on flag set by the config file. + logger.setLevel(logging.WARNING) + else: + logger.setLevel(logging.DEBUG) + # create file handler which logs even debug messages + try: + fh = logging.FileHandler(os.path.join(self.log_dir, 'complete.log')) + except FileNotFoundError: + os.makedirs(self.log_dir) + fh = logging.FileHandler(os.path.join(self.log_dir, 'complete.log')) + + # create console handler with a higher log level + error = logging.StreamHandler() + + # create formatter and add it to the handlers + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + fh.setFormatter(formatter) + error.setFormatter(formatter) + # add the handlers to the logger + logger.addHandler(fh) + logger.addHandler(error) + + logger.info(f"{name}'s LogMaster Instance Initialized Successfully ===> {os.path.join(self.log_dir, 'complete.log')}") + + return logger + + + diff --git a/build_conventional/src/MAGIST/Utils/WebScraper/__init__.py b/build_conventional/src/MAGIST/Utils/WebScraper/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/Utils/WebScraper/google.py b/build_conventional/src/MAGIST/Utils/WebScraper/google.py new file mode 100644 index 0000000..763e705 --- /dev/null +++ b/build_conventional/src/MAGIST/Utils/WebScraper/google.py @@ -0,0 +1,195 @@ +"""Provides basic functions for Google Reverse Image Search and scraping. + +GoogleScraper is the main class containing 2 functions: reverse_image_search and download_raw_img_dataset. The function +reverse_image_search takes a given image path and uses a Google API as well as some scraping to find the name of the +object. The function download_raw_img_dataset takes a given keyword and downloads a given quantity of images from Google +images. +""" + +import requests +from bs4 import BeautifulSoup +from selenium import webdriver +from selenium.webdriver.firefox.options import Options +from google_images_search import GoogleImagesSearch +import os +import pathlib, json +from googleapiclient.errors import HttpError + +from ..LogMaster.log_init import MainLogger + + +class GoogleScraper: + """Main Google Images scraping and downloading tool.""" + + def __init__(self, config): + """Initializes the class and authenticates Google Search API with credentials and parses config file. It also + initializes the logger. + + :param config: A relative or absolute path to master config JSON file. + :param dev_api_key DEPRECATED: API key acquired from Google Search API webpage. + :param project_cx_id DEPRECATED: The Search Engine ID provided by Google per Google Developer Project. + + Note: The CX ID is hard to find. To find it, first go to: http://www.google.com/cse/manage/all. Select your + project and the ID will be called: "Search engine ID". Go to this StackOverflow question and PyPi Post for more + info: https://stackoverflow.com/questions/6562125/getting-a-cx-id-for-custom-search-google-api-python & + https://pypi.org/project/Google-Images-Search/ + """ + + root_log = MainLogger(config) + self.log = root_log.StandardLogger("GoogleScraper") # Create a script specific logging instance + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['api_authentication']: + try: + google_conf = i["google"] + for j in google_conf: + try: + self.dev_api_key = j["api_key"] + except KeyError: + pass + try: + self.project_cx_id = j["project_cx"] + except KeyError: + pass + try: + self.GIS_verbose = j["GIS_downloader_verbose"] + except KeyError: + pass + except KeyError: + pass + + def __my_progressbar(self, url, progress): + """Defines custom progressbar to visualize the download process for the image downloader. + + :param url: The URL from which the downloader is currently downloading the image from. + :param progress: The percentage of progress in downloading the file. + :return: None + """ + self.log.info(url + ' ' + str(progress) + '%') + + # t = tqdm(total=100, desc=url) + # t.update(progress) + + # try: + # if(progress == 1): + # t = tqdm(total=100, desc=url) + # else: + # t.update(progress) + # except: + # pass + + def reverse_image_search(self, image_path): + """Takes a given image path and finds the object name using Google Reverse Image Search and scraping. + + :param image_path: Relative or absolute image path. + :return: Object name(String) + """ + filePath = image_path + + filePath = pathlib.Path(filePath) + filePath = filePath.resolve() # Find the absolute path from relative one. + filePath = str(filePath) + + searchUrl = 'http://www.google.com/searchbyimage/upload' + headers = { + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Change header to ensure that Google Search still functions + multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''} + + response = requests.post(searchUrl, files=multipart, allow_redirects=False) + fetchUrl = response.headers['Location'] + + options = Options() + options.add_argument("--disable-extensions") + options.add_argument("--disable-gpu") + options.add_argument("--no-sandbox") # linux only + options.add_argument("--headless") + options.headless = True # also works + nav = webdriver.Firefox(options=options) + nav.get(fetchUrl) + self.log.info("Selenium reverse search complete.") + + try: + soup = BeautifulSoup(nav.page_source, 'html.parser') + link = soup.find_all("a", {"class": "fKDtNb"})[0] + link = str(link) + start = link.find(">") + len(">") + end = link.find(" Loading data...") + train, test = self.load_data() + self.log.info("Automated Trainer --> Data loaded successfully.") + self.log.info("Automated Trainer --> Building model...") + self.compile_model() + self.log.info("Automated Trainer --> Model built successfully.") + self.log.info("Automated Trainer --> Setting up callbacks...") + self.callbacks_init() + self.log.info("Automated Trainer --> Callbacks setup successfully.") + self.log.info("Automated Trainer --> Training model...") + self.train() + self.log.info("Automated Trainer --> Training completed successfully.") + + +class MAGIST_CNN_Predictor(): + def __init__(self, config): + """Initializes the predictor and config. + + :param config: A dictionary containing the config.json. + """ + root_log = MainLogger(config) + self.log = root_log.StandardLogger("MAGIST_Lite_Predictor") # Create a script specific logging instance + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['tf_lite_detector']: + try: + self.TF_ckpt_path = i["TF_ckpt_path"] + except KeyError: + pass + try: + self.export_path = i["export_full_model"] + except KeyError: + pass + try: + self.input_image_size = i["input_image_size"] + except KeyError: + pass + try: + self.grayscale = i["grayscale"] + except KeyError: + pass + + self.export_path = pathlib.Path(self.export_path) + self.export_path = self.export_path.resolve() # Find absolute path from a relative one. + self.export_path = str(self.export_path) + + self.TF_ckpt_path = pathlib.Path(self.TF_ckpt_path) + self.TF_ckpt_path = self.TF_ckpt_path.resolve() # Find absolute path from a relative one. + self.TF_ckpt_path = str(self.TF_ckpt_path) + + self.imported = tf.keras.models.load_model(self.export_path, compile=False) + self.log.info("Model imported from {}.".format(self.export_path)) + + # latest = tf.train.latest_checkpoint(self.TF_ckpt_path) + + # self.imported.load_weights(latest) + self.imported.summary() + + def __load(self, filename): + """Loads a file from the given filename. + + :param filename: The filename to load. + + :return: The loaded image file as np.array. + """ + np_image = Image.open(filename) + np_image = np.array(np_image).astype('float32') / 255 + if self.grayscale: + np_image = transform.resize(np_image, (self.input_image_size[0], self.input_image_size[1], 1)) + else: + np_image = transform.resize(np_image, (self.input_image_size[0], self.input_image_size[1], 3)) + np_image = np.expand_dims(np_image, axis=0) + return np_image + + def img_prediction(self, img_path): + """Predicts the class of the given image. + + :param img_path: The path to the image. + + :return: The softmax array of predictions and the id of the prediction from class names. + """ + img_path = pathlib.Path(img_path) + img_path = img_path.resolve() # Find absolute path from a relative one. + img_path = str(img_path) + + image = self.__load(img_path) + p = self.imported.predict(image) + + p_id = np.array(p) + p_id = np.squeeze(p) + max = p_id.max() + id = np.where(p_id == max) + + return p, id + + def predict_from_batch_data(self, in_batch_ds): + """Predicts the class of the given batch of images. + + :param in_batch_ds: The batch of images. + + :return: The softmax array of predictions and the id of the prediction from class names. + """ + test_ds = in_batch_ds + + img, label = next(iter(test_ds)) + # print(len(img)) + self.log.info("Predicting on batch of {} images.".format(len(img))) + + ids = [] + for i in img: + i = np.array(i) + i = np.expand_dims(i, axis=0) + p = self.imported.predict(i) + p = np.array(p) + p = np.squeeze(p) + max = p.max() + id = np.where(p == max) + ids.append(id[0]) + return np.array(label), np.squeeze(np.array(ids)) diff --git a/build_conventional/src/MAGIST/Vision/FullySupervisedModels/__init__.py b/build_conventional/src/MAGIST/Vision/FullySupervisedModels/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/Vision/UnsupervisedModels/__init__.py b/build_conventional/src/MAGIST/Vision/UnsupervisedModels/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py b/build_conventional/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py new file mode 100644 index 0000000..863431b --- /dev/null +++ b/build_conventional/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py @@ -0,0 +1,112 @@ +""" + +""" + +import pandas as pd +import matplotlib.pyplot as plt +from skimage.io import imread, imshow, imsave +from skimage.transform import resize +from sklearn.cluster import KMeans +from skimage.util import img_as_uint, img_as_ubyte +from ...Utils.LogMaster.log_init import MainLogger +import pathlib, json + + +class RoughCluster(): + def __init__(self, config): + """Initialize the class, logger module and parse config.json. + + :param config: A relative or absolute path to master config JSON file. + """ + root_log = MainLogger(config) + self.log = root_log.StandardLogger("UnsupervisedClustering") # Create a script specific logging instance + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['basic_variables']: + try: + self.matplot = i["enable_matplot_display"] + except: + pass + + def unsupervised_clusters(self, n_of_clusters, img_location, img_size, masked_img_dir): + """Make, color, and crop unsupervised clusters. + + :param n_of_clusters: Number of expected objects. + :param img_location: Location of input image. + :param img_size: Resized shape of the image in pixels. This is represented as a tuple (length, height). Note: + This is NOT the current size of the image(it can be though), but rather the size it will be scaled down to for + efficient processing. + :param masked_img_dir: Location of the exported image directories. + :return: None + """ + + def image_to_pandas(image): + """ + + :param image: Location of input image. + + :return: Array of masked image locations. + """ + df = pd.DataFrame([image[:, :, 0].flatten(), + image[:, :, 1].flatten(), + image[:, :, 2].flatten()]).T + df.columns = ['Red_Channel', 'Green_Channel', 'Blue_Channel'] + return df + + img_location = pathlib.Path(img_location) + img_location = img_location.resolve() # Find the absolute path from relative one. + img_location = str(img_location) + + masked_img_dir = pathlib.Path(masked_img_dir) + masked_img_dir = masked_img_dir.resolve() # Find the absolute path from relative one. + masked_img_dir = str(masked_img_dir) + + img = imread(img_location) + img = resize(img, img_size) + plt.figure(num=None, figsize=(8, 6), dpi=80) + if (self.matplot): + imshow(img) + + self.log.info("Input image resized and configured for clustering computation.") + + df_img = image_to_pandas(img) + + kmeans = KMeans(n_clusters=n_of_clusters, random_state=0).fit(df_img) + self.log.info("Image clustering complete!") + + result = kmeans.labels_.reshape(img.shape[0], img.shape[1]) + if (self.matplot): + imshow(result, cmap='viridis') + plt.show() + + fig, axes = plt.subplots(1, n_of_clusters, figsize=(15, 12)) + + clustered_img = [] + + for n, ax in enumerate(axes.flatten()): + img2 = imread(img_location) + img2 = resize(img2, img_size) + img2[:, :, 0] = img2[:, :, 0] * (result == [n]) # Disabling pixels of certain type + img2[:, :, 1] = img2[:, :, 1] * (result == [n]) # Disabling pixels of certain type + img2[:, :, 2] = img2[:, :, 2] * (result == [n]) # Disabling pixels of certain type + unit_img = img_as_ubyte(img2) + try: + imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) + except FileNotFoundError: + pathlib.Path(masked_img_dir).mkdir(parents=True, exist_ok=True) + imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) + clustered_img.append(f'{masked_img_dir}/masked{n}.jpg') + ax.imshow(img2) + ax.set_axis_off() + fig.tight_layout() + if (self.matplot): + plt.show() + + return clustered_img + +# unsupervised_clusters(3, 'test.jpg', (540, 480), "./Masks") +# unsupervised_clusters(2, 'masked2.jpg', (540, 480), ".") diff --git a/build_conventional/src/MAGIST/Vision/__init__.py b/build_conventional/src/MAGIST/Vision/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_conventional/src/MAGIST/__init__.py b/build_conventional/src/MAGIST/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/poetry.lock b/poetry.lock index a4f6631..c2e1ec5 100644 --- a/poetry.lock +++ b/poetry.lock @@ -83,7 +83,7 @@ pycparser = "*" [[package]] name = "charset-normalizer" -version = "2.1.0" +version = "2.1.1" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." category = "main" optional = false @@ -108,25 +108,6 @@ category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -[[package]] -name = "cryptography" -version = "37.0.4" -description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." -category = "main" -optional = false -python-versions = ">=3.6" - -[package.dependencies] -cffi = ">=1.12" - -[package.extras] -docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"] -docstest = ["pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"] -pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"] -sdist = ["setuptools_rust (>=0.11.4)"] -ssh = ["bcrypt (>=3.1.5)"] -test = ["pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] - [[package]] name = "cycler" version = "0.11.0" @@ -145,7 +126,7 @@ python-versions = "*" [[package]] name = "fonttools" -version = "4.34.4" +version = "4.37.1" description = "Tools to manipulate font files" category = "main" optional = false @@ -207,7 +188,7 @@ uritemplate = ">=3.0.1,<5" [[package]] name = "google-auth" -version = "2.10.0" +version = "2.11.0" description = "Google Authentication Library" category = "main" optional = false @@ -448,7 +429,7 @@ python-versions = ">=3.7" [[package]] name = "matplotlib" -version = "3.5.2" +version = "3.5.3" description = "Python plotting package" category = "main" optional = false @@ -463,11 +444,11 @@ packaging = ">=20.0" pillow = ">=6.2.0" pyparsing = ">=2.2.1" python-dateutil = ">=2.7" -setuptools_scm = ">=4" +setuptools_scm = ">=4,<7" [[package]] name = "networkx" -version = "2.8.5" +version = "2.8.6" description = "Python package for creating and manipulating graphs and networks" category = "main" optional = false @@ -475,14 +456,14 @@ python-versions = ">=3.8" [package.extras] default = ["numpy (>=1.19)", "scipy (>=1.8)", "matplotlib (>=3.4)", "pandas (>=1.3)"] -developer = ["pre-commit (>=2.19)", "mypy (>=0.960)"] +developer = ["pre-commit (>=2.20)", "mypy (>=0.961)"] doc = ["sphinx (>=5)", "pydata-sphinx-theme (>=0.9)", "sphinx-gallery (>=0.10)", "numpydoc (>=1.4)", "pillow (>=9.1)", "nb2plots (>=0.6)", "texext (>=0.6.6)"] extra = ["lxml (>=4.6)", "pygraphviz (>=1.9)", "pydot (>=1.4.2)", "sympy (>=1.10)"] test = ["pytest (>=7.1)", "pytest-cov (>=3.0)", "codecov (>=2.1)"] [[package]] name = "numpy" -version = "1.23.1" +version = "1.23.2" description = "NumPy is the fundamental package for array computing with Python." category = "main" optional = false @@ -501,6 +482,22 @@ rsa = ["cryptography (>=3.0.0)"] signals = ["blinker (>=1.4.0)"] signedtoken = ["cryptography (>=3.0.0)", "pyjwt (>=2.0.0,<3)"] +[[package]] +name = "opencv-python" +version = "4.6.0.66" +description = "Wrapper package for OpenCV python bindings." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +numpy = [ + {version = ">=1.21.2", markers = "python_version >= \"3.10\" or python_version >= \"3.6\" and platform_system == \"Darwin\" and platform_machine == \"arm64\""}, + {version = ">=1.19.3", markers = "python_version >= \"3.6\" and platform_system == \"Linux\" and platform_machine == \"aarch64\" or python_version >= \"3.9\""}, + {version = ">=1.14.5", markers = "python_version >= \"3.7\""}, + {version = ">=1.17.3", markers = "python_version >= \"3.8\""}, +] + [[package]] name = "opt-einsum" version = "3.3.0" @@ -637,21 +634,6 @@ snappy = ["python-snappy"] srv = ["dnspython (>=1.16.0,<3.0.0)"] zstd = ["zstandard"] -[[package]] -name = "pyopenssl" -version = "22.0.0" -description = "Python wrapper module around the OpenSSL library" -category = "main" -optional = false -python-versions = ">=3.6" - -[package.dependencies] -cryptography = ">=35.0" - -[package.extras] -docs = ["sphinx", "sphinx-rtd-theme"] -test = ["flaky", "pretend", "pytest (>=3.0.1)"] - [[package]] name = "pyparsing" version = "3.0.9" @@ -696,7 +678,7 @@ requests = ">=2.19.1" [[package]] name = "pytz" -version = "2022.1" +version = "2022.2.1" description = "World timezone definitions, modern and historical" category = "main" optional = false @@ -803,7 +785,7 @@ benchmark = ["memory-profiler (>=0.57.0)", "pandas (>=1.0.5)", "matplotlib (>=3. [[package]] name = "scipy" -version = "1.9.0" +version = "1.9.1" description = "SciPy: Scientific Library for Python" category = "main" optional = false @@ -814,29 +796,29 @@ numpy = ">=1.18.5,<1.25.0" [[package]] name = "selenium" -version = "4.4.0" +version = "4.4.3" description = "" category = "main" optional = false python-versions = "~=3.7" [package.dependencies] +certifi = ">=2021.10.8" trio = ">=0.17,<1.0" trio-websocket = ">=0.9,<1.0" -urllib3 = {version = ">=1.26,<2.0", extras = ["secure", "socks"]} +urllib3 = {version = ">=1.26,<2.0", extras = ["socks"]} [[package]] name = "setuptools-scm" -version = "7.0.5" +version = "6.4.2" description = "the blessed package to manage your versions by scm tags" category = "main" optional = false -python-versions = ">=3.7" +python-versions = ">=3.6" [package.dependencies] packaging = ">=20.0" tomli = ">=1.0.0" -typing-extensions = "*" [package.extras] test = ["pytest (>=6.2)", "virtualenv (>20)"] @@ -991,7 +973,7 @@ python-versions = ">=3.6" [[package]] name = "tifffile" -version = "2022.8.8" +version = "2022.8.12" description = "Read and write TIFF files" category = "main" optional = false @@ -1076,22 +1058,18 @@ python-versions = ">=3.6" [[package]] name = "urllib3" -version = "1.26.11" +version = "1.26.12" description = "HTTP library with thread-safe connection pooling, file post, and more." category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" [package.dependencies] -certifi = {version = "*", optional = true, markers = "extra == \"secure\""} -cryptography = {version = ">=1.3.4", optional = true, markers = "extra == \"secure\""} -idna = {version = ">=2.0.0", optional = true, markers = "extra == \"secure\""} -pyOpenSSL = {version = ">=0.14", optional = true, markers = "extra == \"secure\""} PySocks = {version = ">=1.5.6,<1.5.7 || >1.5.7,<2.0", optional = true, markers = "extra == \"socks\""} [package.extras] brotli = ["brotlicffi (>=0.8.0)", "brotli (>=1.0.9)", "brotlipy (>=0.6.0)"] -secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "ipaddress"] +secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "urllib3-secure-extra", "ipaddress"] socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] [[package]] @@ -1130,7 +1108,7 @@ python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" [[package]] name = "wsproto" -version = "1.1.0" +version = "1.2.0" description = "WebSockets state-machine based protocol implementation" category = "main" optional = false @@ -1142,7 +1120,7 @@ h11 = ">=0.9.0,<1" [metadata] lock-version = "1.1" python-versions = ">=3.10,<3.11" -content-hash = "0f6e9bb3d4983069aab2f07cbdc3af412da7921a6126c15eb156574fa8bf8602" +content-hash = "3c9b69c82e85c49d57c11e4f396ba69d6f88e977e21b47f714bb6d0ce58b5923" [metadata.files] absl-py = [ @@ -1240,8 +1218,8 @@ cffi = [ {file = "cffi-1.15.1.tar.gz", hash = "sha256:d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9"}, ] charset-normalizer = [ - {file = "charset-normalizer-2.1.0.tar.gz", hash = "sha256:575e708016ff3a5e3681541cb9d79312c416835686d054a23accb873b254f413"}, - {file = "charset_normalizer-2.1.0-py3-none-any.whl", hash = "sha256:5189b6f22b01957427f35b6a08d9a0bc45b46d3788ef5a92e978433c7a35f8a5"}, + {file = "charset-normalizer-2.1.1.tar.gz", hash = "sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845"}, + {file = "charset_normalizer-2.1.1-py3-none-any.whl", hash = "sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f"}, ] click = [ {file = "click-7.1.2-py2.py3-none-any.whl", hash = "sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc"}, @@ -1251,30 +1229,6 @@ colorama = [ {file = "colorama-0.4.5-py2.py3-none-any.whl", hash = "sha256:854bf444933e37f5824ae7bfc1e98d5bce2ebe4160d46b5edf346a89358e99da"}, {file = "colorama-0.4.5.tar.gz", hash = "sha256:e6c6b4334fc50988a639d9b98aa429a0b57da6e17b9a44f0451f930b6967b7a4"}, ] -cryptography = [ - {file = "cryptography-37.0.4-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:549153378611c0cca1042f20fd9c5030d37a72f634c9326e225c9f666d472884"}, - {file = "cryptography-37.0.4-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:a958c52505c8adf0d3822703078580d2c0456dd1d27fabfb6f76fe63d2971cd6"}, - {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f721d1885ecae9078c3f6bbe8a88bc0786b6e749bf32ccec1ef2b18929a05046"}, - {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:3d41b965b3380f10e4611dbae366f6dc3cefc7c9ac4e8842a806b9672ae9add5"}, - {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:80f49023dd13ba35f7c34072fa17f604d2f19bf0989f292cedf7ab5770b87a0b"}, - {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2dcb0b3b63afb6df7fd94ec6fbddac81b5492513f7b0436210d390c14d46ee8"}, - {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:b7f8dd0d4c1f21759695c05a5ec8536c12f31611541f8904083f3dc582604280"}, - {file = "cryptography-37.0.4-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:30788e070800fec9bbcf9faa71ea6d8068f5136f60029759fd8c3efec3c9dcb3"}, - {file = "cryptography-37.0.4-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:190f82f3e87033821828f60787cfa42bff98404483577b591429ed99bed39d59"}, - {file = "cryptography-37.0.4-cp36-abi3-win32.whl", hash = "sha256:b62439d7cd1222f3da897e9a9fe53bbf5c104fff4d60893ad1355d4c14a24157"}, - {file = "cryptography-37.0.4-cp36-abi3-win_amd64.whl", hash = "sha256:f7a6de3e98771e183645181b3627e2563dcde3ce94a9e42a3f427d2255190327"}, - {file = "cryptography-37.0.4-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bc95ed67b6741b2607298f9ea4932ff157e570ef456ef7ff0ef4884a134cc4b"}, - {file = "cryptography-37.0.4-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:f8c0a6e9e1dd3eb0414ba320f85da6b0dcbd543126e30fcc546e7372a7fbf3b9"}, - {file = "cryptography-37.0.4-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:e007f052ed10cc316df59bc90fbb7ff7950d7e2919c9757fd42a2b8ecf8a5f67"}, - {file = "cryptography-37.0.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bc997818309f56c0038a33b8da5c0bfbb3f1f067f315f9abd6fc07ad359398d"}, - {file = "cryptography-37.0.4-pp38-pypy38_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:d204833f3c8a33bbe11eda63a54b1aad7aa7456ed769a982f21ec599ba5fa282"}, - {file = "cryptography-37.0.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:75976c217f10d48a8b5a8de3d70c454c249e4b91851f6838a4e48b8f41eb71aa"}, - {file = "cryptography-37.0.4-pp39-pypy39_pp73-macosx_10_10_x86_64.whl", hash = "sha256:7099a8d55cd49b737ffc99c17de504f2257e3787e02abe6d1a6d136574873441"}, - {file = "cryptography-37.0.4-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2be53f9f5505673eeda5f2736bea736c40f051a739bfae2f92d18aed1eb54596"}, - {file = "cryptography-37.0.4-pp39-pypy39_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:91ce48d35f4e3d3f1d83e29ef4a9267246e6a3be51864a5b7d2247d5086fa99a"}, - {file = "cryptography-37.0.4-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:4c590ec31550a724ef893c50f9a97a0c14e9c851c85621c5650d699a7b88f7ab"}, - {file = "cryptography-37.0.4.tar.gz", hash = "sha256:63f9c17c0e2474ccbebc9302ce2f07b55b3b3fcb211ded18a42d5764f5c10a82"}, -] cycler = [ {file = "cycler-0.11.0-py3-none-any.whl", hash = "sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3"}, {file = "cycler-0.11.0.tar.gz", hash = "sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f"}, @@ -1284,8 +1238,8 @@ flatbuffers = [ {file = "flatbuffers-1.12.tar.gz", hash = "sha256:63bb9a722d5e373701913e226135b28a6f6ac200d5cc7b4d919fa38d73b44610"}, ] fonttools = [ - {file = "fonttools-4.34.4-py3-none-any.whl", hash = "sha256:d73f25b283cd8033367451122aa868a23de0734757a01984e4b30b18b9050c72"}, - {file = "fonttools-4.34.4.zip", hash = "sha256:9a1c52488045cd6c6491fd07711a380f932466e317cb8e016fc4e99dc7eac2f0"}, + {file = "fonttools-4.37.1-py3-none-any.whl", hash = "sha256:fff6b752e326c15756c819fe2fe7ceab69f96a1dbcfe8911d0941cdb49905007"}, + {file = "fonttools-4.37.1.zip", hash = "sha256:4606e1a88ee1f6699d182fea9511bd9a8a915d913eab4584e5226da1180fcce7"}, ] gast = [ {file = "gast-0.4.0-py3-none-any.whl", hash = "sha256:b7adcdd5adbebf1adf17378da5ba3f543684dbec47b1cda1f3997e573cd542c4"}, @@ -1300,8 +1254,8 @@ google-api-python-client = [ {file = "google_api_python_client-2.48.0-py2.py3-none-any.whl", hash = "sha256:4527f7b8518a795624ab68da412d55628f83b98c67dd6a5d6edf725454f8b30b"}, ] google-auth = [ - {file = "google-auth-2.10.0.tar.gz", hash = "sha256:7904dbd44b745c7323fef29565adee2fe7ff48473e2d94443aced40b0404a395"}, - {file = "google_auth-2.10.0-py2.py3-none-any.whl", hash = "sha256:1deba4a54f95ef67b4139eaf5c20eaa7047215eec9f6a2344599b8596db8863b"}, + {file = "google-auth-2.11.0.tar.gz", hash = "sha256:ed65ecf9f681832298e29328e1ef0a3676e3732b2e56f41532d45f70a22de0fb"}, + {file = "google_auth-2.11.0-py2.py3-none-any.whl", hash = "sha256:be62acaae38d0049c21ca90f27a23847245c9f161ff54ede13af2cb6afecbac9"}, ] google-auth-httplib2 = [ {file = "google-auth-httplib2-0.1.0.tar.gz", hash = "sha256:a07c39fd632becacd3f07718dfd6021bf396978f03ad3ce4321d060015cc30ac"}, @@ -1525,74 +1479,89 @@ markupsafe = [ {file = "MarkupSafe-2.1.1.tar.gz", hash = "sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b"}, ] matplotlib = [ - {file = "matplotlib-3.5.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:03bbb3f5f78836855e127b5dab228d99551ad0642918ccbf3067fcd52ac7ac5e"}, - {file = "matplotlib-3.5.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:49a5938ed6ef9dda560f26ea930a2baae11ea99e1c2080c8714341ecfda72a89"}, - {file = "matplotlib-3.5.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:77157be0fc4469cbfb901270c205e7d8adb3607af23cef8bd11419600647ceed"}, - {file = "matplotlib-3.5.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5844cea45d804174bf0fac219b4ab50774e504bef477fc10f8f730ce2d623441"}, - {file = "matplotlib-3.5.2-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c87973ddec10812bddc6c286b88fdd654a666080fbe846a1f7a3b4ba7b11ab78"}, - {file = "matplotlib-3.5.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4a05f2b37222319753a5d43c0a4fd97ed4ff15ab502113e3f2625c26728040cf"}, - {file = "matplotlib-3.5.2-cp310-cp310-win32.whl", hash = "sha256:9776e1a10636ee5f06ca8efe0122c6de57ffe7e8c843e0fb6e001e9d9256ec95"}, - {file = "matplotlib-3.5.2-cp310-cp310-win_amd64.whl", hash = "sha256:b4fedaa5a9aa9ce14001541812849ed1713112651295fdddd640ea6620e6cf98"}, - {file = "matplotlib-3.5.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ee175a571e692fc8ae8e41ac353c0e07259113f4cb063b0ec769eff9717e84bb"}, - {file = "matplotlib-3.5.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e8bda1088b941ead50caabd682601bece983cadb2283cafff56e8fcddbf7d7f"}, - {file = "matplotlib-3.5.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:9480842d5aadb6e754f0b8f4ebeb73065ac8be1855baa93cd082e46e770591e9"}, - {file = "matplotlib-3.5.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6c623b355d605a81c661546af7f24414165a8a2022cddbe7380a31a4170fa2e9"}, - {file = "matplotlib-3.5.2-cp37-cp37m-win32.whl", hash = "sha256:a91426ae910819383d337ba0dc7971c7cefdaa38599868476d94389a329e599b"}, - {file = "matplotlib-3.5.2-cp37-cp37m-win_amd64.whl", hash = "sha256:c4b82c2ae6d305fcbeb0eb9c93df2602ebd2f174f6e8c8a5d92f9445baa0c1d3"}, - {file = "matplotlib-3.5.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:ebc27ad11df3c1661f4677a7762e57a8a91dd41b466c3605e90717c9a5f90c82"}, - {file = "matplotlib-3.5.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:5a32ea6e12e80dedaca2d4795d9ed40f97bfa56e6011e14f31502fdd528b9c89"}, - {file = "matplotlib-3.5.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:2a0967d4156adbd0d46db06bc1a877f0370bce28d10206a5071f9ecd6dc60b79"}, - {file = "matplotlib-3.5.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e2b696699386766ef171a259d72b203a3c75d99d03ec383b97fc2054f52e15cf"}, - {file = "matplotlib-3.5.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7f409716119fa39b03da3d9602bd9b41142fab7a0568758cd136cd80b1bf36c8"}, - {file = "matplotlib-3.5.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:b8d3f4e71e26307e8c120b72c16671d70c5cd08ae412355c11254aa8254fb87f"}, - {file = "matplotlib-3.5.2-cp38-cp38-win32.whl", hash = "sha256:b6c63cd01cad0ea8704f1fd586e9dc5777ccedcd42f63cbbaa3eae8dd41172a1"}, - {file = "matplotlib-3.5.2-cp38-cp38-win_amd64.whl", hash = "sha256:75c406c527a3aa07638689586343f4b344fcc7ab1f79c396699eb550cd2b91f7"}, - {file = "matplotlib-3.5.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:4a44cdfdb9d1b2f18b1e7d315eb3843abb097869cd1ef89cfce6a488cd1b5182"}, - {file = "matplotlib-3.5.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3d8e129af95b156b41cb3be0d9a7512cc6d73e2b2109f82108f566dbabdbf377"}, - {file = "matplotlib-3.5.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:364e6bca34edc10a96aa3b1d7cd76eb2eea19a4097198c1b19e89bee47ed5781"}, - {file = "matplotlib-3.5.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ea75df8e567743207e2b479ba3d8843537be1c146d4b1e3e395319a4e1a77fe9"}, - {file = "matplotlib-3.5.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:44c6436868186564450df8fd2fc20ed9daaef5caad699aa04069e87099f9b5a8"}, - {file = "matplotlib-3.5.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7d7705022df2c42bb02937a2a824f4ec3cca915700dd80dc23916af47ff05f1a"}, - {file = "matplotlib-3.5.2-cp39-cp39-win32.whl", hash = "sha256:ee0b8e586ac07f83bb2950717e66cb305e2859baf6f00a9c39cc576e0ce9629c"}, - {file = "matplotlib-3.5.2-cp39-cp39-win_amd64.whl", hash = "sha256:c772264631e5ae61f0bd41313bbe48e1b9bcc95b974033e1118c9caa1a84d5c6"}, - {file = "matplotlib-3.5.2-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:751d3815b555dcd6187ad35b21736dc12ce6925fc3fa363bbc6dc0f86f16484f"}, - {file = "matplotlib-3.5.2-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:31fbc2af27ebb820763f077ec7adc79b5a031c2f3f7af446bd7909674cd59460"}, - {file = "matplotlib-3.5.2-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:4fa28ca76ac5c2b2d54bc058b3dad8e22ee85d26d1ee1b116a6fd4d2277b6a04"}, - {file = "matplotlib-3.5.2-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:24173c23d1bcbaed5bf47b8785d27933a1ac26a5d772200a0f3e0e38f471b001"}, - {file = "matplotlib-3.5.2.tar.gz", hash = "sha256:48cf850ce14fa18067f2d9e0d646763681948487a8080ec0af2686468b4607a2"}, + {file = "matplotlib-3.5.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:a206a1b762b39398efea838f528b3a6d60cdb26fe9d58b48265787e29cd1d693"}, + {file = "matplotlib-3.5.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:cd45a6f3e93a780185f70f05cf2a383daed13c3489233faad83e81720f7ede24"}, + {file = "matplotlib-3.5.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d62880e1f60e5a30a2a8484432bcb3a5056969dc97258d7326ad465feb7ae069"}, + {file = "matplotlib-3.5.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9ab29589cef03bc88acfa3a1490359000c18186fc30374d8aa77d33cc4a51a4a"}, + {file = "matplotlib-3.5.3-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2886cc009f40e2984c083687251821f305d811d38e3df8ded414265e4583f0c5"}, + {file = "matplotlib-3.5.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c995f7d9568f18b5db131ab124c64e51b6820a92d10246d4f2b3f3a66698a15b"}, + {file = "matplotlib-3.5.3-cp310-cp310-win32.whl", hash = "sha256:6bb93a0492d68461bd458eba878f52fdc8ac7bdb6c4acdfe43dba684787838c2"}, + {file = "matplotlib-3.5.3-cp310-cp310-win_amd64.whl", hash = "sha256:2e6d184ebe291b9e8f7e78bbab7987d269c38ea3e062eace1fe7d898042ef804"}, + {file = "matplotlib-3.5.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:6ea6aef5c4338e58d8d376068e28f80a24f54e69f09479d1c90b7172bad9f25b"}, + {file = "matplotlib-3.5.3-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:839d47b8ead7ad9669aaacdbc03f29656dc21f0d41a6fea2d473d856c39c8b1c"}, + {file = "matplotlib-3.5.3-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3b4fa56159dc3c7f9250df88f653f085068bcd32dcd38e479bba58909254af7f"}, + {file = "matplotlib-3.5.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:94ff86af56a3869a4ae26a9637a849effd7643858a1a04dd5ee50e9ab75069a7"}, + {file = "matplotlib-3.5.3-cp37-cp37m-win32.whl", hash = "sha256:35a8ad4dddebd51f94c5d24bec689ec0ec66173bf614374a1244c6241c1595e0"}, + {file = "matplotlib-3.5.3-cp37-cp37m-win_amd64.whl", hash = "sha256:43e9d3fa077bf0cc95ded13d331d2156f9973dce17c6f0c8b49ccd57af94dbd9"}, + {file = "matplotlib-3.5.3-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:22227c976ad4dc8c5a5057540421f0d8708c6560744ad2ad638d48e2984e1dbc"}, + {file = "matplotlib-3.5.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:bf618a825deb6205f015df6dfe6167a5d9b351203b03fab82043ae1d30f16511"}, + {file = "matplotlib-3.5.3-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:9befa5954cdbc085e37d974ff6053da269474177921dd61facdad8023c4aeb51"}, + {file = "matplotlib-3.5.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f3840c280ebc87a48488a46f760ea1c0c0c83fcf7abbe2e6baf99d033fd35fd8"}, + {file = "matplotlib-3.5.3-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dacddf5bfcec60e3f26ec5c0ae3d0274853a258b6c3fc5ef2f06a8eb23e042be"}, + {file = "matplotlib-3.5.3-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:b428076a55fb1c084c76cb93e68006f27d247169f056412607c5c88828d08f88"}, + {file = "matplotlib-3.5.3-cp38-cp38-win32.whl", hash = "sha256:874df7505ba820e0400e7091199decf3ff1fde0583652120c50cd60d5820ca9a"}, + {file = "matplotlib-3.5.3-cp38-cp38-win_amd64.whl", hash = "sha256:b28de401d928890187c589036857a270a032961411934bdac4cf12dde3d43094"}, + {file = "matplotlib-3.5.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3211ba82b9f1518d346f6309df137b50c3dc4421b4ed4815d1d7eadc617f45a1"}, + {file = "matplotlib-3.5.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6fe807e8a22620b4cd95cfbc795ba310dc80151d43b037257250faf0bfcd82bc"}, + {file = "matplotlib-3.5.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5c096363b206a3caf43773abebdbb5a23ea13faef71d701b21a9c27fdcef72f4"}, + {file = "matplotlib-3.5.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0bcdfcb0f976e1bac6721d7d457c17be23cf7501f977b6a38f9d38a3762841f7"}, + {file = "matplotlib-3.5.3-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1e64ac9be9da6bfff0a732e62116484b93b02a0b4d4b19934fb4f8e7ad26ad6a"}, + {file = "matplotlib-3.5.3-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:73dd93dc35c85dece610cca8358003bf0760d7986f70b223e2306b4ea6d1406b"}, + {file = "matplotlib-3.5.3-cp39-cp39-win32.whl", hash = "sha256:879c7e5fce4939c6aa04581dfe08d57eb6102a71f2e202e3314d5fbc072fd5a0"}, + {file = "matplotlib-3.5.3-cp39-cp39-win_amd64.whl", hash = "sha256:ab8d26f07fe64f6f6736d635cce7bfd7f625320490ed5bfc347f2cdb4fae0e56"}, + {file = "matplotlib-3.5.3-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:99482b83ebf4eb6d5fc6813d7aacdefdd480f0d9c0b52dcf9f1cc3b2c4b3361a"}, + {file = "matplotlib-3.5.3-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:f814504e459c68118bf2246a530ed953ebd18213dc20e3da524174d84ed010b2"}, + {file = "matplotlib-3.5.3-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:57f1b4e69f438a99bb64d7f2c340db1b096b41ebaa515cf61ea72624279220ce"}, + {file = "matplotlib-3.5.3-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:d2484b350bf3d32cae43f85dcfc89b3ed7bd2bcd781ef351f93eb6fb2cc483f9"}, + {file = "matplotlib-3.5.3.tar.gz", hash = "sha256:339cac48b80ddbc8bfd05daae0a3a73414651a8596904c2a881cfd1edb65f26c"}, ] networkx = [ - {file = "networkx-2.8.5-py3-none-any.whl", hash = "sha256:a762f4b385692d9c3a6f2912d058d76d29a827deaedf9e63ed14d397b8030687"}, - {file = "networkx-2.8.5.tar.gz", hash = "sha256:15a7b81a360791c458c55a417418ea136c13378cfdc06a2dcdc12bd2f9cf09c1"}, + {file = "networkx-2.8.6-py3-none-any.whl", hash = "sha256:2a30822761f34d56b9a370d96a4bf4827a535f5591a4078a453425caeba0c5bb"}, + {file = "networkx-2.8.6.tar.gz", hash = "sha256:bd2b7730300860cbd2dafe8e5af89ff5c9a65c3975b352799d87a6238b4301a6"}, ] numpy = [ - {file = "numpy-1.23.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b15c3f1ed08df4980e02cc79ee058b788a3d0bef2fb3c9ca90bb8cbd5b8a3a04"}, - {file = "numpy-1.23.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9ce242162015b7e88092dccd0e854548c0926b75c7924a3495e02c6067aba1f5"}, - {file = "numpy-1.23.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e0d7447679ae9a7124385ccf0ea990bb85bb869cef217e2ea6c844b6a6855073"}, - {file = "numpy-1.23.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3119daed207e9410eaf57dcf9591fdc68045f60483d94956bee0bfdcba790953"}, - {file = "numpy-1.23.1-cp310-cp310-win32.whl", hash = "sha256:3ab67966c8d45d55a2bdf40701536af6443763907086c0a6d1232688e27e5447"}, - {file = "numpy-1.23.1-cp310-cp310-win_amd64.whl", hash = "sha256:1865fdf51446839ca3fffaab172461f2b781163f6f395f1aed256b1ddc253622"}, - {file = "numpy-1.23.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:aeba539285dcf0a1ba755945865ec61240ede5432df41d6e29fab305f4384db2"}, - {file = "numpy-1.23.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7e8229f3687cdadba2c4faef39204feb51ef7c1a9b669247d49a24f3e2e1617c"}, - {file = "numpy-1.23.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68b69f52e6545af010b76516f5daaef6173e73353e3295c5cb9f96c35d755641"}, - {file = "numpy-1.23.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1408c3527a74a0209c781ac82bde2182b0f0bf54dea6e6a363fe0cc4488a7ce7"}, - {file = "numpy-1.23.1-cp38-cp38-win32.whl", hash = "sha256:47f10ab202fe4d8495ff484b5561c65dd59177949ca07975663f4494f7269e3e"}, - {file = "numpy-1.23.1-cp38-cp38-win_amd64.whl", hash = "sha256:37e5ebebb0eb54c5b4a9b04e6f3018e16b8ef257d26c8945925ba8105008e645"}, - {file = "numpy-1.23.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:173f28921b15d341afadf6c3898a34f20a0569e4ad5435297ba262ee8941e77b"}, - {file = "numpy-1.23.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:876f60de09734fbcb4e27a97c9a286b51284df1326b1ac5f1bf0ad3678236b22"}, - {file = "numpy-1.23.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:35590b9c33c0f1c9732b3231bb6a72d1e4f77872390c47d50a615686ae7ed3fd"}, - {file = "numpy-1.23.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a35c4e64dfca659fe4d0f1421fc0f05b8ed1ca8c46fb73d9e5a7f175f85696bb"}, - {file = "numpy-1.23.1-cp39-cp39-win32.whl", hash = "sha256:c2f91f88230042a130ceb1b496932aa717dcbd665350beb821534c5c7e15881c"}, - {file = "numpy-1.23.1-cp39-cp39-win_amd64.whl", hash = "sha256:37ece2bd095e9781a7156852e43d18044fd0d742934833335599c583618181b9"}, - {file = "numpy-1.23.1-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:8002574a6b46ac3b5739a003b5233376aeac5163e5dcd43dd7ad062f3e186129"}, - {file = "numpy-1.23.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d732d17b8a9061540a10fda5bfeabca5785700ab5469a5e9b93aca5e2d3a5fb"}, - {file = "numpy-1.23.1-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:55df0f7483b822855af67e38fb3a526e787adf189383b4934305565d71c4b148"}, - {file = "numpy-1.23.1.tar.gz", hash = "sha256:d748ef349bfef2e1194b59da37ed5a29c19ea8d7e6342019921ba2ba4fd8b624"}, + {file = "numpy-1.23.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e603ca1fb47b913942f3e660a15e55a9ebca906857edfea476ae5f0fe9b457d5"}, + {file = "numpy-1.23.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:633679a472934b1c20a12ed0c9a6c9eb167fbb4cb89031939bfd03dd9dbc62b8"}, + {file = "numpy-1.23.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:17e5226674f6ea79e14e3b91bfbc153fdf3ac13f5cc54ee7bc8fdbe820a32da0"}, + {file = "numpy-1.23.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bdc02c0235b261925102b1bd586579b7158e9d0d07ecb61148a1799214a4afd5"}, + {file = "numpy-1.23.2-cp310-cp310-win32.whl", hash = "sha256:df28dda02c9328e122661f399f7655cdcbcf22ea42daa3650a26bce08a187450"}, + {file = "numpy-1.23.2-cp310-cp310-win_amd64.whl", hash = "sha256:8ebf7e194b89bc66b78475bd3624d92980fca4e5bb86dda08d677d786fefc414"}, + {file = "numpy-1.23.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:dc76bca1ca98f4b122114435f83f1fcf3c0fe48e4e6f660e07996abf2f53903c"}, + {file = "numpy-1.23.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ecfdd68d334a6b97472ed032b5b37a30d8217c097acfff15e8452c710e775524"}, + {file = "numpy-1.23.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5593f67e66dea4e237f5af998d31a43e447786b2154ba1ad833676c788f37cde"}, + {file = "numpy-1.23.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ac987b35df8c2a2eab495ee206658117e9ce867acf3ccb376a19e83070e69418"}, + {file = "numpy-1.23.2-cp311-cp311-win32.whl", hash = "sha256:d98addfd3c8728ee8b2c49126f3c44c703e2b005d4a95998e2167af176a9e722"}, + {file = "numpy-1.23.2-cp311-cp311-win_amd64.whl", hash = "sha256:8ecb818231afe5f0f568c81f12ce50f2b828ff2b27487520d85eb44c71313b9e"}, + {file = "numpy-1.23.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:909c56c4d4341ec8315291a105169d8aae732cfb4c250fbc375a1efb7a844f8f"}, + {file = "numpy-1.23.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:8247f01c4721479e482cc2f9f7d973f3f47810cbc8c65e38fd1bbd3141cc9842"}, + {file = "numpy-1.23.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b8b97a8a87cadcd3f94659b4ef6ec056261fa1e1c3317f4193ac231d4df70215"}, + {file = "numpy-1.23.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd5b7ccae24e3d8501ee5563e82febc1771e73bd268eef82a1e8d2b4d556ae66"}, + {file = "numpy-1.23.2-cp38-cp38-win32.whl", hash = "sha256:9b83d48e464f393d46e8dd8171687394d39bc5abfe2978896b77dc2604e8635d"}, + {file = "numpy-1.23.2-cp38-cp38-win_amd64.whl", hash = "sha256:dec198619b7dbd6db58603cd256e092bcadef22a796f778bf87f8592b468441d"}, + {file = "numpy-1.23.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4f41f5bf20d9a521f8cab3a34557cd77b6f205ab2116651f12959714494268b0"}, + {file = "numpy-1.23.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:806cc25d5c43e240db709875e947076b2826f47c2c340a5a2f36da5bb10c58d6"}, + {file = "numpy-1.23.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f9d84a24889ebb4c641a9b99e54adb8cab50972f0166a3abc14c3b93163f074"}, + {file = "numpy-1.23.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c403c81bb8ffb1c993d0165a11493fd4bf1353d258f6997b3ee288b0a48fce77"}, + {file = "numpy-1.23.2-cp39-cp39-win32.whl", hash = "sha256:cf8c6aed12a935abf2e290860af8e77b26a042eb7f2582ff83dc7ed5f963340c"}, + {file = "numpy-1.23.2-cp39-cp39-win_amd64.whl", hash = "sha256:5e28cd64624dc2354a349152599e55308eb6ca95a13ce6a7d5679ebff2962913"}, + {file = "numpy-1.23.2-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:806970e69106556d1dd200e26647e9bee5e2b3f1814f9da104a943e8d548ca38"}, + {file = "numpy-1.23.2-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bd879d3ca4b6f39b7770829f73278b7c5e248c91d538aab1e506c628353e47f"}, + {file = "numpy-1.23.2-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:be6b350dfbc7f708d9d853663772a9310783ea58f6035eec649fb9c4371b5389"}, + {file = "numpy-1.23.2.tar.gz", hash = "sha256:b78d00e48261fbbd04aa0d7427cf78d18401ee0abd89c7559bbf422e5b1c7d01"}, ] oauthlib = [ {file = "oauthlib-3.2.0-py3-none-any.whl", hash = "sha256:6db33440354787f9b7f3a6dbd4febf5d0f93758354060e802f6c06cb493022fe"}, {file = "oauthlib-3.2.0.tar.gz", hash = "sha256:23a8208d75b902797ea29fd31fa80a15ed9dc2c6c16fe73f5d346f83f6fa27a2"}, ] +opencv-python = [ + {file = "opencv-python-4.6.0.66.tar.gz", hash = "sha256:c5bfae41ad4031e66bb10ec4a0a2ffd3e514d092652781e8b1ac98d1b59f1158"}, + {file = "opencv_python-4.6.0.66-cp36-abi3-macosx_10_15_x86_64.whl", hash = "sha256:e6e448b62afc95c5b58f97e87ef84699e6607fe5c58730a03301c52496005cae"}, + {file = "opencv_python-4.6.0.66-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5af8ba35a4fcb8913ffb86e92403e9a656a4bff4a645d196987468f0f8947875"}, + {file = "opencv_python-4.6.0.66-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dbdc84a9b4ea2cbae33861652d25093944b9959279200b7ae0badd32439f74de"}, + {file = "opencv_python-4.6.0.66-cp36-abi3-win32.whl", hash = "sha256:f482e78de6e7b0b060ff994ffd859bddc3f7f382bb2019ef157b0ea8ca8712f5"}, + {file = "opencv_python-4.6.0.66-cp36-abi3-win_amd64.whl", hash = "sha256:0dc82a3d8630c099d2f3ac1b1aabee164e8188db54a786abb7a4e27eba309440"}, + {file = "opencv_python-4.6.0.66-cp37-abi3-macosx_11_0_arm64.whl", hash = "sha256:6e32af22e3202748bd233ed8f538741876191863882eba44e332d1a34993165b"}, +] opt-einsum = [ {file = "opt_einsum-3.3.0-py3-none-any.whl", hash = "sha256:2455e59e3947d3c275477df7f5205b30635e266fe6dc300e3d9f9646bfcea147"}, {file = "opt_einsum-3.3.0.tar.gz", hash = "sha256:59f6475f77bbc37dcf7cd748519c0ec60722e91e63ca114e68821c0c54a46549"}, @@ -1825,10 +1794,6 @@ pymongo = [ {file = "pymongo-4.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:44b36ccb90aac5ea50be23c1a6e8f24fbfc78afabdef114af16c6e0a80981364"}, {file = "pymongo-4.2.0.tar.gz", hash = "sha256:72f338f6aabd37d343bd9d1fdd3de921104d395766bcc5cdc4039e4c2dd97766"}, ] -pyopenssl = [ - {file = "pyOpenSSL-22.0.0-py2.py3-none-any.whl", hash = "sha256:ea252b38c87425b64116f808355e8da644ef9b07e429398bfece610f893ee2e0"}, - {file = "pyOpenSSL-22.0.0.tar.gz", hash = "sha256:660b1b1425aac4a1bea1d94168a85d99f0b3144c869dd4390d27629d0087f1bf"}, -] pyparsing = [ {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, @@ -1847,8 +1812,8 @@ python-resize-image = [ {file = "python_resize_image-1.1.20-py2.py3-none-any.whl", hash = "sha256:0977bcf8454949b2d37e56c66d95494146c4d9da295a8f7af8eff43d2c35ca6a"}, ] pytz = [ - {file = "pytz-2022.1-py2.py3-none-any.whl", hash = "sha256:e68985985296d9a66a881eb3193b0906246245294a881e7c8afe623866ac6a5c"}, - {file = "pytz-2022.1.tar.gz", hash = "sha256:1e760e2fe6a8163bc0b3d9a19c4f84342afa0a2affebfaa84b01b978a02ecaa7"}, + {file = "pytz-2022.2.1-py2.py3-none-any.whl", hash = "sha256:220f481bdafa09c3955dfbdddb7b57780e9a94f5127e35456a48589b9e0c0197"}, + {file = "pytz-2022.2.1.tar.gz", hash = "sha256:cea221417204f2d1a2aa03ddae3e867921971d0d76f14d87abb4414415bbdcf5"}, ] pywavelets = [ {file = "PyWavelets-1.3.0-cp310-cp310-macosx_10_13_universal2.whl", hash = "sha256:eebaa9c28600da336743fefd650332460c132792660e70eb09abf343b0664b87"}, @@ -1943,36 +1908,36 @@ scikit-learn = [ {file = "scikit_learn-1.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:407e9a1cb9e6ba458a539986a9bd25546a757088095b3aab91d465b79a760d37"}, ] scipy = [ - {file = "scipy-1.9.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0424d1bbbfa51d5ddaa16d067fd593863c9f2fb7c6840c32f8a08a8832f8e7a4"}, - {file = "scipy-1.9.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:8f2232c9d9119ec356240255a715a289b3a33be828c3e4abac11fd052ce15b1e"}, - {file = "scipy-1.9.0-cp310-cp310-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:e2004d2a3c397b26ca78e67c9d320153a1a9b71ae713ad33f4a3a3ab3d79cc65"}, - {file = "scipy-1.9.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45f0d6c0d6e55582d3b8f5c58ad4ca4259a02affb190f89f06c8cc02e21bba81"}, - {file = "scipy-1.9.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79dd7876614fc2869bf5d311ef33962d2066ea888bc66c80fd4fa80f8772e5a9"}, - {file = "scipy-1.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:10417935486b320d98536d732a58362e3d37e84add98c251e070c59a6bfe0863"}, - {file = "scipy-1.9.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:adb6c438c6ef550e2bb83968e772b9690cb421f2c6073f9c2cb6af15ee538bc9"}, - {file = "scipy-1.9.0-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:8d541db2d441ef87afb60c4a2addb00c3af281633602a4967e733ef4b7050504"}, - {file = "scipy-1.9.0-cp38-cp38-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:97a1f1e51ea30782d7baa8d0c52f72c3f9f05cb609cf1b990664231c5102bccd"}, - {file = "scipy-1.9.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:16207622570af10f9e6a2cdc7da7a9660678852477adbcd056b6d1057a036fef"}, - {file = "scipy-1.9.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb687d245b6963673c639f318eea7e875d1ba147a67925586abed3d6f39bb7d8"}, - {file = "scipy-1.9.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:73b704c5eea9be811919cae4caacf3180dd9212d9aed08477c1d2ba14900a9de"}, - {file = "scipy-1.9.0-cp38-cp38-win32.whl", hash = "sha256:12005d30894e4fe7b247f7233ba0801a341f887b62e2eb99034dd6f2a8a33ad6"}, - {file = "scipy-1.9.0-cp38-cp38-win_amd64.whl", hash = "sha256:fc58c3fcb8a724b703ffbc126afdca5a8353d4d5945d5c92db85617e165299e7"}, - {file = "scipy-1.9.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:01c2015e132774feefe059d5354055fec6b751d7a7d70ad2cf5ce314e7426e2a"}, - {file = "scipy-1.9.0-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:f7c3c578ff556333f3890c2df6c056955d53537bb176698359088108af73a58f"}, - {file = "scipy-1.9.0-cp39-cp39-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:e2ac088ea4aa61115b96b47f5f3d94b3fa29554340b6629cd2bfe6b0521ee33b"}, - {file = "scipy-1.9.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:5d1b9cf3771fd921f7213b4b886ab2606010343bb36259b544a816044576d69e"}, - {file = "scipy-1.9.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3a326673ac5afa9ef5613a61626b9ec15c8f7222b4ecd1ce0fd8fcba7b83c59"}, - {file = "scipy-1.9.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:693b3fe2e7736ce0dbc72b4d933798eb6ca8ce51b8b934e3f547cc06f48b2afb"}, - {file = "scipy-1.9.0-cp39-cp39-win32.whl", hash = "sha256:7bad16b91918bf3288089a78a4157e04892ea6475fb7a1d9bcdf32c30c8a3dba"}, - {file = "scipy-1.9.0-cp39-cp39-win_amd64.whl", hash = "sha256:bd490f77f35800d5620f4d9af669e372d9a88db1f76ef219e1609cc4ecdd1a24"}, - {file = "scipy-1.9.0.tar.gz", hash = "sha256:c0dfd7d2429452e7e94904c6a3af63cbaa3cf51b348bd9d35b42db7e9ad42791"}, + {file = "scipy-1.9.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c61b4a91a702e8e04aeb0bfc40460e1f17a640977c04dda8757efb0199c75332"}, + {file = "scipy-1.9.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:d79da472015d0120ba9b357b28a99146cd6c17b9609403164b1a8ed149b4dfc8"}, + {file = "scipy-1.9.1-cp310-cp310-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:825951b88f56765aeb6e5e38ac9d7d47407cfaaeb008d40aa1b45a2d7ea2731e"}, + {file = "scipy-1.9.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f950a04b33e17b38ff561d5a0951caf3f5b47caa841edd772ffb7959f20a6af0"}, + {file = "scipy-1.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8cc81ac25659fec73599ccc52c989670e5ccd8974cf34bacd7b54a8d809aff1a"}, + {file = "scipy-1.9.1-cp310-cp310-win_amd64.whl", hash = "sha256:8d3faa40ac16c6357aaf7ea50394ea6f1e8e99d75e927a51102b1943b311b4d9"}, + {file = "scipy-1.9.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7a412c476a91b080e456229e413792bbb5d6202865dae963d1e6e28c2bb58691"}, + {file = "scipy-1.9.1-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:eb954f5aca4d26f468bbebcdc5448348eb287f7bea536c6306f62ea062f63d9a"}, + {file = "scipy-1.9.1-cp38-cp38-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:3c6f5d1d4b9a5e4fe5e14f26ffc9444fc59473bbf8d45dc4a9a15283b7063a72"}, + {file = "scipy-1.9.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:bc4e2c77d4cd015d739e75e74ebbafed59ba8497a7ed0fd400231ed7683497c4"}, + {file = "scipy-1.9.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0419485dbcd0ed78c0d5bf234c5dd63e86065b39b4d669e45810d42199d49521"}, + {file = "scipy-1.9.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:34441dfbee5b002f9e15285014fd56e5e3372493c3e64ae297bae2c4b9659f5a"}, + {file = "scipy-1.9.1-cp38-cp38-win32.whl", hash = "sha256:b97b479f39c7e4aaf807efd0424dec74bbb379108f7d22cf09323086afcd312c"}, + {file = "scipy-1.9.1-cp38-cp38-win_amd64.whl", hash = "sha256:e8fe305d9d67a81255e06203454729405706907dccbdfcc330b7b3482a6c371d"}, + {file = "scipy-1.9.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:39ab9240cd215a9349c85ab908dda6d732f7d3b4b192fa05780812495536acc4"}, + {file = "scipy-1.9.1-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:71487c503e036740635f18324f62a11f283a632ace9d35933b2b0a04fd898c98"}, + {file = "scipy-1.9.1-cp39-cp39-macosx_12_0_universal2.macosx_10_9_x86_64.whl", hash = "sha256:3bc1ab68b9a096f368ba06c3a5e1d1d50957a86665fc929c4332d21355e7e8f4"}, + {file = "scipy-1.9.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:f7c39f7dbb57cce00c108d06d731f3b0e2a4d3a95c66d96bce697684876ce4d4"}, + {file = "scipy-1.9.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:47d1a95bd9d37302afcfe1b84c8011377c4f81e33649c5a5785db9ab827a6ade"}, + {file = "scipy-1.9.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:96d7cf7b25c9f23c59a766385f6370dab0659741699ecc7a451f9b94604938ce"}, + {file = "scipy-1.9.1-cp39-cp39-win32.whl", hash = "sha256:09412eb7fb60b8f00b328037fd814d25d261066ebc43a1e339cdce4f7502877e"}, + {file = "scipy-1.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:90c805f30c46cf60f1e76e947574f02954d25e3bb1e97aa8a07bc53aa31cf7d1"}, + {file = "scipy-1.9.1.tar.gz", hash = "sha256:26d28c468900e6d5fdb37d2812ab46db0ccd22c63baa095057871faa3a498bc9"}, ] selenium = [ - {file = "selenium-4.4.0-py3-none-any.whl", hash = "sha256:61c8b02788b66f08f2e61d5295afc956991e394815e33573072e68402ed4e8d5"}, + {file = "selenium-4.4.3-py3-none-any.whl", hash = "sha256:ca6ed4a58a426bb40bf5aa2b027ce211cc5200f1acdcdfb8258b32b24624150c"}, ] setuptools-scm = [ - {file = "setuptools_scm-7.0.5-py3-none-any.whl", hash = "sha256:7930f720905e03ccd1e1d821db521bff7ec2ac9cf0ceb6552dd73d24a45d3b02"}, - {file = "setuptools_scm-7.0.5.tar.gz", hash = "sha256:031e13af771d6f892b941adb6ea04545bbf91ebc5ce68c78aaf3fff6e1fb4844"}, + {file = "setuptools_scm-6.4.2-py3-none-any.whl", hash = "sha256:acea13255093849de7ccb11af9e1fb8bde7067783450cee9ef7a93139bddf6d4"}, + {file = "setuptools_scm-6.4.2.tar.gz", hash = "sha256:6833ac65c6ed9711a4d5d2266f8024cfa07c533a0e55f4c12f6eff280a5a9e30"}, ] six = [ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, @@ -2048,8 +2013,8 @@ threadpoolctl = [ {file = "threadpoolctl-3.1.0.tar.gz", hash = "sha256:a335baacfaa4400ae1f0d8e3a58d6674d2f8828e3716bb2802c44955ad391380"}, ] tifffile = [ - {file = "tifffile-2022.8.8-py3-none-any.whl", hash = "sha256:dfb88106f42883a97b8f76c9ea2dddfd513a896ece4b3558e8c3cf3c10ca9b8a"}, - {file = "tifffile-2022.8.8.tar.gz", hash = "sha256:594498345c43a4bb2abb67f0e71c17708059a8f5f5ef1ca70a3416d549c78952"}, + {file = "tifffile-2022.8.12-py3-none-any.whl", hash = "sha256:1456f9f6943c85082ef4d73f5329038826da67f70d5d513873a06f3b1598d23e"}, + {file = "tifffile-2022.8.12.tar.gz", hash = "sha256:3e74e0fd48838477ebcf40e09b7780bd095ee5920b2238f485e2c68463a3dcb4"}, ] tomli = [ {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, @@ -2076,8 +2041,8 @@ uritemplate = [ {file = "uritemplate-4.1.1.tar.gz", hash = "sha256:4346edfc5c3b79f694bccd6d6099a322bbeb628dbf2cd86eea55a456ce5124f0"}, ] urllib3 = [ - {file = "urllib3-1.26.11-py2.py3-none-any.whl", hash = "sha256:c33ccba33c819596124764c23a97d25f32b28433ba0dedeb77d873a38722c9bc"}, - {file = "urllib3-1.26.11.tar.gz", hash = "sha256:ea6e8fb210b19d950fab93b60c9009226c63a28808bc8386e05301e25883ac0a"}, + {file = "urllib3-1.26.12-py2.py3-none-any.whl", hash = "sha256:b930dd878d5a8afb066a637fbb35144fe7901e3b209d1cd4f524bd0e9deee997"}, + {file = "urllib3-1.26.12.tar.gz", hash = "sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e"}, ] werkzeug = [ {file = "Werkzeug-2.2.2-py3-none-any.whl", hash = "sha256:f979ab81f58d7318e064e99c4506445d60135ac5cd2e177a2de0089bfd4c9bd5"}, @@ -2153,6 +2118,6 @@ wrapt = [ {file = "wrapt-1.14.1.tar.gz", hash = "sha256:380a85cf89e0e69b7cfbe2ea9f765f004ff419f34194018a6827ac0e3edfed4d"}, ] wsproto = [ - {file = "wsproto-1.1.0-py3-none-any.whl", hash = "sha256:2218cb57952d90b9fca325c0dcfb08c3bda93e8fd8070b0a17f048e2e47a521b"}, - {file = "wsproto-1.1.0.tar.gz", hash = "sha256:a2e56bfd5c7cd83c1369d83b5feccd6d37798b74872866e62616e0ecf111bda8"}, + {file = "wsproto-1.2.0-py3-none-any.whl", hash = "sha256:b9acddd652b585d75b20477888c56642fdade28bdfd3579aa24a4d2c037dd736"}, + {file = "wsproto-1.2.0.tar.gz", hash = "sha256:ad565f26ecb92588a3e43bc3d96164de84cd9902482b130d0ddbaa9664a85065"}, ] diff --git a/pyproject.toml b/pyproject.toml index d464224..c4b7e0b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ SpeechRecognition-ForkedVersion = "^3.9.2" tensorflow = "^2.9.1" tqdm = "^4.64.0" wikipedia = "^1.4.0" +opencv-python = "^4.6.0" [tool.poetry.dev-dependencies] diff --git a/src/MAGIST/NLP/AudioTranscriber.py b/src/MAGIST/NLP/AudioTranscriber.py index 6b139de..1947757 100644 --- a/src/MAGIST/NLP/AudioTranscriber.py +++ b/src/MAGIST/NLP/AudioTranscriber.py @@ -10,73 +10,76 @@ from ..Utils.LogMaster.log_init import MainLogger + class GoogleAudioTranscriber(): - """Google Audio Transcriber Class.""" + """Google Audio Transcriber Class.""" - def __init__(self, config): - """Initialize the Google Audio Transcriber and Microphone object. + def __init__(self, config): + """Initialize the Google Audio Transcriber and Microphone object. - :param config: The config file(config.json). - """ + :param config: The config file(config.json). + """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("GoogleAudioTranscriber") # Create a script specific logging instance + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("GoogleAudioTranscriber") - self.log.info("GoogleAudioTranscriber Recognizer Initialized Successfully") + self.log.info( + "GoogleAudioTranscriber Recognizer Initialized Successfully") - def microphone_listener(self): - """Listen to the microphone and transcribe the audio. + def microphone_listener(self): + """Listen to the microphone and transcribe the audio. - :return: The transcription of the audio as a string. - """ + :return: The transcription of the audio as a string. + """ - self.r = sr.Recognizer() - self.m = sr.Microphone() + self.r = sr.Recognizer() + self.m = sr.Microphone() - with self.m as source: - self.log.info("GoogleAudioTranscriber Listening...") - audio = self.r.listen(source) - self.log.info("GoogleAudioTranscriber Listening Complete") - try: - start = time.time() - transcription = self.r.recognize_google(audio) - self.log.info("Transcribed Prediction: " + transcription) - end = time.time() - except sr.UnknownValueError: - self.log.warning("Google could not understand audio") + with self.m as source: + self.log.info("GoogleAudioTranscriber Listening...") + audio = self.r.listen(source) + self.log.info("GoogleAudioTranscriber Listening Complete") + try: + start = time.time() + transcription = self.r.recognize_google(audio) + self.log.info("Transcribed Prediction: " + transcription) + end = time.time() + except sr.UnknownValueError: + self.log.warning("Google could not understand audio") - self.log.info("Time taken: " + str(end - start)) - return transcription + self.log.info("Time taken: " + str(end - start)) + return transcription - def file_transcriber(self, file): - """Transcribe an audio file. + def file_transcriber(self, file): + """Transcribe an audio file. - :param file: The file to be transcribed. + :param file: The file to be transcribed. - :return: The transcription of the audio as a string. - """ + :return: The transcription of the audio as a string. + """ - self.r = sr.Recognizer() - self.m = sr.Microphone() + self.r = sr.Recognizer() + self.m = sr.Microphone() - file = pathlib.Path(file) - file = file.resolve() # Find absolute path from a relative one. - file = str(file) + file = pathlib.Path(file) + file = file.resolve() # Find absolute path from a relative one. + file = str(file) - audio = sr.AudioFile(file) + audio = sr.AudioFile(file) - with audio as source: - self.log.info("GoogleAudioTranscriber Processing...") - audio = self.r.record(source) - self.log.info("GoogleAudioTranscriber Processing Complete") - try: - start = time.time() - transcription = self.r.recognize_google(audio) - self.log.info("Transcribed Prediction: " + transcription) - end = time.time() - except sr.UnknownValueError: - self.log.warning("Google could not understand audio") + with audio as source: + self.log.info("GoogleAudioTranscriber Processing...") + audio = self.r.record(source) + self.log.info("GoogleAudioTranscriber Processing Complete") + try: + start = time.time() + transcription = self.r.recognize_google(audio) + self.log.info("Transcribed Prediction: " + transcription) + end = time.time() + except sr.UnknownValueError: + self.log.warning("Google could not understand audio") - self.log.info("Time taken: " + str(end - start)) + self.log.info("Time taken: " + str(end - start)) - return transcription \ No newline at end of file + return transcription diff --git a/src/MAGIST/NLP/SelfAttention.py b/src/MAGIST/NLP/SelfAttention.py index d93b713..d4acb14 100644 --- a/src/MAGIST/NLP/SelfAttention.py +++ b/src/MAGIST/NLP/SelfAttention.py @@ -9,238 +9,250 @@ import numpy as np from ..Utils.LogMaster.log_init import MainLogger -class TextPreprocessing(): - def __init__(self, config): - """Initializes the TextPreprocessing class and config. - - :param config: The config file containing all necessary parameters(config.json). - """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("TextPreprocessing") # Create a script specific logging instance - - def __format_data(self, in_text): - """Formats the input text to be compatible with the model. - - :param in_text: The text(string) to be formatted. - - :return: The formatted text. - """ - punctuation = [".", ",", ";", ":", "!", "?", "\"", "'", "`", "~", "`", "´", "’", "‘", "“", "”", "„", "‟", "‹", "›", - "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", - "„", - "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", - "’", - "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", - "‹", - "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", - "›", - "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", - "„", - "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’"] - def __remove_puctuation(text): - """Removes punctuation from the text. - - :param text: The text to be formatted. - - :return: The formatted text. - """ - for i in punctuation: - text = text.replace(i, "") - return text - - def __lowercase(text): - """Converts the text to lowercase. - - :param text: The text to be formatted. - - :return: The formatted text. - """ - return text.lower() - - in_text = __remove_puctuation(in_text) - in_text = __lowercase(in_text) - return in_text - def __tokenize(self, input_text): - """Splits the input text into tokens. - - :param input_text: The text to be split. - - :return: The tokens. - """ - input_text = self.__format_data(input_text) - return input_text.split(" ") - - def split_positional_encodings(self, input_text): - """Splits the input text into positional encodings. - - :param input_text: The text to be split. - - :return: The positional encodings. - """ - input_text = self.__format_data(input_text) - split_text = self.__tokenize(input_text) - - position_dict = [] - count = 1 - for s in split_text: - position_dict.append([count, s]) - count += 1 - - return position_dict - - def vectorize_text(self, raw_input_text): - """Vectorizes the input text. +class TextPreprocessing(): + def __init__(self, config): + """Initializes the TextPreprocessing class and config. - :param raw_input_text: The text to be vectorized. + :param config: The config file containing all necessary parameters(config.json). + """ + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("TextPreprocessing") - :return: The vectorized text. - """ - input_text = self.__format_data(raw_input_text) - self.vectorize_layer = tf.keras.layers.TextVectorization() - self.vectorize_layer.adapt([raw_input_text]) - vec = self.vectorize_layer(raw_input_text) + def __format_data(self, in_text): + """Formats the input text to be compatible with the model. + + :param in_text: The text(string) to be formatted. - return np.array(vec) + :return: The formatted text. + """ + punctuation = [ + ".", ",", ";", ":", "!", "?", "\"", "'", "`", "~", "`", "´", "’", + "‘", "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", + "“", "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", + "”", "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", + "„", "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", + "‟", "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", + "‹", "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", + "›", "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", + "«", "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", + "»", "‹", "›", "‘", "’", "“", "”", "„", "‟", "‹", "›", "«", "»", + "‹", "›", "‘", "’"] + + def __remove_puctuation(text): + """Removes punctuation from the text. - def __positional_embedding_function(self, n, scale=0.1, scalar=1): - """Computes the positional embedding. + :param text: The text to be formatted. - :param n: The position to be computed. - :param scale: The scale of the positional embedding function. - :param scalar: The scalar multiplier to the output of the positional embedding. - - :return: The positional embedding. - """ - x = np.multiply(n, scale) - part1 = np.sin(np.multiply(n, x)) - part2 = np.sin(np.divide(1, x)) - return np.multiply(np.abs(np.multiply(part1, part2)), scalar) - - def positional_embedding(self, split_positional_encodings, vectorized_text, scalar=3): - """Computes the positional embedding. + :return: The formatted text. + """ + for i in punctuation: + text = text.replace(i, "") + return text - :param split_positional_encodings: The positional encodings to be computed. - :param vectorized_text: The vectorized text. - :param scalar: The scalar multiplier to the output of the positional embedding. - - :return: The positional embedding. - """ - position_computed = [] - for i in split_positional_encodings: - pos = self.__positional_embedding_function(i[0], scalar=scalar) - position_computed.append(pos) + def __lowercase(text): + """Converts the text to lowercase. - final_position_embedding = [] + :param text: The text to be formatted. - for i in range(len(position_computed)): - final_position_embedding.append(int(vectorized_text[i]) + position_computed[i]) + :return: The formatted text. + """ + return text.lower() - return final_position_embedding + in_text = __remove_puctuation(in_text) + in_text = __lowercase(in_text) + return in_text - def SelfAttention(self, value, query, key, in_len): - """Computes the self attention. + def __tokenize(self, input_text): + """Splits the input text into tokens. - :param value: The value to be computed. - :param query: The query to be computed. - :param key: The key to be computed. - :param in_len: The length of the input. + :param input_text: The text to be split. - Note: The value, query, and key must be the same length and are the same thing usually for self-attention. - """ - value_mod = tf.keras.models.Sequential() - value_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + :return: The tokens. + """ + input_text = self.__format_data(input_text) + return input_text.split(" ") - key_mod = tf.keras.models.Sequential() - key_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + def split_positional_encodings(self, input_text): + """Splits the input text into positional encodings. - query_mod = tf.keras.models.Sequential() - query_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) + :param input_text: The text to be split. - # value = value_mod.predict(value) - # key = key_mod.predict(key) - # query = query_mod.predict(query) + :return: The positional encodings. + """ + input_text = self.__format_data(input_text) + split_text = self.__tokenize(input_text) - value = np.array(value).astype(np.float64) - key = np.array(key).astype(np.float64) - query = np.array(query).astype(np.float64) + position_dict = [] + count = 1 + for s in split_text: + position_dict.append([count, s]) + count += 1 - value = np.squeeze(value) - key = np.squeeze(key) - query = np.squeeze(query) + return position_dict - val_mag = np.sqrt(np.dot(value, value)) - key_mag = np.sqrt(np.dot(key, key)) - query_mag = np.sqrt(np.dot(query, query)) + def vectorize_text(self, raw_input_text): + """Vectorizes the input text. - matmul = key_mag * query_mag - theta = np.dot(value, query) / matmul + :param raw_input_text: The text to be vectorized. - # theta = np.arccos(theta) + :return: The vectorized text. + """ + input_text = self.__format_data(raw_input_text) + self.vectorize_layer = tf.keras.layers.TextVectorization() + self.vectorize_layer.adapt([raw_input_text]) + vec = self.vectorize_layer(raw_input_text) - softmax = 1 / ((np.e) ** (-theta) + 1) + return np.array(vec) - out = softmax * value + def __positional_embedding_function(self, n, scale=0.1, scalar=1): + """Computes the positional embedding. - return out + :param n: The position to be computed. + :param scale: The scale of the positional embedding function. + :param scalar: The scalar multiplier to the output of the positional embedding. - def compute_theshold(self, attention_weights): - """Computes the threshold for relevant and irrelevant text. + :return: The positional embedding. + """ + x = np.multiply(n, scale) + part1 = np.sin(np.multiply(n, x)) + part2 = np.sin(np.divide(1, x)) + return np.multiply(np.abs(np.multiply(part1, part2)), scalar) + + def positional_embedding( + self, split_positional_encodings, vectorized_text, scalar=3): + """Computes the positional embedding. + + :param split_positional_encodings: The positional encodings to be computed. + :param vectorized_text: The vectorized text. + :param scalar: The scalar multiplier to the output of the positional embedding. + + :return: The positional embedding. + """ + position_computed = [] + for i in split_positional_encodings: + pos = self.__positional_embedding_function(i[0], scalar=scalar) + position_computed.append(pos) - :param attention_weights: The attention weights to be computed. + final_position_embedding = [] - :return: The threshold(int). - """ - threshold = 0 - for b in attention_weights: - if b != 0: - threshold += b - return threshold / len(attention_weights) + for i in range(len(position_computed)): + final_position_embedding.append( + int(vectorized_text[i]) + position_computed[i]) - def print_results(self, attention_weights, threshold, vectorized_text, show_only_important=False): - """Prints the results. - """ - for i in range(len(attention_weights)): - stat = "" - if attention_weights[i] > threshold: - stat = "Good" - elif attention_weights[i] == threshold: - stat = "Meh" - elif attention_weights[i] < threshold: - stat = "Not" - if show_only_important: - if attention_weights[i] >= threshold: - self.log.info(f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") - else: - self.log.info( - f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") + return final_position_embedding - def __call__(self, input_text): - """Computes everything and returns the importance matrix. + def SelfAttention(self, value, query, key, in_len): + """Computes the self attention. - :param input_text: The text to be computed. + :param value: The value to be computed. + :param query: The query to be computed. + :param key: The key to be computed. + :param in_len: The length of the input. - :return: The simplified importance matrix. - """ - s = self.split_positional_encodings(input_text) - vec = self.vectorize_text(input_text) + Note: The value, query, and key must be the same length and are the same thing usually for self-attention. + """ + value_mod = tf.keras.models.Sequential() + value_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) - out_fin = self.positional_embedding(s, vec) + key_mod = tf.keras.models.Sequential() + key_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) - attention_weights = self.SelfAttention(out_fin, out_fin, out_fin, len(out_fin)) - threshold = self.compute_theshold(attention_weights) + query_mod = tf.keras.models.Sequential() + query_mod.add(tf.keras.layers.Dense(in_len, use_bias=False)) - final_output_array = [] + # value = value_mod.predict(value) + # key = key_mod.predict(key) + # query = query_mod.predict(query) - for i in range(len(attention_weights)): - stat = "" - if attention_weights[i] > threshold: - stat = "Good" - elif attention_weights[i] == threshold: - stat = "Meh" - elif attention_weights[i] < threshold: - stat = "Not" + value = np.array(value).astype(np.float64) + key = np.array(key).astype(np.float64) + query = np.array(query).astype(np.float64) + + value = np.squeeze(value) + key = np.squeeze(key) + query = np.squeeze(query) - final_output_array.append([attention_weights[i], self.vectorize_layer.get_vocabulary()[vec[i]], stat]) + val_mag = np.sqrt(np.dot(value, value)) + key_mag = np.sqrt(np.dot(key, key)) + query_mag = np.sqrt(np.dot(query, query)) + + matmul = key_mag * query_mag + theta = np.dot(value, query) / matmul + + # theta = np.arccos(theta) + + softmax = 1 / ((np.e) ** (-theta) + 1) + + out = softmax * value + + return out + + def compute_theshold(self, attention_weights): + """Computes the threshold for relevant and irrelevant text. + + :param attention_weights: The attention weights to be computed. + + :return: The threshold(int). + """ + threshold = 0 + for b in attention_weights: + if b != 0: + threshold += b + return threshold / len(attention_weights) + + def print_results( + self, attention_weights, threshold, vectorized_text, + show_only_important=False): + """Prints the results. + """ + for i in range(len(attention_weights)): + stat = "" + if attention_weights[i] > threshold: + stat = "Good" + elif attention_weights[i] == threshold: + stat = "Meh" + elif attention_weights[i] < threshold: + stat = "Not" + if show_only_important: + if attention_weights[i] >= threshold: + self.log.info( + f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") + else: + self.log.info( + f"{attention_weights[i]:.2f}, {self.vectorize_layer.get_vocabulary()[vectorized_text[i]]}, {stat}") + + def __call__(self, input_text): + """Computes everything and returns the importance matrix. + + :param input_text: The text to be computed. + + :return: The simplified importance matrix. + """ + s = self.split_positional_encodings(input_text) + vec = self.vectorize_text(input_text) + + out_fin = self.positional_embedding(s, vec) - return final_output_array + attention_weights = self.SelfAttention( + out_fin, out_fin, out_fin, len(out_fin)) + threshold = self.compute_theshold(attention_weights) + + final_output_array = [] + + for i in range(len(attention_weights)): + stat = "" + if attention_weights[i] > threshold: + stat = "Good" + elif attention_weights[i] == threshold: + stat = "Meh" + elif attention_weights[i] < threshold: + stat = "Not" + + final_output_array.append( + [attention_weights[i], + self.vectorize_layer.get_vocabulary()[vec[i]], + stat]) + + return final_output_array diff --git a/src/MAGIST/NLP/WordScraper.py b/src/MAGIST/NLP/WordScraper.py index 11165ef..825683c 100644 --- a/src/MAGIST/NLP/WordScraper.py +++ b/src/MAGIST/NLP/WordScraper.py @@ -1,107 +1,109 @@ -import requests, json +import requests +import json from ..Utils.LogMaster.log_init import MainLogger class ClassDeprecated(Exception): - pass + pass class UrbanDictionary(): - def __init__(self, config): - """Initialize the Urban Dictionary API. - :param config: The config file(config.json). - """ + def __init__(self, config): + """Initialize the Urban Dictionary API. + :param config: The config file(config.json). + """ - raise ClassDeprecated("This class is deprecated") + raise ClassDeprecated("This class is deprecated") - root_log = MainLogger(config) - self.log = root_log.StandardLogger("UrbanDictionary") + root_log = MainLogger(config) + self.log = root_log.StandardLogger("UrbanDictionary") - self.url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define" + self.url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define" - def define(self, word): - """Define a word. - :param word: The word to be defined. - :return: The definition of the word. - """ + def define(self, word): + """Define a word. + :param word: The word to be defined. + :return: The definition of the word. + """ - querystring = {"term": word} + querystring = {"term": word} - headers = { - "X-RapidAPI-Key": "xxx", - "X-RapidAPI-Host": "mashape-community-urban-dictionary.p.rapidapi.com" - } + headers = { + "X-RapidAPI-Key": "xxx", + "X-RapidAPI-Host": "mashape-community-urban-dictionary.p.rapidapi.com"} - response = requests.request("GET", self.url, headers=headers, params=querystring) + response = requests.request( + "GET", self.url, headers=headers, params=querystring, timeout=20) - json_data = json.loads(response.text) + json_data = json.loads(response.text) - definition = json_data["list"][0]["definition"] + definition = json_data["list"][0]["definition"] - self.log.info(f"Definition of {word}: " + definition) + self.log.info(f"Definition of {word}: " + definition) - return definition + return definition -class DicitonaryAPIDev(): - def __init__(self, config): - """Initialize the Dictionary API.. - :param config: The config file(config.json). - """ +class DicitonaryAPIDev(): + def __init__(self, config): + """Initialize the Dictionary API.. - root_log = MainLogger(config) - self.log = root_log.StandardLogger("DisctionaryAPI") + :param config: The config file(config.json). + """ - self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + root_log = MainLogger(config) + self.log = root_log.StandardLogger("DisctionaryAPI") - def define(self, word): - """Define a word. + self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" - :param word: The word to be defined. + def define(self, word): + """Define a word. - :return: The definition of the word. - """ + :param word: The word to be defined. - querystring = {"term": word} + :return: The definition of the word. + """ - self.url = self.url + word + querystring = {"term": word} - response = requests.request("GET", self.url, params=querystring) + self.url = self.url + word - json_data = json.loads(response.text) + response = requests.request("GET", self.url, params=querystring, timeout=20) - definition = json_data - try: - definition = definition[0]["meanings"][0]["definitions"][0]["definition"] - except KeyError: - definition = "No definition found" + json_data = json.loads(response.text) - self.log.info(f"Definition of {word}: " + definition) + definition = json_data + try: + definition = definition[0]["meanings"][0]["definitions"][0][ + "definition"] + except KeyError: + definition = "No definition found" - self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + self.log.info(f"Definition of {word}: " + definition) - return definition + self.url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + return definition class FullDictionarySearch(): - def __init__(self, config): - """Initialize the Dictionary API.. + def __init__(self, config): + """Initialize the Dictionary API.. - :param config: The config file(config.json). - """ + :param config: The config file(config.json). + """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("FullDictionarySearch") + root_log = MainLogger(config) + self.log = root_log.StandardLogger("FullDictionarySearch") - self.dictdev = DicitonaryAPIDev(config) + self.dictdev = DicitonaryAPIDev(config) - def define(self, word): - definition = self.dictdev.define(word) + def define(self, word): + definition = self.dictdev.define(word) - if definition == "No definition found": - self.log.info("No definition found in DictionaryAPI.dev.") - definition = None + if definition == "No definition found": + self.log.info("No definition found in DictionaryAPI.dev.") + definition = None - return definition \ No newline at end of file + return definition diff --git a/src/MAGIST/NeuralDB/ElasticSearch.py b/src/MAGIST/NeuralDB/ElasticSearch.py index 3b2fc64..9b759c9 100644 --- a/src/MAGIST/NeuralDB/ElasticSearch.py +++ b/src/MAGIST/NeuralDB/ElasticSearch.py @@ -6,243 +6,270 @@ class ESDB(): - def __init__(self, config, es_uri, queries_file, schema_file, auto_check_server=True): - - root_log = MainLogger(config) - self.log = root_log.StandardLogger("NeuralDB - ElasticSearchClient") # Create a script specific logging instance - - self.es_uri = es_uri - - schema_file = pathlib.Path(schema_file) - schema_file = schema_file.resolve() # Find absolute path from a relative one. - queries_file = pathlib.Path(queries_file) - queries_file = queries_file.resolve() # Find absolute path from a relative one. - - self.schema_file = f = open(schema_file, 'r') - self.schema_file_data = json.load(self.schema_file) - self.queries_file = f = open(queries_file, 'r') - self.queries_file_data = json.load(self.queries_file) - - self.log.debug(f"ElasticSearch Client initialized with {self.es_uri}. Config files: {self.schema_file} and {self.queries_file} parsed!") - - if auto_check_server: - self.__check_es_status() - - def __check_es_status(self): - es_status = requests.get(self.es_uri, timeout=10) - es_status = json.dumps(str(es_status)) - if "200" not in str(es_status): - raise RuntimeError(f"ElasticSearch Server is unreachable!") - else: - self.log.info(f"ElasticSearch Server is reachable!") - return True - - def create_index(self, index_name, schema_name): - available_schemas = ['object_db_schema', 'word_db_schema'] - success_status = "" - - try: - specific_schema = self.schema_file_data[schema_name] - except KeyError: - self.log.error(f"Schema not found from available schemas: {available_schemas}") - return - - # print(json.dumps(specific_schema, indent=2)) - - schema_uri = self.es_uri + "/" + index_name - - schema_stat = requests.put(schema_uri, json=specific_schema) - - schema_stat = json.dumps(str(schema_stat)) - - check_stat = requests.get(schema_uri + "/_settings") - check_stat = json.dumps(str(check_stat)) - - if "200" in str(schema_stat) and "200" in str(check_stat): - self.log.info(f"Index {index_name} with {schema_name} schema successfully created and verified!") - elif "200" in str(schema_stat) and "200" not in str(check_stat): - self.log.error( - f'Error creating index {index_name} with {schema_name} schema! Perhaps request was incorrectly formed or ' - f'ElasticSearch Server is unreachable.') - elif "200" not in str(schema_stat) and "200" in str(check_stat): - self.log.warning(f'Error creating index {index_name} with {schema_name} schema! The schema named {schema_name} likely ' - f'already exists.') - else: - self.log.error( - f'Error creating index {index_name} with {schema_name} schema! Perhaps request was incorrectly formed or ' - f'ElasticSearch Server is unreachable.') - - #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - def add_doc(es_uri, index_name, data_type, data, update="add"): - data_type_valid = ['object_db_schema', 'word_db_schema'] - if data_type not in data_type_valid: - raise ValueError(f"Data type {data_type} not found in available data types: {data_type_valid}") - - update_valid = ["add", "concatenate", "overwrite", "blind"] - if update not in update_valid: - raise ValueError(f"Data type {data_type} not found in available data types: {update_valid}") - - success_status = "" - - if data_type == 'object_db_schema': - index_check = requests.get(es_uri + "/" + index_name) - index_check = json.dumps(str(index_check)) - if "200" not in str(index_check): - raise RuntimeError(f"Index {index_name} not found!") - - try: - name = data['name'] - description = data['description'] - users = data['users'] - related_objects = data['related_objects'] - locations = data['locations'] - except KeyError: - raise RuntimeError("Improperly formatted data. Data MUST be in the following format: {name: str, " - "description: str, users: list, related_objects: list, locations: list}") - - queries_file = open('queries.json', 'r') - queries = json.load(queries_file) - - queries["object_exists"]["query"]["query_string"]["query"] = name - - object_exists = requests.post(es_uri + "/" + index_name + "/_search", json=queries["object_exists"]) - object_exists_simple = json.dumps(str(object_exists)) - object_exists_full = json.loads(str(object_exists.text)) - - print(object_exists_full["hits"]["total"]["value"]) - - if "200" in object_exists_simple and object_exists_full["hits"]["total"]["value"] > 0 and update != "add": - print(f"Object {name} already exists in index {index_name}!") - if object_exists_full["hits"]["total"]["value"] > 1: - raise RuntimeError("Search for existing objects failed and returned more than one result.") - - hit = object_exists_full["hits"]["hits"][0] - hit_id = hit["_id"] - hit_source = hit["_source"] - - print(type(hit_source["users"])) - - if update == "concatenate" or update == "blind": - hit_source["name"] = name - hit_source["description"] += description - hit_source["users"] += users - hit_source["related_objects"] += related_objects - hit_source["locations"] += locations - elif update == "overwrite": - hit_source["name"] = name - hit_source["description"] = description - hit_source["users"] = users - hit_source["related_objects"] = related_objects - hit_source["locations"] = locations - - hit_source = json.dumps(hit_source) - print(hit_source) - hit_source = """{"doc":""" + hit_source + "}" - print(hit_source) - hit_source = json.loads(hit_source) - print(hit_source) - - update_uri = es_uri + "/" + index_name + "/_update/" + hit_id - update_stat = requests.post(update_uri, json=hit_source) - print(update_stat.text) - - - elif "200" in object_exists_simple and object_exists_full["hits"]["total"][ - "value"] == 0 and update == "add": - print(f"Object {name} does not exist in index {index_name}! Proceeding to add object...") - - data_uri = es_uri + "/" + index_name + "/_doc" - data_stat = requests.post(data_uri, json=data) - data_stat = json.dumps(str(data_stat)) - - print(data_stat) - - if "201" in str(data_stat): - print(f"Object {name} successfully added to index {index_name}!") - else: - print(f"Error adding object {name} to index {index_name}!") - else: - print(f"Error checking if object {name} exists in index {index_name}!") - - elif data_type == 'word_db_schema': - index_check = requests.get(es_uri + "/" + index_name) - index_check = json.dumps(str(index_check)) - if "200" not in str(index_check): - raise RuntimeError(f"Index {index_name} not found!") - - try: - word = data['word'] - definition = data['definition'] - users = data['users'] - related_words = data['related_words'] - related_objects = data['related_objects'] - locations = data['locations'] - except KeyError: - raise RuntimeError("Improperly formatted data. Data MUST be in the following format: {name: str, " - "description: str, users: list, related_objects: list, locations: list}") - - queries_file = open('queries.json', 'r') - queries = json.load(queries_file) - - queries["word_exists"]["query"]["query_string"]["query"] = word - - word_exists = requests.post(es_uri + "/" + index_name + "/_search", json=queries["word_exists"]) - word_exists_simple = json.dumps(str(word_exists)) - word_exists_full = json.loads(str(word_exists.text)) - - print(word_exists_full["hits"]["total"]["value"]) - - if "200" in word_exists_simple and word_exists_full["hits"]["total"]["value"] > 0 and update != "add": - print(f"Object {word} already exists in index {index_name}!") - if word_exists_full["hits"]["total"]["value"] > 1: - raise RuntimeError("Search for existing objects failed and returned more than one result.") - - hit = word_exists_full["hits"]["hits"][0] - hit_id = hit["_id"] - hit_source = hit["_source"] - - print(type(hit_source["users"])) - - if update == "concatenate" or update == "blind": - hit_source["word"] += word - hit_source["description"] += definition - hit_source["users"] += users - hit_source["related_objects"] += related_objects - hit_source["related_words"] += related_words - hit_source["locations"] += locations - elif update == "overwrite": - hit_source["word"] = word - hit_source["description"] = definition - hit_source["users"] = users - hit_source["related_objects"] = related_objects - hit_source["related_words"] = related_words - hit_source["locations"] = locations - - hit_source = json.dumps(hit_source) - print(hit_source) - hit_source = """{"doc":""" + hit_source + "}" - print(hit_source) - hit_source = json.loads(hit_source) - print(hit_source) - - update_uri = es_uri + "/" + index_name + "/_update/" + hit_id - update_stat = requests.post(update_uri, json=hit_source) - print(update_stat.text) - - - elif "200" in word_exists_simple and word_exists_full["hits"]["total"]["value"] == 0 and update == "add": - print(f"Object {word} does not exist in index {index_name}! Proceeding to add object...") - - data_uri = es_uri + "/" + index_name + "/_doc" - data_stat = requests.post(data_uri, json=data) - data_stat = json.dumps(str(data_stat)) - - print(data_stat) - - if "201" in str(data_stat): - print(f"Object {word} successfully added to index {index_name}!") - else: - print(f"Error adding object {word} to index {index_name}!") - else: - print(f"Error checking if object {word} exists in index {index_name}!") + def __init__(self, config, es_uri, queries_file, + schema_file, auto_check_server=True): + + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("NeuralDB - ElasticSearchClient") + + self.es_uri = es_uri + + schema_file = pathlib.Path(schema_file) + # Find absolute path from a relative one. + schema_file = schema_file.resolve() + queries_file = pathlib.Path(queries_file) + # Find absolute path from a relative one. + queries_file = queries_file.resolve() + + + self.schema_file = open(schema_file, 'r') + self.schema_file_data = json.load(self.schema_file) + self.queries_file = open(queries_file, 'r') + self.queries_file_data = json.load(self.queries_file) + + self.log.debug( + f"ElasticSearch Client initialized with {self.es_uri}. Config files: {self.schema_file} and {self.queries_file} parsed!") + + if auto_check_server: + self.__check_es_status() + + def __check_es_status(self): + es_status = requests.get(self.es_uri, timeout=10) + es_status = json.dumps(str(es_status)) + if "200" not in str(es_status): + raise RuntimeError(f"ElasticSearch Server is unreachable!") + else: + self.log.info(f"ElasticSearch Server is reachable!") + return True + + def create_index(self, index_name, schema_name): + available_schemas = ['object_db_schema', 'word_db_schema'] + success_status = "" + + try: + specific_schema = self.schema_file_data[schema_name] + except KeyError: + self.log.error( + f"Schema not found from available schemas: {available_schemas}") + return + + # print(json.dumps(specific_schema, indent=2)) + + schema_uri = self.es_uri + "/" + index_name + + schema_stat = requests.put(schema_uri, json=specific_schema, timeout=20) + + schema_stat = json.dumps(str(schema_stat)) + + check_stat = requests.get(schema_uri + "/_settings", timeout=20) + check_stat = json.dumps(str(check_stat)) + + if "200" in str(schema_stat) and "200" in str(check_stat): + self.log.info( + f"Index {index_name} with {schema_name} schema successfully created and verified!") + elif "200" in str(schema_stat) and "200" not in str(check_stat): + self.log.error( + f'Error creating index {index_name} with {schema_name} schema! Perhaps request was incorrectly formed or ' + f'ElasticSearch Server is unreachable.') + elif "200" not in str(schema_stat) and "200" in str(check_stat): + self.log.warning( + f'Error creating index {index_name} with {schema_name} schema! The schema named {schema_name} likely ' + f'already exists.') + else: + self.log.error( + f'Error creating index {index_name} with {schema_name} schema! Perhaps request was incorrectly formed or ' + f'ElasticSearch Server is unreachable.') + + # ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + def add_doc(es_uri, index_name, data_type, data, update="add"): + data_type_valid = ['object_db_schema', 'word_db_schema'] + if data_type not in data_type_valid: + raise ValueError( + f"Data type {data_type} not found in available data types: {data_type_valid}") + + update_valid = ["add", "concatenate", "overwrite", "blind"] + if update not in update_valid: + raise ValueError( + f"Data type {data_type} not found in available data types: {update_valid}") + + success_status = "" + + if data_type == 'object_db_schema': + index_check = requests.get(es_uri + "/" + index_name, timeout=20) + index_check = json.dumps(str(index_check)) + if "200" not in str(index_check): + raise RuntimeError(f"Index {index_name} not found!") + + try: + name = data['name'] + description = data['description'] + users = data['users'] + related_objects = data['related_objects'] + locations = data['locations'] + except KeyError: + raise RuntimeError( + "Improperly formatted data. Data MUST be in the following format: {name: str, " + "description: str, users: list, related_objects: list, locations: list}") + + queries_file = open('queries.json', 'r') + queries = json.load(queries_file) + + queries["object_exists"]["query"]["query_string"]["query"] = name + + object_exists = requests.post( + es_uri + "/" + index_name + "/_search", + json=queries["object_exists"], + timeout=20) + object_exists_simple = json.dumps(str(object_exists)) + object_exists_full = json.loads(str(object_exists.text)) + + print(object_exists_full["hits"]["total"]["value"]) + + if "200" in object_exists_simple and object_exists_full["hits"][ + "total"]["value"] > 0 and update != "add": + print(f"Object {name} already exists in index {index_name}!") + if object_exists_full["hits"]["total"]["value"] > 1: + raise RuntimeError( + "Search for existing objects failed and returned more than one result.") + + hit = object_exists_full["hits"]["hits"][0] + hit_id = hit["_id"] + hit_source = hit["_source"] + + print(type(hit_source["users"])) + + if update == "concatenate" or update == "blind": + hit_source["name"] = name + hit_source["description"] += description + hit_source["users"] += users + hit_source["related_objects"] += related_objects + hit_source["locations"] += locations + elif update == "overwrite": + hit_source["name"] = name + hit_source["description"] = description + hit_source["users"] = users + hit_source["related_objects"] = related_objects + hit_source["locations"] = locations + + hit_source = json.dumps(hit_source) + print(hit_source) + hit_source = """{"doc":""" + hit_source + "}" + print(hit_source) + hit_source = json.loads(hit_source) + print(hit_source) + + update_uri = es_uri + "/" + index_name + "/_update/" + hit_id + update_stat = requests.post(update_uri, json=hit_source, timeout=20) + print(update_stat.text) + + elif "200" in object_exists_simple and object_exists_full["hits"]["total"][ + "value"] == 0 and update == "add": + print( + f"Object {name} does not exist in index {index_name}! Proceeding to add object...") + + data_uri = es_uri + "/" + index_name + "/_doc" + data_stat = requests.post(data_uri, json=data, timeout=20) + data_stat = json.dumps(str(data_stat)) + + print(data_stat) + + if "201" in str(data_stat): + print( + f"Object {name} successfully added to index {index_name}!") + else: + print(f"Error adding object {name} to index {index_name}!") + else: + print( + f"Error checking if object {name} exists in index {index_name}!") + + elif data_type == 'word_db_schema': + index_check = requests.get(es_uri + "/" + index_name, timeout=20) + index_check = json.dumps(str(index_check)) + if "200" not in str(index_check): + raise RuntimeError(f"Index {index_name} not found!") + + try: + word = data['word'] + definition = data['definition'] + users = data['users'] + related_words = data['related_words'] + related_objects = data['related_objects'] + locations = data['locations'] + except KeyError: + raise RuntimeError( + "Improperly formatted data. Data MUST be in the following format: {name: str, " + "description: str, users: list, related_objects: list, locations: list}") + + queries_file = open('queries.json', 'r') + queries = json.load(queries_file) + + queries["word_exists"]["query"]["query_string"]["query"] = word + + word_exists = requests.post( + es_uri + "/" + index_name + "/_search", + json=queries["word_exists"], + timeout=20) + word_exists_simple = json.dumps(str(word_exists)) + word_exists_full = json.loads(str(word_exists.text)) + + print(word_exists_full["hits"]["total"]["value"]) + + if "200" in word_exists_simple and word_exists_full["hits"][ + "total"]["value"] > 0 and update != "add": + print(f"Object {word} already exists in index {index_name}!") + if word_exists_full["hits"]["total"]["value"] > 1: + raise RuntimeError( + "Search for existing objects failed and returned more than one result.") + + hit = word_exists_full["hits"]["hits"][0] + hit_id = hit["_id"] + hit_source = hit["_source"] + + print(type(hit_source["users"])) + + if update == "concatenate" or update == "blind": + hit_source["word"] += word + hit_source["description"] += definition + hit_source["users"] += users + hit_source["related_objects"] += related_objects + hit_source["related_words"] += related_words + hit_source["locations"] += locations + elif update == "overwrite": + hit_source["word"] = word + hit_source["description"] = definition + hit_source["users"] = users + hit_source["related_objects"] = related_objects + hit_source["related_words"] = related_words + hit_source["locations"] = locations + + hit_source = json.dumps(hit_source) + print(hit_source) + hit_source = """{"doc":""" + hit_source + "}" + print(hit_source) + hit_source = json.loads(hit_source) + print(hit_source) + + update_uri = es_uri + "/" + index_name + "/_update/" + hit_id + update_stat = requests.post(update_uri, json=hit_source, timeout=20) + print(update_stat.text) + + elif "200" in word_exists_simple and word_exists_full["hits"]["total"]["value"] == 0 and update == "add": + print( + f"Object {word} does not exist in index {index_name}! Proceeding to add object...") + + data_uri = es_uri + "/" + index_name + "/_doc" + data_stat = requests.post(data_uri, json=data, timeout=20) + data_stat = json.dumps(str(data_stat)) + + print(data_stat) + + if "201" in str(data_stat): + print( + f"Object {word} successfully added to index {index_name}!") + else: + print(f"Error adding object {word} to index {index_name}!") + else: + print( + f"Error checking if object {word} exists in index {index_name}!") diff --git a/src/MAGIST/NeuralDB/MongoUtils.py b/src/MAGIST/NeuralDB/MongoUtils.py index bf4427d..1f5d7b6 100644 --- a/src/MAGIST/NeuralDB/MongoUtils.py +++ b/src/MAGIST/NeuralDB/MongoUtils.py @@ -13,80 +13,86 @@ class AdminUtils(): - """Class that manages the MongoDB connection.""" + """Class that manages the MongoDB connection.""" - def __init__(self, config): - """Initialize the AdminUtils class. + def __init__(self, config): + """Initialize the AdminUtils class. - :param config: The config file(string). - """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("MongoAdminUtils") # Create a script specific logging instance + :param config: The config file(string). + """ - self.log.info("Firing up MongoDB Neural Database! Standby...") + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("MongoAdminUtils") - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) + self.log.info("Firing up MongoDB Neural Database! Standby...") - for i in config['system_administration']: - try: - self.passcode = i["sudo_password"] - except KeyError: - pass + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + with open(config) as f: + config = json.load(f) - for j in config['neural_db']: - try: - self.mgsocket = j["mongo_socket"] - except KeyError: - pass + for i in config['system_administration']: + try: + self.passcode = i["sudo_password"] + except KeyError: + pass - def initialize_neuraldb(self): - """Initialize the MongoDB connection. + for j in config['neural_db']: + try: + self.mgsocket = j["mongo_socket"] + except KeyError: + pass - :return: The MongoDB client. - """ + self.db_client = mongo.MongoClient(self.mgsocket) - command = 'systemctl start mongod' - p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) - self.log.info("NeuralDB Launched Successfully! Attempting to connect to local socket...") + def initialize_neuraldb(self): + """Initialize the MongoDB connection. - self.db_client = mongo.MongoClient(self.mgsocket) + :return: The MongoDB client. + """ - if self.db_client: - self.log.info("Mongo client linked successfully. Local DB Agent is running.") - else: - self.log.error("Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " - "something like this: mongodb://localhost:27017/") + command = 'systemctl start mongod' + p = os.system(f'echo {self.passcode}|sudo -S {command}') + self.log.info( + "NeuralDB Launched Successfully! Attempting to connect to local socket...") - return self.db_client + if self.db_client: + self.log.info( + "Mongo client linked successfully. Local DB Agent is running.") + else: + self.log.error( + "Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " + "something like this: mongodb://localhost:27017/") - def stop_db(self): - """Stop the MongoDB connection. - """ + return self.db_client - self.log.info("Shutting down MongoDB Neural Database! Standby...") - command = 'systemctl stop mongod' - p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) - self.log.info("NeuralDB Closed Successfully!") + def stop_db(self): + """Stop the MongoDB connection. + """ - def restart_db(self): - """Restart the MongoDB connection. - """ + self.log.info("Shutting down MongoDB Neural Database! Standby...") + command = 'systemctl stop mongod' + p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) + self.log.info("NeuralDB Closed Successfully!") - self.log.info("Restarting MongoDB Neural Database! Standby...") + def restart_db(self): + """Restart the MongoDB connection. + """ - command = 'systemctl restart mongod' - p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) - self.log.info("NeuralDB Re-Launched Successfully! Attempting to connect to local socket...") + self.log.info("Restarting MongoDB Neural Database! Standby...") - self.db_client = mongo.MongoClient(self.mgsocket) + command = 'systemctl restart mongod' + p = os.system('echo %s|sudo -S %s' % (self.passcode, command)) + self.log.info( + "NeuralDB Re-Launched Successfully! Attempting to connect to local socket...") - if self.db_client: - self.log.info("Mongo client linked successfully. Local DB Agent is running.") - else: - self.log.error("Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " - "something like this: mongodb://localhost:27017/") + if self.db_client: + self.log.info( + "Mongo client linked successfully. Local DB Agent is running.") + else: + self.log.error( + "Mongo client failed to connect. The Mongo socket URL could be incorrect. It should look " + "something like this: mongodb://localhost:27017/") - return self.db_client + return self.db_client diff --git a/src/MAGIST/NeuralDB/PrimaryNeuralDB.py b/src/MAGIST/NeuralDB/PrimaryNeuralDB.py index 42b8e78..e9ead56 100644 --- a/src/MAGIST/NeuralDB/PrimaryNeuralDB.py +++ b/src/MAGIST/NeuralDB/PrimaryNeuralDB.py @@ -13,414 +13,451 @@ class NeuralDB(): - """Main NeuralDB class""" - def __init__(self, config, db_client): - """Initialize NeuralDB class, parse config.json, and receive MongoDB client + """Main NeuralDB class""" + + def __init__(self, config, db_client): + """Initialize NeuralDB class, parse config.json, and receive MongoDB client + + :param config: The config(config.json) file as a string. + :param db_client: The MongoDB client from MongoUtils. + """ + + self.collections = [] + self.dbs = [] + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("NeuralDB") + self.client = db_client + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['neural_db']: + try: + self.db_string = i["db_search_zone"] + except KeyError: + pass + + def recreate_db(self): + """Recreate the databases and collections + """ + + self.log.warning( + "NeuralDB is about to reset and recreate all Databases and tables. Proceeding in 5 seconds...") + + for i in range(5): + self.log.warning("{}...".format(5 - i)) + time.sleep(1) + self.log.warning( + "Resetting and recreating all databases and tables...") + + for d in self.db_string: + if d == "vision": + self.vision = self.client['VisionDB'] + + self.obj_desc = self.vision["ObjectDesc"] + self.obj_location = self.vision["ObjectLocation"] + self.obj_obj_relation = self.vision["ObjectObjectRelation"] + self.obj_users = self.vision["ObjectUsers"] + + self.log.info( + "Vision database is included in NeuralDB search.") + + self.dbs.append(self.vision) + + self.collections.append(self.obj_desc) + self.collections.append(self.obj_location) + self.collections.append(self.obj_obj_relation) + self.collections.append(self.obj_users) + if d == "nlp": + self.nlp = self.client["NLP"] + + self.word_desc = self.nlp["WordDesc"] + self.word_location = self.nlp["WordLocation"] + + self.log.info("NLP database is included in NeuralDB search.") + + self.dbs.append(self.nlp) + + self.collections.append(self.word_desc) + self.collections.append(self.word_location) + if d == "common": + self.common = self.client["Common"] + + self.word_obj_relation = self.common["WordObjectRelation"] + + self.log.info( + "Common database is included in NeuralDB search.") + + self.dbs.append(self.common) + + self.collections.append(self.word_obj_relation) + + try: + if self.vision is None: + self.log.warning( + "Vision database was not included from NeuralDB search.") + except AttributeError: + self.log.warning( + "Vision database was not included from NeuralDB search.") + + try: + if self.nlp is None: + self.log.warning( + "NLP database was not included from NeuralDB search.") + except AttributeError: + self.log.warning( + "NLP database was not included from NeuralDB search.") + + try: + if self.common is None: + self.log.warning( + "Common database was not included from NeuralDB search.") + except AttributeError: + self.log.warning( + "Common database was not included from NeuralDB search.") + + def insert_obj_desc(self, obj_name, obj_desc): + """Insert object and its description into the Vision database. + + :param obj_name: The name of the object(string). + :param obj_desc: The description of the object(string). + """ + + self.log.info(f"Inserting object description: {obj_name} - {obj_desc}") + self.obj_desc.insert_one({"obj_name": obj_name, "obj_desc": obj_desc}) - :param config: The config(config.json) file as a string. - :param db_client: The MongoDB client from MongoUtils. - """ + def insert_obj_location(self, obj_name, obj_location): + """Insert object and its location into the Vision database. - root_log = MainLogger(config) - self.log = root_log.StandardLogger("NeuralDB") # Create a script specific logging instance - self.client = db_client + :param obj_name: The name of the object(string). + :param obj_location: The location of the object(string). + """ + self.log.info( + f"Inserting object location: {obj_name} - {obj_location}") + self.obj_location.insert_one( + {"obj_name": obj_name, "obj_location": obj_location}) - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) + def insert_obj_obj_relation(self, obj_name, second_obj_name): + """Insert object and its relation to another object into the Vision database. - for i in config['neural_db']: - try: - self.db_string = i["db_search_zone"] - except KeyError: - pass + :param obj_name: The name of the object(string). + :param second_obj_name: The name of the second object(string). + """ - def recreate_db(self): - """Recreate the databases and collections - """ + self.log.info( + f"Inserting object object relation: {obj_name} - {second_obj_name}") + self.obj_obj_relation.insert_one( + {"obj_name": obj_name, "second_obj_name": second_obj_name}) - self.log.warning("NeuralDB is about to reset and recreate all Databases and tables. Proceeding in 5 seconds...") + def insert_obj_users(self, obj_name, user_name): + """Insert object and its users into the Vision database. - for i in range(5): - self.log.warning("{}...".format(5 - i)) - time.sleep(1) - self.log.warning("Resetting and recreating all databases and tables...") + :param obj_name: The name of the object(string). + :param user_name: The name of the user(string). + """ - self.dbs = [] - self.collections = [] + self.log.info(f"Inserting object users: {obj_name} - {user_name}") + self.obj_users.insert_one( + {"obj_name": obj_name, "user_name": user_name}) - for d in self.db_string: - if d == "vision": - self.vision = self.client['VisionDB'] - - self.obj_desc = self.vision["ObjectDesc"] - self.obj_location = self.vision["ObjectLocation"] - self.obj_obj_relation = self.vision["ObjectObjectRelation"] - self.obj_users = self.vision["ObjectUsers"] - - self.log.info("Vision database is included in NeuralDB search.") - - self.dbs.append(self.vision) - - self.collections.append(self.obj_desc) - self.collections.append(self.obj_location) - self.collections.append(self.obj_obj_relation) - self.collections.append(self.obj_users) - if d == "nlp": - self.nlp = self.client["NLP"] - - self.word_desc = self.nlp["WordDesc"] - self.word_location = self.nlp["WordLocation"] - - self.log.info("NLP database is included in NeuralDB search.") + def insert_word_desc(self, word_name, word_desc): + """Insert word and its description into the NLP database. - self.dbs.append(self.nlp) + :param word_name: The name of the word(string). + :param word_desc: The description of the word(string). + """ + if word_desc is not None: + self.log.info( + f"Inserting word description: {word_name} - {word_desc}") + self.word_desc.insert_one( + {"word_name": word_name, "word_desc": word_desc}) - self.collections.append(self.word_desc) - self.collections.append(self.word_location) - if d == "common": - self.common = self.client["Common"] + def insert_word_location(self, word_name, word_location): + """Insert word and its location into the NLP database. - self.word_obj_relation = self.common["WordObjectRelation"] + :param word_name: The name of the word(string). + :param word_location: The location of the word(string). + """ - self.log.info("Common database is included in NeuralDB search.") + self.log.info( + f"Inserting word location: {word_name} - {word_location}") + self.word_location.insert_one( + {"word_name": word_name, "word_location": word_location}) + + def insert_word_obj_relation(self, word_name, obj_name): + """Insert word and its relation to an object into the NLP database. + + :param word_name: The name of the word(string). + :param obj_name: The name of the object(string). + """ + + self.log.info( + f"Inserting word object relation: {word_name} - {obj_name}") + self.word_obj_relation.insert_one( + {"word_name": word_name, "word_relation": obj_name}) - self.dbs.append(self.common) + def search_obj_details(self, obj_name): + """Search for object all details in the Vision database. - self.collections.append(self.word_obj_relation) + :param obj_name: The name of the object(string). - try: - if self.vision is None: - self.log.warning("Vision database was not included from NeuralDB search.") - except AttributeError: - self.log.warning("Vision database was not included from NeuralDB search.") + :return: A dictionary containing the object details. + """ - try: - if self.nlp is None: - self.log.warning("NLP database was not included from NeuralDB search.") - except AttributeError: - self.log.warning("NLP database was not included from NeuralDB search.") + data = [] + self.log.info(f"Searching object details: {obj_name}") - try: - if self.common is None: - self.log.warning("Common database was not included from NeuralDB search.") - except AttributeError: - self.log.warning("Common database was not included from NeuralDB search.") + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - def insert_obj_desc(self, obj_name, obj_desc): - """Insert object and its description into the Vision database. + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"obj_name": re.compile(rf"\b{obj_name}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - :param obj_name: The name of the object(string). - :param obj_desc: The description of the object(string). - """ + def search_obj_desc(self, keyword): + """Search for object descriptions by keyword in the Vision database. - self.log.info(f"Inserting object description: {obj_name} - {obj_desc}") - self.obj_desc.insert_one({"obj_name": obj_name, "obj_desc": obj_desc}) - def insert_obj_location(self, obj_name, obj_location): - """Insert object and its location into the Vision database. + :param keyword: The keyword to search for(string). - :param obj_name: The name of the object(string). - :param obj_location: The location of the object(string). - """ - self.log.info(f"Inserting object location: {obj_name} - {obj_location}") - self.obj_location.insert_one({"obj_name": obj_name, "obj_location": obj_location}) - def insert_obj_obj_relation(self, obj_name, second_obj_name): - """Insert object and its relation to another object into the Vision database. + :return: A dictionary containing the object descriptions. + """ - :param obj_name: The name of the object(string). - :param second_obj_name: The name of the second object(string). - """ + data = [] + self.log.info(f"Searching object details by keyword: {keyword}") - self.log.info(f"Inserting object object relation: {obj_name} - {second_obj_name}") - self.obj_obj_relation.insert_one({"obj_name": obj_name, "second_obj_name": second_obj_name}) - def insert_obj_users(self, obj_name, user_name): - """Insert object and its users into the Vision database. + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - :param obj_name: The name of the object(string). - :param user_name: The name of the user(string). - """ + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"obj_desc": re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - self.log.info(f"Inserting object users: {obj_name} - {user_name}") - self.obj_users.insert_one({"obj_name": obj_name, "user_name": user_name}) + def search_obj_location(self, location): + """Search for object locations by location in the Vision database. - def insert_word_desc(self, word_name, word_desc): - """Insert word and its description into the NLP database. + :param location: The location to search for(string). - :param word_name: The name of the word(string). - :param word_desc: The description of the word(string). - """ - if word_desc != None: - self.log.info(f"Inserting word description: {word_name} - {word_desc}") - self.word_desc.insert_one({"word_name": word_name, "word_desc": word_desc}) - def insert_word_location(self, word_name, word_location): - """Insert word and its location into the NLP database. + :return: A dictionary containing the object locations. + """ - :param word_name: The name of the word(string). - :param word_location: The location of the word(string). - """ + data = [] + self.log.info(f"Searching object details by location: {location}") - self.log.info(f"Inserting word location: {word_name} - {word_location}") - self.word_location.insert_one({"word_name": word_name, "word_location": word_location}) - def insert_word_obj_relation(self, word_name, obj_name): - """Insert word and its relation to an object into the NLP database. + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - :param word_name: The name of the word(string). - :param obj_name: The name of the object(string). - """ + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"obj_location": re.compile( + rf"\b{location}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - self.log.info(f"Inserting word object relation: {word_name} - {obj_name}") - self.word_obj_relation.insert_one({"word_name": word_name, "word_relation": obj_name}) + def search_obj_user(self, user): + """Search for object users by user in the Vision database. - def search_obj_details(self, obj_name): - """Search for object all details in the Vision database. + :param user: The user to search for(string). - :param obj_name: The name of the object(string). + :return: A dictionary containing the object users. + """ - :return: A dictionary containing the object details. - """ + data = [] + self.log.info(f"Searching object details by user: {user}") - data = [] - self.log.info(f"Searching object details: {obj_name}") + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"user_name": re.compile(rf"\b{user}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"obj_name": re.compile(rf"\b{obj_name}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data + def search_word_details(self, word): + """Search for word details in the NLP database. - def search_obj_desc(self, keyword): - """Search for object descriptions by keyword in the Vision database. + :param word: The word to search for(string). - :param keyword: The keyword to search for(string). + :return: A dictionary containing the word details. + """ - :return: A dictionary containing the object descriptions. - """ + data = [] + self.log.info(f"Searching word details: {word}") - data = [] - self.log.info(f"Searching object details by keyword: {keyword}") + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"word_name": re.compile(rf"\b{word}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"obj_desc" : re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data + def search_word_desc(self, keyword): + """Search for word descriptions by keyword in the NLP database. - def search_obj_location(self, location): - """Search for object locations by location in the Vision database. + :param keyword: The keyword to search for(string). - :param location: The location to search for(string). + :return: A dictionary containing the word descriptions. + """ - :return: A dictionary containing the object locations. - """ + data = [] + self.log.info(f"Searching word details by keyword: {keyword}") - data = [] - self.log.info(f"Searching object details by location: {location}") + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"word_desc": re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"obj_location" : re.compile(rf"\b{location}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data + def search_word_location(self, location): + """Search for word locations by location in the NLP database. - def search_obj_user(self, user): - """Search for object users by user in the Vision database. + :param location: The location to search for(string). - :param user: The user to search for(string). + :return: A dictionary containing the word locations. + """ - :return: A dictionary containing the object users. - """ + data = [] + self.log.info(f"Searching word details by location: {location}") - data = [] - self.log.info(f"Searching object details by user: {user}") - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"user_name" : re.compile(rf"\b{user}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data - - - - - - def search_word_details(self, word): - """Search for word details in the NLP database. - - :param word: The word to search for(string). - - :return: A dictionary containing the word details. - """ - - data = [] - self.log.info(f"Searching word details: {word}") - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"word_name" : re.compile(rf"\b{word}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data - - def search_word_desc(self, keyword): - """Search for word descriptions by keyword in the NLP database. - - :param keyword: The keyword to search for(string). - - :return: A dictionary containing the word descriptions. - """ - - data = [] - self.log.info(f"Searching word details by keyword: {keyword}") - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"word_desc" : re.compile(rf"\b{keyword}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data - - def search_word_location(self, location): - """Search for word locations by location in the NLP database. - - :param location: The location to search for(string). - - :return: A dictionary containing the word locations. - """ - - data = [] - self.log.info(f"Searching word details by location: {location}") - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"word_location" : re.compile(rf"\b{location}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data - - def search_word_relation(self, relation): - """Search for word relations by relation in the NLP database. - - :param relation: The relation to search for(string). - - :return: A dictionary containing the word relations. - """ - - data = [] - self.log.info(f"Searching word details by relation: {relation}") - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - - for i in d.list_collection_names(): - self.log.info(f" ===> Collection: {i}") - for j in self.vision[i].find({"word_relation" : re.compile(rf"\b{relation}\b", re.IGNORECASE)}): - self.log.info(f" ===> {j}") - data.append(j) - return data - - - def search_entire_db(self, term): - """Search for entire database by term in the NLP database. - - :param term: The term to search for(string). - - :return: A dictionary containing the entire database. - """ - - self._locals_search = locals() - - results = [] - - self.log.info(f"Searching entire database for: {term}") - - final_results = [] - - for d in self.dbs: - self.log.info(f"===> Database: {d.name}") - for c in d.list_collection_names(): - self.log.info(f" ===> Collection: {c}") - exec(f"db_col_search = self.client.{d.name}.{c}", self._locals_search) - db_col_search = self._locals_search['db_col_search'] - - cursor = d[c].find({}) - keys = list(cursor.next().keys()) - - for key in keys: - self.log.info(f" ===> Key: {c}") - search = db_col_search.find({key : re.compile(rf"\b{term}\b", re.IGNORECASE)}) - results.append(search) - try: - a = search.next() - self.log.info(f" ===> Found: {a}") - final_results.append(a) - except: - self.log.info(f" ===> Found: None") - - return final_results - - - - def remove_duplicates(self): - """Remove duplicates from the Vision database. - """ - - self._locals = locals() - print(self.vision.ObjectDesc) - for d in self.dbs: - for i in d.list_collection_names(): - exec(f"db_col = self.client.{d.name}.{i}", self._locals) - db_col = self._locals['db_col'] - - repeated_val = "" - - if "vision" in d.name.lower(): - repeated_val = "obj_name" - print("vision") - if "nlp" in d.name.lower(): - repeated_val = "word_name" - print("nlp") - - replic = db_col.aggregate([ # Cursor with all duplicated documents - {'$group': { - '_id': {repeated_val: f'${repeated_val}'}, # Duplicated field - 'uniqueIDs': {'$addToSet': '$_id'}, - 'total': {'$sum': 1} - } - }, - {'$match': { - 'total': {'$gt': 1} # Holds how many duplicates for each group, if you need it. - } - } - ]) - # Result is a list of lists of ObjectsIds - for i in replic: - for idx, j in enumerate(i['uniqueIDs']): # It holds the ids of all duplicates - if idx != 0: # Jump over first element to keep it - db_col.delete_one({'_id': j}) + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"word_location": re.compile( + rf"\b{location}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_word_relation(self, relation): + """Search for word relations by relation in the NLP database. + + :param relation: The relation to search for(string). + + :return: A dictionary containing the word relations. + """ + + data = [] + self.log.info(f"Searching word details by relation: {relation}") + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + + for i in d.list_collection_names(): + self.log.info(f" ===> Collection: {i}") + for j in self.vision[i].find( + {"word_relation": re.compile( + rf"\b{relation}\b", re.IGNORECASE)}): + self.log.info(f" ===> {j}") + data.append(j) + return data + + def search_entire_db(self, term): + """Search for entire database by term in the NLP database. + + :param term: The term to search for(string). + + :return: A dictionary containing the entire database. + """ + + self._locals_search = locals() + + results = [] + + self.log.info(f"Searching entire database for: {term}") + + final_results = [] + + for d in self.dbs: + self.log.info(f"===> Database: {d.name}") + for c in d.list_collection_names(): + self.log.info(f" ===> Collection: {c}") + exec( + f"db_col_search = self.client.{d.name}.{c}", + self._locals_search) + db_col_search = self._locals_search['db_col_search'] + + cursor = d[c].find({}) + keys = list(cursor.next().keys()) + + for key in keys: + self.log.info(f" ===> Key: {c}") + search = db_col_search.find( + {key: re.compile(rf"\b{term}\b", re.IGNORECASE)}) + results.append(search) + try: + a = search.next() + self.log.info(f" ===> Found: {a}") + final_results.append(a) + except BaseException: + self.log.info(f" ===> Found: None") + + return final_results + + def remove_duplicates(self): + """Remove duplicates from the Vision database. + """ + + self._locals = locals() + print(self.vision.ObjectDesc) + for d in self.dbs: + for i in d.list_collection_names(): + exec(f"db_col = self.client.{d.name}.{i}", self._locals) + db_col = self._locals['db_col'] + + repeated_val = "" + + if "vision" in d.name.lower(): + repeated_val = "obj_name" + print("vision") + if "nlp" in d.name.lower(): + repeated_val = "word_name" + print("nlp") + + replic = db_col.aggregate([ # Cursor with all duplicated documents + {'$group': { + # Duplicated field + '_id': {repeated_val: f'${repeated_val}'}, + 'uniqueIDs': {'$addToSet': '$_id'}, + 'total': {'$sum': 1} + } + }, + {'$match': { + # Holds how many duplicates for each group, if you need + # it. + 'total': {'$gt': 1} + } + } + ]) + # Result is a list of lists of ObjectsIds + for i in replic: + for idx, j in enumerate( + i['uniqueIDs']): # It holds the ids of all duplicates + if idx != 0: # Jump over first element to keep it + db_col.delete_one({'_id': j}) diff --git a/src/MAGIST/TaskManagment/ThreadedQueue.py b/src/MAGIST/TaskManagment/ThreadedQueue.py index 5d879b0..053a43d 100644 --- a/src/MAGIST/TaskManagment/ThreadedQueue.py +++ b/src/MAGIST/TaskManagment/ThreadedQueue.py @@ -6,118 +6,120 @@ import queue import threading import uuid -import numpy as np -import pathlib import json +import pathlib +import numpy as np from ..Utils.LogMaster.log_init import MainLogger class MainPriorityQueue(): - """Main Priority Queue Class.""" - - def __init__(self, config): - """Initialize the queue. + """Main Priority Queue Class.""" - :param config: The config file(config.json). - """ + def __init__(self, config): + """Initialize the queue. - self.q = queue.PriorityQueue() + :param config: The config file(config.json). + """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("QueueController") # Create a script specific logging instance + self.guid = uuid.uuid4() + self.q = queue.PriorityQueue() - self.function_returns = [] + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("QueueController") - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) + self.function_returns = [] - for i in config['task_management']: - try: - self.worker_threads = i["num_of_worker_threads"] - except KeyError: - pass + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + with open(config) as f: + config = json.load(f) - def __worker(self): - """The worker thread. This actually executes the tasks in the queue. - """ + for i in config['task_management']: + try: + self.worker_threads = i["num_of_worker_threads"] + except KeyError: + pass - while True: - items = self.q.get() - items = items[1] - func = items[0] - args = items[1:] - # print(f'Working on {args}') + def __worker(self): + """The worker thread. This actually executes the tasks in the queue. + """ - last_item = args[-1] # name - second_last_item = args[-2] # priority - third_last_item = args[-3] # guid + while True: + items = self.q.get() + items = items[1] + func = items[0] + args = items[1:] + # print(f'Working on {args}') - args = args[:len(args) - 3] + last_item = args[-1] # name + second_last_item = args[-2] # priority + third_last_item = args[-3] # guid - self.log.info(f'Received task: {last_item} with priority {second_last_item}. Unique ID assigned: {third_last_item}. Executing...') - [*returns] = [func(*args)] - self.log.info(f'Finished {last_item} successfully.') - self.q.task_done() - returns = np.array(returns) - self.function_returns.append([third_last_item, returns]) - # self.function_returns = np.squeeze(self.function_returns) + args = args[:len(args) - 3] - def put_queue(self, function, *args, name="Unnamed", priority=None): - """Add a task to the queue. + self.log.info( + f'Received task: {last_item} with priority {second_last_item}. ' + f'Unique ID assigned: {third_last_item}. Executing...') + [*returns] = [func(*args)] + self.log.info(f'Finished {last_item} successfully.') + self.q.task_done() + returns = np.array(returns) + self.function_returns.append([third_last_item, returns]) + # self.function_returns = np.squeeze(self.function_returns) - :param function: The function to be executed. NOTE: This must be in the form of Class.put_queue(function...), - not Class.put_queue(function()...). - :param args: The arguments to be passed to the function. This can be any number of args. - :param name: The name of the task. - :param priority: The priority of the task. + def put_queue(self, function, *args, name="Unnamed", priority=None): + """Add a task to the queue. - :return: The unique ID of the task. - """ + :param function: The function to be executed. NOTE: This must be in the form of Class.put_queue(function...), + not Class.put_queue(function()...). + :param args: The arguments to be passed to the function. This can be any number of args. + :param name: The name of the task. + :param priority: The priority of the task. - args = list(args) + :return: The unique ID of the task. + """ - self.guid = uuid.uuid4() + args = list(args) - for i in args: - if i == name or i == priority: - raise ValueError( - "Name or priority cannot be used as argument. Please use priority= and name= in the function call.") + for i in args: + if i in (name, priority): + raise ValueError( + "Name or priority cannot be used as argument. Please use priority= and name= in the function call.") - self.q.put((priority, (function, *args, self.guid, priority, name))) + self.q.put((priority, (function, *args, self.guid, priority, name))) - return self.guid + return self.guid - def detach_thread(self): - """Detach the thread from the main thread. - """ + def detach_thread(self): + """Detach the thread from the main thread. + """ - # Turn-on the worker thread. - for i in range(self.worker_threads): - threading.Thread(target=self.__worker, daemon=True).start() - self.log.info("Thread created and daemonized. Queue started...") + # Turn-on the worker thread. + for i in range(self.worker_threads): + threading.Thread(target=self.__worker, daemon=True).start() + self.log.info("Thread created and daemonized. Queue started...") - def join_thread(self): - """Join the queue thread with main. - """ + def join_thread(self): + """Join the queue thread with main. + """ - self.log.info("Attempting to join main thread...") - self.q.join() - self.log.info("Queue merge finished.") + self.log.info("Attempting to join main thread...") + self.q.join() + self.log.info("Queue merge finished.") - def search_results(self, query): - """Search the results for a specific task by ID. + def search_results(self, query): + """Search the results for a specific task by ID. - :param query: The unique ID of the task. NOTE: This must be a UUID object. + :param query: The unique ID of the task. NOTE: This must be a UUID object. - :return: The results of the task. - """ + :return: The results of the task. + """ - r = self.function_returns - r = np.array(r) - r = r[r[:, 0] == query] - r = np.squeeze(r) + r = self.function_returns + r = np.array(r) + r = r[r[:, 0] == query] + r = np.squeeze(r) - return np.squeeze(r[1]) + return np.squeeze(r[1]) diff --git a/src/MAGIST/Utils/LogMaster/log_init.py b/src/MAGIST/Utils/LogMaster/log_init.py index db4db52..231d85d 100644 --- a/src/MAGIST/Utils/LogMaster/log_init.py +++ b/src/MAGIST/Utils/LogMaster/log_init.py @@ -5,7 +5,9 @@ import logging import json -import os, pathlib +import os +import pathlib + class CustomFormatter(logging.Formatter): @@ -16,14 +18,14 @@ class CustomFormatter(logging.Formatter): red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" - format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + format_s = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" FORMATS = { - logging.DEBUG: blue + format + reset, - logging.INFO: green + format + reset, - logging.WARNING: yellow + format + reset, - logging.ERROR: red + format + reset, - logging.CRITICAL: bold_red + format + reset + logging.DEBUG: blue + format_s + reset, + logging.INFO: green + format_s + reset, + logging.WARNING: yellow + format_s + reset, + logging.ERROR: red + format_s + reset, + logging.CRITICAL: bold_red + format_s + reset } def format(self, record): @@ -31,6 +33,7 @@ def format(self, record): formatter = logging.Formatter(log_fmt) return formatter.format(record) + class MainLogger(): # Logging Class @@ -40,9 +43,10 @@ def __init__(self, config): :param config: A relative or absolute path to master config JSON file. """ config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) + config = config.resolve() # Find absolute path from a relative one. + + with open(config) as f: + config = json.load(f) for i in config['paths']: try: @@ -56,21 +60,28 @@ def __init__(self, config): pass self.log_dir = pathlib.Path(self.log_dir) - self.log_dir = self.log_dir.resolve() # Find absolute path from a relative one. + # Find absolute path from a relative one. + self.log_dir = self.log_dir.resolve() self.log_dir = str(self.log_dir) def StandardLogger(self, name): logger = logging.getLogger(name) - if not self.verbose: # Enable verbose depending on flag set by the config file. + if not self.verbose: # Enable verbose depending on flag set by the config file. logger.setLevel(logging.WARNING) else: logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages try: - fh = logging.FileHandler(os.path.join(self.log_dir, 'complete.log')) + fh = logging.FileHandler( + os.path.join( + self.log_dir, + 'complete.log')) except FileNotFoundError: os.makedirs(self.log_dir) - fh = logging.FileHandler(os.path.join(self.log_dir, 'complete.log')) + fh = logging.FileHandler( + os.path.join( + self.log_dir, + 'complete.log')) # create console handler with a higher log level error = logging.StreamHandler() @@ -78,7 +89,8 @@ def StandardLogger(self, name): error.setFormatter(CustomFormatter()) # create formatter and add it to the handlers - formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) # error.setFormatter(formatter) @@ -86,9 +98,7 @@ def StandardLogger(self, name): logger.addHandler(fh) logger.addHandler(error) - logger.info(f"{name}'s LogMaster Instance Initialized Successfully ===> {os.path.join(self.log_dir, 'complete.log')}") + logger.info( + f"{name}'s LogMaster Instance Initialized Successfully ===> {os.path.join(self.log_dir, 'complete.log')}") return logger - - - diff --git a/src/MAGIST/Utils/WebScraper/google.py b/src/MAGIST/Utils/WebScraper/google.py index 763e705..0271050 100644 --- a/src/MAGIST/Utils/WebScraper/google.py +++ b/src/MAGIST/Utils/WebScraper/google.py @@ -6,190 +6,223 @@ images. """ +import os +import pathlib +import json import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.firefox.options import Options from google_images_search import GoogleImagesSearch -import os -import pathlib, json from googleapiclient.errors import HttpError from ..LogMaster.log_init import MainLogger class GoogleScraper: - """Main Google Images scraping and downloading tool.""" - - def __init__(self, config): - """Initializes the class and authenticates Google Search API with credentials and parses config file. It also - initializes the logger. - - :param config: A relative or absolute path to master config JSON file. - :param dev_api_key DEPRECATED: API key acquired from Google Search API webpage. - :param project_cx_id DEPRECATED: The Search Engine ID provided by Google per Google Developer Project. - - Note: The CX ID is hard to find. To find it, first go to: http://www.google.com/cse/manage/all. Select your - project and the ID will be called: "Search engine ID". Go to this StackOverflow question and PyPi Post for more - info: https://stackoverflow.com/questions/6562125/getting-a-cx-id-for-custom-search-google-api-python & - https://pypi.org/project/Google-Images-Search/ - """ - - root_log = MainLogger(config) - self.log = root_log.StandardLogger("GoogleScraper") # Create a script specific logging instance - - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) - - for i in config['api_authentication']: - try: - google_conf = i["google"] - for j in google_conf: - try: - self.dev_api_key = j["api_key"] - except KeyError: - pass - try: - self.project_cx_id = j["project_cx"] - except KeyError: - pass - try: - self.GIS_verbose = j["GIS_downloader_verbose"] - except KeyError: - pass - except KeyError: - pass - - def __my_progressbar(self, url, progress): - """Defines custom progressbar to visualize the download process for the image downloader. - - :param url: The URL from which the downloader is currently downloading the image from. - :param progress: The percentage of progress in downloading the file. - :return: None - """ - self.log.info(url + ' ' + str(progress) + '%') - - # t = tqdm(total=100, desc=url) - # t.update(progress) - - # try: - # if(progress == 1): - # t = tqdm(total=100, desc=url) - # else: - # t.update(progress) - # except: - # pass - - def reverse_image_search(self, image_path): - """Takes a given image path and finds the object name using Google Reverse Image Search and scraping. - - :param image_path: Relative or absolute image path. - :return: Object name(String) - """ - filePath = image_path - - filePath = pathlib.Path(filePath) - filePath = filePath.resolve() # Find the absolute path from relative one. - filePath = str(filePath) - - searchUrl = 'http://www.google.com/searchbyimage/upload' - headers = { - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Change header to ensure that Google Search still functions - multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''} - - response = requests.post(searchUrl, files=multipart, allow_redirects=False) - fetchUrl = response.headers['Location'] - - options = Options() - options.add_argument("--disable-extensions") - options.add_argument("--disable-gpu") - options.add_argument("--no-sandbox") # linux only - options.add_argument("--headless") - options.headless = True # also works - nav = webdriver.Firefox(options=options) - nav.get(fetchUrl) - self.log.info("Selenium reverse search complete.") - - try: - soup = BeautifulSoup(nav.page_source, 'html.parser') - link = soup.find_all("a", {"class": "fKDtNb"})[0] - link = str(link) - start = link.find(">") + len(">") - end = link.find("") + len(">") + end = link.find(" Loading data...") - train, test = self.load_data() - self.log.info("Automated Trainer --> Data loaded successfully.") - self.log.info("Automated Trainer --> Building model...") - self.compile_model() - self.log.info("Automated Trainer --> Model built successfully.") - self.log.info("Automated Trainer --> Setting up callbacks...") - self.callbacks_init() - self.log.info("Automated Trainer --> Callbacks setup successfully.") - self.log.info("Automated Trainer --> Training model...") - self.train() - self.log.info("Automated Trainer --> Training completed successfully.") + def __init__(self, config): + """Initializes the model and sets training variables. + + :param config: The configuration file(JSON). + """ + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("MAGIST_Lite_CNN") + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['tf_lite_detector']: + try: + self.data_path = i["data_path"] + except KeyError: + pass + try: + self.TensorBoard_log_dir = i["TensorBoard_log_dir"] + except KeyError: + pass + try: + self.TF_ckpt_path = i["TF_ckpt_path"] + except KeyError: + pass + try: + self.input_image_size = i["input_image_size"] + except KeyError: + pass + try: + self.epochs = i["epochs"] + except KeyError: + pass + try: + self.batch_size = i["batch_size"] + except KeyError: + pass + try: + self.seed = i["seed"] + except KeyError: + pass + try: + self.validation_split = i["validation_split"] + except KeyError: + pass + try: + self.export_path = i["export_full_model"] + except KeyError: + pass + try: + self.grayscale = i["grayscale"] + except KeyError: + pass + + self.data_path = pathlib.Path(self.data_path) + # Find absolute path from a relative one. + self.data_path = self.data_path.resolve() + self.data_path = str(self.data_path) + + self.TensorBoard_log_dir = pathlib.Path(self.TensorBoard_log_dir) + # Find absolute path from a relative one. + self.TensorBoard_log_dir = self.TensorBoard_log_dir.resolve() + self.TensorBoard_log_dir = str(self.TensorBoard_log_dir) + + self.TF_ckpt_path = pathlib.Path(self.TF_ckpt_path) + # Find absolute path from a relative one. + self.TF_ckpt_path = self.TF_ckpt_path.resolve() + self.TF_ckpt_path = str(self.TF_ckpt_path) + + self.export_path = pathlib.Path(self.export_path) + # Find absolute path from a relative one. + self.export_path = self.export_path.resolve() + self.export_path = str(self.export_path) + + self.epoch_arr = [] + self.train_loss_arr = [] + self.train_accuracy_arr = [] + self.test_loss_arr = [] + self.test_accuracy_arr = [] + + def load_data(self): + """Loads the text_ds from the data_path. + + :return: The train_ds and test_ds. + """ + if self.grayscale: + self.train_ds = tf.keras.utils.image_dataset_from_directory( + self.data_path, + labels='inferred', + label_mode='int', + class_names=None, + color_mode='grayscale', + batch_size=self.batch_size, + image_size=tuple(self.input_image_size), + shuffle=True, + seed=self.seed, + validation_split=self.validation_split, + subset='training', + interpolation='bilinear', + follow_links=False, + crop_to_aspect_ratio=False, + # class_mode='sparse' + ) + + self.val_ds = tf.keras.utils.image_dataset_from_directory( + self.data_path, + labels='inferred', + label_mode='int', + class_names=None, + color_mode='grayscale', + batch_size=self.batch_size, + image_size=tuple(self.input_image_size), + shuffle=True, + seed=self.seed, + validation_split=self.validation_split, + subset='validation', + interpolation='bilinear', + follow_links=False, + crop_to_aspect_ratio=False, + # class_mode='sparse' + ) + else: + self.train_ds = tf.keras.utils.image_dataset_from_directory( + self.data_path, + labels='inferred', + label_mode='int', + class_names=None, + color_mode='rgb', + batch_size=self.batch_size, + image_size=tuple(self.input_image_size), + shuffle=True, + seed=self.seed, + validation_split=self.validation_split, + subset='training', + interpolation='bilinear', + follow_links=False, + crop_to_aspect_ratio=False, + # class_mode='sparse' + ) + + self.val_ds = tf.keras.utils.image_dataset_from_directory( + self.data_path, + labels='inferred', + label_mode='int', + class_names=None, + color_mode='rgb', + batch_size=self.batch_size, + image_size=tuple(self.input_image_size), + shuffle=True, + seed=self.seed, + validation_split=self.validation_split, + subset='validation', + interpolation='bilinear', + follow_links=False, + crop_to_aspect_ratio=False, + # class_mode='sparse' + ) + + self.log.info("Data loaded and batched") + + return self.train_ds, self.val_ds + + def compile_model(self): + """Compiles the model. + + :return: The compiled model. + """ + self.model = _CNN() + + self.loss_object = tf.keras.losses.SparseCategoricalCrossentropy( + from_logits=True) + + self.optimizer = tf.keras.optimizers.Adam() + + self.train_loss = tf.keras.metrics.Mean(name='train_loss') + self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + name='train_accuracy') + + self.test_loss = tf.keras.metrics.Mean(name='test_loss') + self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + name='test_accuracy') + + self.log.info("Model optimizer and loss function set and compiled.") + + return self.model + + def callbacks_init(self): + """Initializes the callbacks. + + :return: The configured callbacks. + """ + self.current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + self.train_log_dir = f'{self.TensorBoard_log_dir}/train_logs/gradient_tape/' + self.current_time + '/train' + self.test_log_dir = f'{self.TensorBoard_log_dir}/train_logs/gradient_tape/' + self.current_time + '/test' + self.train_summary_writer = tf.summary.create_file_writer( + self.train_log_dir) + self.test_summary_writer = tf.summary.create_file_writer( + self.test_log_dir) + + self.log_dir = f"{self.TensorBoard_log_dir}/tf_histograms/fit/" + \ + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + self.tensorboard_callback = tf.keras.callbacks.TensorBoard( + log_dir=self.log_dir, histogram_freq=1, update_freq='batch') + self.tensorboard_callback.set_model(self.model) + + self.callbacks = tf.keras.callbacks.CallbackList( + [self.tensorboard_callback]) + + self.ckpt = tf.train.Checkpoint( + step=tf.Variable(1), + optimizer=self.optimizer, + net=self.model, + iterator=self.train_ds) + self.manager = tf.train.CheckpointManager( + self.ckpt, f'{self.TF_ckpt_path}', max_to_keep=4000) + + self.log.info( + f"Callbacks initialized. TensorBoard histograms are logged to {self.log_dir}/tf_histograms. " + f"TensorBoard training text_ds is stored in {self.log_dir}/train_logs/gradient_tape. Checkpoint " + f"saved to {self.TF_ckpt_path}!") + + self.ckpt.restore(self.manager.latest_checkpoint) + if self.manager.latest_checkpoint: + self.log.info( + "Restored from {}".format( + self.manager.latest_checkpoint)) + else: + self.log.info("Initializing from scratch.") + + return self.ckpt, self.manager, self.callbacks + + @tf.function + def __train_step(self, images, labels): + with tf.GradientTape() as tape: + # training=True is only needed if there are layers with different + # behavior during training versus inference (e.g. Dropout). + self.predictions = self.model(images, training=True) + self.loss = self.loss_object(labels, self.predictions) + self.gradients = tape.gradient( + self.loss, self.model.trainable_variables) + self.optimizer.apply_gradients( + zip(self.gradients, self.model.trainable_variables)) + + self.train_loss(self.loss) + self.train_accuracy(labels, self.predictions) + + @tf.function + def __test_step(self, images, labels): + # training=False is only needed if there are layers with different + # behavior during training versus inference (e.g. Dropout). + predictions = self.model(images, training=False) + t_loss = self.loss_object(labels, predictions) + + self.test_loss(t_loss) + self.test_accuracy(labels, predictions) + + def train(self): + """Trains the model and exports training data. + """ + self.callbacks.on_train_begin() + self.log.info("Training started successfully.") + for epoch in (pbar_epoch:= tqdm(range(self.epochs), ascii="░▒█")): + self.callbacks.on_epoch_begin(epoch) + pbar_epoch.set_description("Epoch Progress: ") + # Reset the metrics at the start of the next epoch + self.train_loss.reset_states() + self.train_accuracy.reset_states() + self.test_loss.reset_states() + self.test_accuracy.reset_states() + + for images, labels in (pbar_train:= tqdm(self.train_ds.take(self.batch_size), leave=False, ascii="░▒█")): + self.callbacks.on_train_batch_begin(images) + pbar_train.set_description("Train Step: ") + self.__train_step(images, labels) + pbar_train.set_postfix( + {"loss": float(self.train_loss.result()), + "accuracy": float(self.train_accuracy.result()) * 100}) + self.ckpt.step.assign_add(1) + with self.train_summary_writer.as_default(): + tf.summary.scalar('loss', self.train_loss.result(), step=epoch) + tf.summary.scalar( + 'accuracy', + self.train_accuracy.result(), + step=epoch) + + for test_images, test_labels in ( + pbar_test:= tqdm(self.val_ds.take(self.batch_size), leave=False, ascii="░▒█")): + pbar_test.set_description("Test Step: ") + self.__test_step(test_images, test_labels) + pbar_test.set_postfix( + {"loss": float(self.test_loss.result()), + "accuracy": float(self.test_accuracy.result()) * 100}) + with self.test_summary_writer.as_default(): + tf.summary.scalar('loss', self.test_loss.result(), step=epoch) + tf.summary.scalar( + 'accuracy', + self.test_accuracy.result(), + step=epoch) + + if ((int(self.ckpt.step) - 1) % self.batch_size) == 0: + save_path = self.manager.save() + self.log.info("Saved checkpoint for step {}: {}".format( + int(self.ckpt.step) - 1, save_path)) + + self.epoch_arr.append(epoch + 1) + self.train_loss_arr.append(self.train_loss.result()) + self.train_accuracy_arr.append(self.train_accuracy.result() * 100) + self.test_loss_arr.append(self.test_loss.result()) + self.test_accuracy_arr.append(self.test_accuracy.result() * 100) + + pbar_epoch.set_postfix( + {"train_loss": float(self.train_loss.result()), + "test_loss": float(self.test_loss.result()), + "test_accuracy": float(self.test_accuracy.result()) * 100, + "train_accuracy": float(self.train_accuracy.result()) * 100}) + self.callbacks.on_epoch_end(epoch) + self.callbacks.on_train_end() + + for i in range(len(self.epoch_arr)): + self.log.info( + f'Epoch {self.epoch_arr[i]}, ' + f'Loss: {self.train_loss_arr[i]}, ' + f'Accuracy: {self.train_accuracy_arr[i]}, ' + f'Test Loss: {self.test_loss_arr[i]}, ' + f'Test Accuracy: {self.test_accuracy_arr[i]}' + ) + + self.model.save( + self.export_path, + save_format="tf", + include_optimizer=True) + self.log.info("Model exported to {}.".format(self.export_path)) + + def get_class_names(self): + """Returns the class names. + + :return: List of class names. + """ + if self.train_ds is None or self.val_ds is None: + self.log.error( + "Dataset not loaded! Please load dataset first using 'class.load_data()'.") + return None + train_classes = self.train_ds.class_names + test_classes = self.val_ds.class_names + if train_classes == test_classes: + return train_classes + else: + self.log.error( + "Class names do not match between train and test datasets. Please check your text_ds.") + return None + + def __call__(self): + """Calls the train method.""" + self.log.info("Automated Trainer --> Loading data...") + train, test = self.load_data() + self.log.info("Automated Trainer --> Data loaded successfully.") + self.log.info("Automated Trainer --> Building model...") + self.compile_model() + self.log.info("Automated Trainer --> Model built successfully.") + self.log.info("Automated Trainer --> Setting up callbacks...") + self.callbacks_init() + self.log.info("Automated Trainer --> Callbacks setup successfully.") + self.log.info("Automated Trainer --> Training model...") + self.train() + self.log.info("Automated Trainer --> Training completed successfully.") class MAGIST_CNN_Predictor(): - def __init__(self, config): - """Initializes the predictor and config. - - :param config: A dictionary containing the config.json. - """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("MAGIST_Lite_Predictor") # Create a script specific logging instance - - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) - - for i in config['tf_lite_detector']: - try: - self.TF_ckpt_path = i["TF_ckpt_path"] - except KeyError: - pass - try: - self.export_path = i["export_full_model"] - except KeyError: - pass - try: - self.input_image_size = i["input_image_size"] - except KeyError: - pass - try: - self.grayscale = i["grayscale"] - except KeyError: - pass - - self.export_path = pathlib.Path(self.export_path) - self.export_path = self.export_path.resolve() # Find absolute path from a relative one. - self.export_path = str(self.export_path) - - self.TF_ckpt_path = pathlib.Path(self.TF_ckpt_path) - self.TF_ckpt_path = self.TF_ckpt_path.resolve() # Find absolute path from a relative one. - self.TF_ckpt_path = str(self.TF_ckpt_path) - - self.imported = tf.keras.models.load_model(self.export_path, compile=False) - self.log.info("Model imported from {}.".format(self.export_path)) - - # latest = tf.train.latest_checkpoint(self.TF_ckpt_path) - - # self.imported.load_weights(latest) - self.imported.summary() - - def __load(self, filename): - """Loads a file from the given filename. - - :param filename: The filename to load. - - :return: The loaded image file as np.array. - """ - np_image = Image.open(filename) - np_image = np.array(np_image).astype('float32') / 255 - if self.grayscale: - np_image = transform.resize(np_image, (self.input_image_size[0], self.input_image_size[1], 1)) - else: - np_image = transform.resize(np_image, (self.input_image_size[0], self.input_image_size[1], 3)) - np_image = np.expand_dims(np_image, axis=0) - return np_image - - def img_prediction(self, img_path): - """Predicts the class of the given image. - - :param img_path: The path to the image. - - :return: The softmax array of predictions and the id of the prediction from class names. - """ - img_path = pathlib.Path(img_path) - img_path = img_path.resolve() # Find absolute path from a relative one. - img_path = str(img_path) - - image = self.__load(img_path) - p = self.imported.predict(image) - - p_id = np.array(p) - p_id = np.squeeze(p) - max = p_id.max() - id = np.where(p_id == max) - - return p, id - - def predict_from_batch_data(self, in_batch_ds): - """Predicts the class of the given batch of images. - - :param in_batch_ds: The batch of images. - - :return: The softmax array of predictions and the id of the prediction from class names. - """ - test_ds = in_batch_ds - - img, label = next(iter(test_ds)) - # print(len(img)) - self.log.info("Predicting on batch of {} images.".format(len(img))) - - ids = [] - for i in img: - i = np.array(i) - i = np.expand_dims(i, axis=0) - p = self.imported.predict(i) - p = np.array(p) - p = np.squeeze(p) - max = p.max() - id = np.where(p == max) - ids.append(id[0]) - return np.array(label), np.squeeze(np.array(ids)) + def __init__(self, config): + """Initializes the predictor and config. + + :param config: A dictionary containing the config.json. + """ + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("MAGIST_Lite_Predictor") + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['tf_lite_detector']: + try: + self.TF_ckpt_path = i["TF_ckpt_path"] + except KeyError: + pass + try: + self.export_path = i["export_full_model"] + except KeyError: + pass + try: + self.input_image_size = i["input_image_size"] + except KeyError: + pass + try: + self.grayscale = i["grayscale"] + except KeyError: + pass + + self.export_path = pathlib.Path(self.export_path) + # Find absolute path from a relative one. + self.export_path = self.export_path.resolve() + self.export_path = str(self.export_path) + + self.TF_ckpt_path = pathlib.Path(self.TF_ckpt_path) + # Find absolute path from a relative one. + self.TF_ckpt_path = self.TF_ckpt_path.resolve() + self.TF_ckpt_path = str(self.TF_ckpt_path) + + self.imported = tf.keras.models.load_model( + self.export_path, compile=False) + self.log.info("Model imported from {}.".format(self.export_path)) + + # latest = tf.train.latest_checkpoint(self.TF_ckpt_path) + + # self.imported.load_weights(latest) + self.imported.summary() + + def __load(self, filename): + """Loads a file from the given filename. + + :param filename: The filename to load. + + :return: The loaded image file as np.array. + """ + np_image = Image.open(filename) + np_image = np.array(np_image).astype('float32') / 255 + if self.grayscale: + np_image = transform.resize( + np_image, (self.input_image_size[0], self.input_image_size[1], 1)) + else: + np_image = transform.resize( + np_image, (self.input_image_size[0], self.input_image_size[1], 3)) + np_image = np.expand_dims(np_image, axis=0) + return np_image + + def img_prediction(self, img_path): + """Predicts the class of the given image. + + :param img_path: The path to the image. + + :return: The softmax array of predictions and the id of the prediction from class names. + """ + img_path = pathlib.Path(img_path) + # Find absolute path from a relative one. + img_path = img_path.resolve() + img_path = str(img_path) + + image = self.__load(img_path) + p = self.imported.predict(image) + + p_id = np.array(p) + p_id = np.squeeze(p) + max = p_id.max() + id = np.where(p_id == max) + + return p, id + + def predict_from_batch_data(self, in_batch_ds): + """Predicts the class of the given batch of images. + + :param in_batch_ds: The batch of images. + + :return: The softmax array of predictions and the id of the prediction from class names. + """ + test_ds = in_batch_ds + + img, label = next(iter(test_ds)) + # print(len(img)) + self.log.info("Predicting on batch of {} images.".format(len(img))) + + ids = [] + for i in img: + i = np.array(i) + i = np.expand_dims(i, axis=0) + p = self.imported.predict(i) + p = np.array(p) + p = np.squeeze(p) + max = p.max() + id = np.where(p == max) + ids.append(id[0]) + return np.array(label), np.squeeze(np.array(ids)) diff --git a/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py b/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py index 863431b..19f06b3 100644 --- a/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py +++ b/src/MAGIST/Vision/UnsupervisedModels/img_cluster.py @@ -9,104 +9,113 @@ from sklearn.cluster import KMeans from skimage.util import img_as_uint, img_as_ubyte from ...Utils.LogMaster.log_init import MainLogger -import pathlib, json +import pathlib +import json class RoughCluster(): - def __init__(self, config): - """Initialize the class, logger module and parse config.json. - - :param config: A relative or absolute path to master config JSON file. - """ - root_log = MainLogger(config) - self.log = root_log.StandardLogger("UnsupervisedClustering") # Create a script specific logging instance - - config = pathlib.Path(config) - config = config.resolve() # Find absolute path from a relative one. - f = open(config) - config = json.load(f) - - for i in config['basic_variables']: - try: - self.matplot = i["enable_matplot_display"] - except: - pass - - def unsupervised_clusters(self, n_of_clusters, img_location, img_size, masked_img_dir): - """Make, color, and crop unsupervised clusters. - - :param n_of_clusters: Number of expected objects. - :param img_location: Location of input image. - :param img_size: Resized shape of the image in pixels. This is represented as a tuple (length, height). Note: - This is NOT the current size of the image(it can be though), but rather the size it will be scaled down to for - efficient processing. - :param masked_img_dir: Location of the exported image directories. - :return: None - """ - - def image_to_pandas(image): - """ - - :param image: Location of input image. - - :return: Array of masked image locations. - """ - df = pd.DataFrame([image[:, :, 0].flatten(), - image[:, :, 1].flatten(), - image[:, :, 2].flatten()]).T - df.columns = ['Red_Channel', 'Green_Channel', 'Blue_Channel'] - return df - - img_location = pathlib.Path(img_location) - img_location = img_location.resolve() # Find the absolute path from relative one. - img_location = str(img_location) - - masked_img_dir = pathlib.Path(masked_img_dir) - masked_img_dir = masked_img_dir.resolve() # Find the absolute path from relative one. - masked_img_dir = str(masked_img_dir) - - img = imread(img_location) - img = resize(img, img_size) - plt.figure(num=None, figsize=(8, 6), dpi=80) - if (self.matplot): - imshow(img) - - self.log.info("Input image resized and configured for clustering computation.") - - df_img = image_to_pandas(img) - - kmeans = KMeans(n_clusters=n_of_clusters, random_state=0).fit(df_img) - self.log.info("Image clustering complete!") - - result = kmeans.labels_.reshape(img.shape[0], img.shape[1]) - if (self.matplot): - imshow(result, cmap='viridis') - plt.show() - - fig, axes = plt.subplots(1, n_of_clusters, figsize=(15, 12)) - - clustered_img = [] - - for n, ax in enumerate(axes.flatten()): - img2 = imread(img_location) - img2 = resize(img2, img_size) - img2[:, :, 0] = img2[:, :, 0] * (result == [n]) # Disabling pixels of certain type - img2[:, :, 1] = img2[:, :, 1] * (result == [n]) # Disabling pixels of certain type - img2[:, :, 2] = img2[:, :, 2] * (result == [n]) # Disabling pixels of certain type - unit_img = img_as_ubyte(img2) - try: - imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) - except FileNotFoundError: - pathlib.Path(masked_img_dir).mkdir(parents=True, exist_ok=True) - imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) - clustered_img.append(f'{masked_img_dir}/masked{n}.jpg') - ax.imshow(img2) - ax.set_axis_off() - fig.tight_layout() - if (self.matplot): - plt.show() - - return clustered_img + def __init__(self, config): + """Initialize the class, logger module and parse config.json. + + :param config: A relative or absolute path to master config JSON file. + """ + root_log = MainLogger(config) + # Create a script specific logging instance + self.log = root_log.StandardLogger("UnsupervisedClustering") + + config = pathlib.Path(config) + config = config.resolve() # Find absolute path from a relative one. + f = open(config) + config = json.load(f) + + for i in config['basic_variables']: + try: + self.matplot = i["enable_matplot_display"] + except BaseException: + pass + + def unsupervised_clusters( + self, n_of_clusters, img_location, img_size, masked_img_dir): + """Make, color, and crop unsupervised clusters. + + :param n_of_clusters: Number of expected objects. + :param img_location: Location of input image. + :param img_size: Resized shape of the image in pixels. This is represented as a tuple (length, height). Note: + This is NOT the current size of the image(it can be though), but rather the size it will be scaled down to for + efficient processing. + :param masked_img_dir: Location of the exported image directories. + :return: None + """ + + def image_to_pandas(image): + """ + + :param image: Location of input image. + + :return: Array of masked image locations. + """ + df = pd.DataFrame([image[:, :, 0].flatten(), + image[:, :, 1].flatten(), + image[:, :, 2].flatten()]).T + df.columns = ['Red_Channel', 'Green_Channel', 'Blue_Channel'] + return df + + img_location = pathlib.Path(img_location) + # Find the absolute path from relative one. + img_location = img_location.resolve() + img_location = str(img_location) + + masked_img_dir = pathlib.Path(masked_img_dir) + # Find the absolute path from relative one. + masked_img_dir = masked_img_dir.resolve() + masked_img_dir = str(masked_img_dir) + + img = imread(img_location) + img = resize(img, img_size) + plt.figure(num=None, figsize=(8, 6), dpi=80) + if (self.matplot): + imshow(img) + + self.log.info( + "Input image resized and configured for clustering computation.") + + df_img = image_to_pandas(img) + + kmeans = KMeans(n_clusters=n_of_clusters, random_state=0).fit(df_img) + self.log.info("Image clustering complete!") + + result = kmeans.labels_.reshape(img.shape[0], img.shape[1]) + if (self.matplot): + imshow(result, cmap='viridis') + plt.show() + + fig, axes = plt.subplots(1, n_of_clusters, figsize=(15, 12)) + + clustered_img = [] + + for n, ax in enumerate(axes.flatten()): + img2 = imread(img_location) + img2 = resize(img2, img_size) + # Disabling pixels of certain type + img2[:, :, 0] = img2[:, :, 0] * (result == [n]) + # Disabling pixels of certain type + img2[:, :, 1] = img2[:, :, 1] * (result == [n]) + # Disabling pixels of certain type + img2[:, :, 2] = img2[:, :, 2] * (result == [n]) + unit_img = img_as_ubyte(img2) + try: + imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) + except FileNotFoundError: + pathlib.Path(masked_img_dir).mkdir(parents=True, exist_ok=True) + imsave(f'{masked_img_dir}/masked{n}.jpg', unit_img) + clustered_img.append(f'{masked_img_dir}/masked{n}.jpg') + ax.imshow(img2) + ax.set_axis_off() + fig.tight_layout() + if (self.matplot): + plt.show() + + return clustered_img # unsupervised_clusters(3, 'test.jpg', (540, 480), "./Masks") # unsupervised_clusters(2, 'masked2.jpg', (540, 480), ".") diff --git a/src/main.py b/src/main.py index 588d309..49d0a85 100644 --- a/src/main.py +++ b/src/main.py @@ -1,119 +1,91 @@ from MAGIST.Vision.UnsupervisedModels.img_cluster import RoughCluster -import numpy as np - -cluster = RoughCluster("config.json") - -imgs = cluster.unsupervised_clusters(3, "2.jpg", (200, 200), "Clusters") - - from MAGIST.Utils.WebScraper.google import GoogleScraper - -scraper = GoogleScraper("config.json") - -labels = [] - -for i in imgs: - label = scraper.reverse_image_search(i) - labels.append(label) - -labels = np.unique(np.array(labels)) - from MAGIST.TaskManagment.ThreadedQueue import MainPriorityQueue - -queue = MainPriorityQueue("config.json") -queue.detach_thread() - -priority = 1 - - -for l in labels: - queue.put_queue(scraper.download_raw_img_dataset, l, 10, "Data/", name=f"Downloading {l}", priority=priority) - priority += 1 - - -from MAGIST.Vision.DetectionDataManager.image_slicer import ImageSlicer - -slicer = ImageSlicer("config.json") - - - -for l in labels: - path = os.path.join("Data", l) - slicer.image_integrity_verification(path, delete_invalid=True) - slicer.resizer((500, 500), path) - coordinates = slicer.coordinate_compute((500, 500), (100, 100)) - slicer.crop_segments(coordinates, path, "Sliced", l) - - - - -from MAGIST.Vision.FullySupervisedModels.MAGIST_Lite_Detector import MAGIST_CNN - -cnn = MAGIST_CNN("config.json") - -queue.put_queue(cnn, name="MAGIST_CNN_Trainer", priority=10) - from MAGIST.Utils.WebScraper.wikipedia import WikipediaScraper from MAGIST.NeuralDB.MongoUtils import AdminUtils - -mongo_admin = AdminUtils("config.json") -client = mongo_admin.initialize_neuraldb() - from MAGIST.NeuralDB.PrimaryNeuralDB import NeuralDB -neural_db = NeuralDB("config.json", client) -neural_db.recreate_db() - -wiki = WikipediaScraper("config.json") - -for l in labels: - description = wiki.get_summary(l) - neural_db.insert_obj_desc(l, description) - -neural_db.remove_duplicates() - -from MAGIST.NLP.AudioTranscriber import GoogleAudioTranscriber - -transcriber = GoogleAudioTranscriber("config.json") - -text = transcriber.microphone_listener() - -from MAGIST.NLP.SelfAttention import TextPreprocessing - -selfattention = TextPreprocessing("config.json") - -selected = [] -for i in selfattention.__call__(text): - if i[2] == "Good": - selected.append(i[1]) - - -search_res = [] -unused_terms = [] -for i in selected: - res = neural_db.search_entire_db(i) - if res != []: - search_res.append(res) - else: - unused_terms.append(i) - -search_res = np.array(search_res) -search_res = np.squeeze(search_res) - -try: - print("=====================================================================================================") - print(search_res) - print("=====================================================================================================") - print(unused_terms) -except IndexError: - print("No results found") - -from MAGIST.NLP.WordScraper import FullDictionarySearch +import numpy as np +import os +from os import walk +from tqdm import tqdm -dict = FullDictionarySearch("config.json") +filenames = next(walk("inputs"), (None, None, []))[2] # [] if no file -for i in unused_terms: - definition = dict.define(i) - neural_db.insert_word_desc(i, definition) +cluster = RoughCluster("config/config.json") +scraper = GoogleScraper("config/config.json") +queue = MainPriorityQueue("config/config.json") +mongo_admin = AdminUtils("config/config.json") +client = mongo_admin.initialize_neuraldb() +neural_db = NeuralDB("config/config.json", client) +wiki = WikipediaScraper("config/config.json") +neural_db.recreate_db() -neural_db.remove_duplicates() \ No newline at end of file +for f in tqdm(filenames): + try: + imgs = cluster.unsupervised_clusters( + 3, f"inputs/{f}", (200, 200), "Clusters") + + labels = [] + + for i in imgs: + label = scraper.reverse_image_search(i) + labels.append(label) + + labels = np.unique(np.array(labels)) + + queue.detach_thread() + + priority = 1 + + # for l in labels: + # scraper.download_raw_img_dataset(l, 10, "Data/") + + # from MAGIST.Vision.DetectionDataManager.image_slicer import ImageSlicer + # + # slicer = ImageSlicer("config/config.json") + # + # counter = 0 + # for l in labels: + # path = os.path.join("Data", l) + # file = os.listdir(path) + # + # for f in file: + # full_path = os.path.join(path, f) + # os.system(f"mv '{full_path}' '{os.path.join(path, f'Frame{str(counter).zfill(2)}.jpg')}'") + # counter += 1 + # + # counter = 0 + # for l in labels: + # path = os.path.join("Data", l) + # os.listdir(path) + # + # + # for l in labels: + # path = os.path.join("Data", l) + # + # slicer.image_integrity_verification(path, delete_invalid=True) + # slicer.resizer((500, 500), path) + # coordinates = slicer.coordinate_compute((500, 500), (100, 100)) + # slicer.crop_segments(coordinates, path, "Sliced", l) + # + # + # + # + # from MAGIST.Vision.FullySupervisedModels.MAGIST_Lite_Detector import MAGIST_CNN + # + # cnn = MAGIST_CNN("config/config.json") + # + # queue.put_queue(cnn, name="MAGIST_CNN_Trainer", priority=10) + + for l in labels: + description = wiki.get_summary(l) + neural_db.insert_obj_desc(l, description) + + neural_db.remove_duplicates() + queue.join_thread() + + except Exception as e: + print("=============================BIG ERROR: SKIP IMAGE=============================") + print(e) + pass diff --git a/src/main_hmi.py b/src/main_hmi.py new file mode 100644 index 0000000..907b2df --- /dev/null +++ b/src/main_hmi.py @@ -0,0 +1,139 @@ +from MAGIST.NLP.WordScraper import FullDictionarySearch +from MAGIST.NLP.SelfAttention import TextPreprocessing +from MAGIST.NLP.AudioTranscriber import GoogleAudioTranscriber +from MAGIST.Vision.UnsupervisedModels.img_cluster import RoughCluster +import numpy as np +import os +from os import walk +from tqdm import tqdm + +filenames = next(walk("inputs"), (None, None, []))[2] # [] if no file + +cluster = RoughCluster("config/config.json") + +for f in tqdm(filenames): + try: + imgs = cluster.unsupervised_clusters( + 3, f"inputs/{f}", (200, 200), "Clusters") + + from MAGIST.Utils.WebScraper.google import GoogleScraper + + scraper = GoogleScraper("config/config.json") + + labels = [] + + for i in imgs: + label = scraper.reverse_image_search(i) + labels.append(label) + + labels = np.unique(np.array(labels)) + + from MAGIST.TaskManagment.ThreadedQueue import MainPriorityQueue + + queue = MainPriorityQueue("config/config.json") + queue.detach_thread() + + priority = 1 + + for l in labels: + scraper.download_raw_img_dataset(l, 10, "Data/") + + from MAGIST.Vision.DetectionDataManager.image_slicer import ImageSlicer + + slicer = ImageSlicer("config/config.json") + + counter = 0 + for l in labels: + path = os.path.join("Data", l) + file = os.listdir(path) + + for f in file: + full_path = os.path.join(path, f) + os.system( + f"mv '{full_path}' '{os.path.join(path, f'Frame{str(counter).zfill(2)}.jpg')}'") + counter += 1 + + counter = 0 + for l in labels: + path = os.path.join("Data", l) + os.listdir(path) + + for l in labels: + path = os.path.join("Data", l) + + slicer.image_integrity_verification(path, delete_invalid=True) + slicer.resizer((500, 500), path) + coordinates = slicer.coordinate_compute((500, 500), (100, 100)) + slicer.crop_segments(coordinates, path, "Sliced", l) + + from MAGIST.Vision.FullySupervisedModels.MAGIST_Lite_Detector import MAGIST_CNN + + cnn = MAGIST_CNN("config/config.json") + + queue.put_queue(cnn, name="MAGIST_CNN_Trainer", priority=10) + + from MAGIST.Utils.WebScraper.wikipedia import WikipediaScraper + from MAGIST.NeuralDB.MongoUtils import AdminUtils + + mongo_admin = AdminUtils("config/config.json") + client = mongo_admin.initialize_neuraldb() + + from MAGIST.NeuralDB.PrimaryNeuralDB import NeuralDB + + neural_db = NeuralDB("config/config.json", client) + neural_db.recreate_db() + + wiki = WikipediaScraper("config/config.json") + + for l in labels: + description = wiki.get_summary(l) + neural_db.insert_obj_desc(l, description) + + neural_db.remove_duplicates() + queue.join_thread() + except BaseException: + print("=============================BIG ERROR: SKIP IMAGE=============================") + pass + + +transcriber = GoogleAudioTranscriber("config/config.json") + +text = transcriber.microphone_listener() + + +selfattention = TextPreprocessing("config/config.json") + +selected = [] +for i in selfattention.__call__(text): + if i[2] == "Good": + selected.append(i[1]) + + +search_res = [] +unused_terms = [] +for i in selected: + res = neural_db.search_entire_db(i) + if res != []: + search_res.append(res) + else: + unused_terms.append(i) + +search_res = np.array(search_res) +search_res = np.squeeze(search_res) + +try: + print("=====================================================================================================") + print(search_res) + print("=====================================================================================================") + print(unused_terms) +except IndexError: + print("No results found") + + +dict = FullDictionarySearch("config/config.json") + +for i in unused_terms: + definition = dict.define(i) + neural_db.insert_word_desc(i, definition) + +neural_db.remove_duplicates() diff --git a/src/test.py b/src/test.py index c772e4a..6cb78e8 100644 --- a/src/test.py +++ b/src/test.py @@ -1,14 +1,23 @@ -from MAGIST.NeuralDB.MongoUtils import AdminUtils -from MAGIST.NeuralDB.PrimaryNeuralDB import NeuralDB +# from MAGIST.NeuralDB.ElasticSearch import ESDB +# +# esdb = ESDB("config/config.json", "http://192.168.31.188:9200", "config/queries.json", "config/schema.json") +# +# +# esdb.create_index("test_index22", "word_db_schema") -a = AdminUtils("config.json") -client = a.initialize_neuraldb() +# +# import cv2 +# vidcap = cv2.VideoCapture('vid.mp4') +# success,image = vidcap.read() +# count = 0 +# while success: +# cv2.imwrite("inputs/frame%d.jpg" % count, image) # save frame as JPEG file +# success,image = vidcap.read() +# print('Read a new frame: ', success) +# count += 1 -neural_db = NeuralDB("config.json", client) -neural_db.recreate_db() -a = neural_db.search_entire_db("blah") +from os import walk -print(a) - -//testing123 +filenames = next(walk("inputs"), (None, None, []))[2] # [] if no file +print(filenames) \ No newline at end of file