From 8f1a56630936a74550704ed5c2478f6dc4a99e0d Mon Sep 17 00:00:00 2001 From: =?utf8?q?Alexandre=20Delano=C3=AB?= Date: Wed, 2 Aug 2017 11:33:24 +0200 Subject: [PATCH 1/1] First commit to start with. --- LICENSE | 1236 +++++++++++++++++ app/Main.hs | 6 + gargantext.cabal | 99 ++ src/Data/Gargantext.hs | 9 + src/Data/Gargantext/Analysis.hs | 23 + src/Data/Gargantext/DSL.hs | 54 + src/Data/Gargantext/Database.hs | 29 + src/Data/Gargantext/Database/Instances.hs | 27 + src/Data/Gargantext/Database/Ngram.hs | 82 ++ src/Data/Gargantext/Database/Node.hs | 140 ++ src/Data/Gargantext/Database/NodeNgram.hs | 64 + .../Gargantext/Database/NodeNgramNgram.hs | 66 + src/Data/Gargantext/Database/NodeNode.hs | 63 + src/Data/Gargantext/Database/NodeNodeNgram.hs | 66 + src/Data/Gargantext/Database/Private.hs | 15 + src/Data/Gargantext/Database/User.hs | 130 ++ src/Data/Gargantext/Ngrams.hs | 11 + src/Data/Gargantext/Ngrams/Count.hs | 47 + src/Data/Gargantext/Ngrams/Hetero.hs | 75 + src/Data/Gargantext/Ngrams/TextMining.hs | 56 + src/Data/Gargantext/Ngrams/Utils.hs | 32 + src/Data/Gargantext/Ngrams/Words.hs | 60 + src/Data/Gargantext/Parsers.hs | 3 + src/Data/Gargantext/Parsers/Occurrences.hs | 28 + src/Data/Gargantext/Prelude.hs | 170 +++ src/Data/Gargantext/Server.hs | 93 ++ src/Data/Gargantext/Types.hs | 6 + src/Data/Gargantext/Types/Main.hs | 132 ++ src/Data/Gargantext/Types/Node.hs | 117 ++ src/Data/Gargantext/Utils.hs | 6 + src/Data/Gargantext/Utils/Chronos.hs | 94 ++ src/Data/Gargantext/Utils/Count.hs | 72 + src/Data/Gargantext/Utils/DateUtils.hs | 32 + src/Data/Gargantext/Utils/LangDetect.hs | 93 ++ src/Data/Gargantext/Utils/Prefix.hs | 48 + src/Data/Gargantext/Utils/SaveGetHash.hs | 91 ++ stack.yaml | 10 + test/Parsers.hs | 54 + test/Spec.hs | 47 + 39 files changed, 3486 insertions(+) create mode 100644 LICENSE create mode 100644 app/Main.hs create mode 100644 gargantext.cabal create mode 100644 src/Data/Gargantext.hs create mode 100644 src/Data/Gargantext/Analysis.hs create mode 100644 src/Data/Gargantext/DSL.hs create mode 100644 src/Data/Gargantext/Database.hs create mode 100644 src/Data/Gargantext/Database/Instances.hs create mode 100644 src/Data/Gargantext/Database/Ngram.hs create mode 100644 src/Data/Gargantext/Database/Node.hs create mode 100644 src/Data/Gargantext/Database/NodeNgram.hs create mode 100644 src/Data/Gargantext/Database/NodeNgramNgram.hs create mode 100644 src/Data/Gargantext/Database/NodeNode.hs create mode 100644 src/Data/Gargantext/Database/NodeNodeNgram.hs create mode 100644 src/Data/Gargantext/Database/Private.hs create mode 100644 src/Data/Gargantext/Database/User.hs create mode 100644 src/Data/Gargantext/Ngrams.hs create mode 100644 src/Data/Gargantext/Ngrams/Count.hs create mode 100644 src/Data/Gargantext/Ngrams/Hetero.hs create mode 100644 src/Data/Gargantext/Ngrams/TextMining.hs create mode 100644 src/Data/Gargantext/Ngrams/Utils.hs create mode 100644 src/Data/Gargantext/Ngrams/Words.hs create mode 100644 src/Data/Gargantext/Parsers.hs create mode 100644 src/Data/Gargantext/Parsers/Occurrences.hs create mode 100644 src/Data/Gargantext/Prelude.hs create mode 100644 src/Data/Gargantext/Server.hs create mode 100644 src/Data/Gargantext/Types.hs create mode 100644 src/Data/Gargantext/Types/Main.hs create mode 100644 src/Data/Gargantext/Types/Node.hs create mode 100644 src/Data/Gargantext/Utils.hs create mode 100644 src/Data/Gargantext/Utils/Chronos.hs create mode 100644 src/Data/Gargantext/Utils/Count.hs create mode 100644 src/Data/Gargantext/Utils/DateUtils.hs create mode 100644 src/Data/Gargantext/Utils/LangDetect.hs create mode 100644 src/Data/Gargantext/Utils/Prefix.hs create mode 100644 src/Data/Gargantext/Utils/SaveGetHash.hs create mode 100644 stack.yaml create mode 100644 test/Parsers.hs create mode 100644 test/Spec.hs diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..8de7d803 --- /dev/null +++ b/LICENSE @@ -0,0 +1,1236 @@ +Gargantext Software Copyright (c) 2016-2017 CNRS ISC-PIF - http://iscpif.fr + Licences: + - GNU aGPLV3 + - a CECILL variant affero compliant + + +======================================================================== + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + +======================================================================== + + CONTRAT DE LICENCE DE LOGICIEL LIBRE HYBRIDE CECILL/AFFERO + +Ce contrat est une licence de logiciel libre qui reprend intégralement +le texte de la licence CECILL tel que publié dans sa Version 2.1 +du 2013-06-21, en y ajoutant, en 5.3.5 une disposition extraite de +la licence Affero-GPL version 3, relative à l’accès distant au +logiciel. + + + Avertissement + +Ce contrat est une licence de logiciel libre issue d'une concertation +entre ses auteurs afin que le respect de deux grands principes préside à +sa rédaction: + + * d'une part, le respect des principes de diffusion des logiciels + libres: accès au code source, droits étendus conférés aux utilisateurs, + * d'autre part, la désignation d'un droit applicable, le droit + français, auquel elle est conforme, tant au regard du droit de la + responsabilité civile que du droit de la propriété intellectuelle et + de la protection qu'il offre aux auteurs et titulaires des droits + patrimoniaux sur un logiciel. + +Les auteurs de la licence CeCILL (Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) +sont: + +Commissariat à l'énergie atomique et aux énergies alternatives - CEA, +établissement public de recherche à caractère scientifique, technique et +industriel, dont le siège est situé 25 rue Leblanc, immeuble Le Ponant +D, 75015 Paris. + +Centre National de la Recherche Scientifique - CNRS, établissement +public à caractère scientifique et technologique, dont le siège est +situé 3 rue Michel-Ange, 75794 Paris cedex 16. + +Institut National de Recherche en Informatique et en Automatique - +Inria, établissement public à caractère scientifique et technologique, +dont le siège est situé Domaine de Voluceau, Rocquencourt, BP 105, 78153 +Le Chesnay cedex. + + + Préambule + +Ce contrat est une licence de logiciel libre dont l'objectif est de +conférer aux utilisateurs la liberté de modification et de +redistribution du logiciel régi par cette licence dans le cadre d'un +modèle de diffusion en logiciel libre. + +L'exercice de ces libertés est assorti de certains devoirs à la charge +des utilisateurs afin de préserver ce statut au cours des +redistributions ultérieures. + +L'accessibilité au code source et les droits de copie, de modification +et de redistribution qui en découlent ont pour contrepartie de n'offrir +aux utilisateurs qu'une garantie limitée et de ne faire peser sur +l'auteur du logiciel, le titulaire des droits patrimoniaux et les +concédants successifs qu'une responsabilité restreinte. + +A cet égard l'attention de l'utilisateur est attirée sur les risques +associés au chargement, à l'utilisation, à la modification et/ou au +développement et à la reproduction du logiciel par l'utilisateur étant +donné sa spécificité de logiciel libre, qui peut le rendre complexe à +manipuler et qui le réserve donc à des développeurs ou des +professionnels avertis possédant des connaissances informatiques +approfondies. Les utilisateurs sont donc invités à charger et tester +l'adéquation du logiciel à leurs besoins dans des conditions permettant +d'assurer la sécurité de leurs systèmes et/ou de leurs données et, plus +généralement, à l'utiliser et l'exploiter dans les mêmes conditions de +sécurité. Ce contrat peut être reproduit et diffusé librement, sous +réserve de le conserver en l'état, sans ajout ni suppression de clauses. + +Ce contrat est susceptible de s'appliquer à tout logiciel dont le +titulaire des droits patrimoniaux décide de soumettre l'exploitation aux +dispositions qu'il contient. + +Une liste de questions fréquemment posées se trouve sur le site web +officiel de la famille des licences CeCILL +(http://www.cecill.info/index.fr.html) pour toute clarification qui +serait nécessaire. + + + Article 1 - DEFINITIONS + +Dans ce contrat, les termes suivants, lorsqu'ils seront écrits avec une +lettre capitale, auront la signification suivante: + +Contrat: désigne le présent contrat de licence, ses éventuelles versions +postérieures et annexes. + +Logiciel: désigne le logiciel sous sa forme de Code Objet et/ou de Code +Source et le cas échéant sa documentation, dans leur état au moment de +l'acceptation du Contrat par le Licencié. + +Logiciel Initial: désigne le Logiciel sous sa forme de Code Source et +éventuellement de Code Objet et le cas échéant sa documentation, dans +leur état au moment de leur première diffusion sous les termes du Contrat. + +Logiciel Modifié: désigne le Logiciel modifié par au moins une +Contribution. + +Code Source: désigne l'ensemble des instructions et des lignes de +programme du Logiciel et auquel l'accès est nécessaire en vue de +modifier le Logiciel. + +Code Objet: désigne les fichiers binaires issus de la compilation du +Code Source. + +Titulaire: désigne le ou les détenteurs des droits patrimoniaux d'auteur +sur le Logiciel Initial. + +Licencié: désigne le ou les utilisateurs du Logiciel ayant accepté le +Contrat. + +Contributeur: désigne le Licencié auteur d'au moins une Contribution. + +Concédant: désigne le Titulaire ou toute personne physique ou morale +distribuant le Logiciel sous le Contrat. + +Contribution: désigne l'ensemble des modifications, corrections, +traductions, adaptations et/ou nouvelles fonctionnalités intégrées dans +le Logiciel par tout Contributeur, ainsi que tout Module Interne. + +Module: désigne un ensemble de fichiers sources y compris leur +documentation qui permet de réaliser des fonctionnalités ou services +supplémentaires à ceux fournis par le Logiciel. + +Module Externe: désigne tout Module, non dérivé du Logiciel, tel que ce +Module et le Logiciel s'exécutent dans des espaces d'adressage +différents, l'un appelant l'autre au moment de leur exécution. + +Module Interne: désigne tout Module lié au Logiciel de telle sorte +qu'ils s'exécutent dans le même espace d'adressage. + +GNU GPL: désigne la GNU General Public License dans sa version 2 ou +toute version ultérieure, telle que publiée par Free Software Foundation +Inc. + +GNU Affero GPL: désigne la GNU Affero General Public License dans sa +version 3 ou toute version ultérieure, telle que publiée par Free +Software Foundation Inc. + +EUPL: désigne la Licence Publique de l'Union européenne dans sa version +1.1 ou toute version ultérieure, telle que publiée par la Commission +Européenne. + +Parties: désigne collectivement le Licencié et le Concédant. + +Ces termes s'entendent au singulier comme au pluriel. + + + Article 2 - OBJET + +Le Contrat a pour objet la concession par le Concédant au Licencié d'une +licence non exclusive, cessible et mondiale du Logiciel telle que +définie ci-après à l'article 5 <#etendue> pour toute la durée de +protection des droits portant sur ce Logiciel. + + + Article 3 - ACCEPTATION + +3.1 L'acceptation par le Licencié des termes du Contrat est réputée +acquise du fait du premier des faits suivants: + + * (i) le chargement du Logiciel par tout moyen notamment par + téléchargement à partir d'un serveur distant ou par chargement à + partir d'un support physique; + * (ii) le premier exercice par le Licencié de l'un quelconque des + droits concédés par le Contrat. + +3.2 Un exemplaire du Contrat, contenant notamment un avertissement +relatif aux spécificités du Logiciel, à la restriction de garantie et à +la limitation à un usage par des utilisateurs expérimentés a été mis à +disposition du Licencié préalablement à son acceptation telle que +définie à l'article 3.1 <#acceptation-acquise> ci dessus et le Licencié +reconnaît en avoir pris connaissance. + + + Article 4 - ENTREE EN VIGUEUR ET DUREE + + + 4.1 ENTREE EN VIGUEUR + +Le Contrat entre en vigueur à la date de son acceptation par le Licencié +telle que définie en 3.1 <#acceptation-acquise>. + + + 4.2 DUREE + +Le Contrat produira ses effets pendant toute la durée légale de +protection des droits patrimoniaux portant sur le Logiciel. + + + Article 5 - ETENDUE DES DROITS CONCEDES + +Le Concédant concède au Licencié, qui accepte, les droits suivants sur +le Logiciel pour toutes destinations et pour la durée du Contrat dans +les conditions ci-après détaillées. + +Par ailleurs, si le Concédant détient ou venait à détenir un ou +plusieurs brevets d'invention protégeant tout ou partie des +fonctionnalités du Logiciel ou de ses composants, il s'engage à ne pas +opposer les éventuels droits conférés par ces brevets aux Licenciés +successifs qui utiliseraient, exploiteraient ou modifieraient le +Logiciel. En cas de cession de ces brevets, le Concédant s'engage à +faire reprendre les obligations du présent alinéa aux cessionnaires. + + + 5.1 DROIT D'UTILISATION + +Le Licencié est autorisé à utiliser le Logiciel, sans restriction quant +aux domaines d'application, étant ci-après précisé que cela comporte: + + 1. + + la reproduction permanente ou provisoire du Logiciel en tout ou + partie par tout moyen et sous toute forme. + + 2. + + le chargement, l'affichage, l'exécution, ou le stockage du Logiciel + sur tout support. + + 3. + + la possibilité d'en observer, d'en étudier, ou d'en tester le + fonctionnement afin de déterminer les idées et principes qui sont à + la base de n'importe quel élément de ce Logiciel; et ceci, lorsque + le Licencié effectue toute opération de chargement, d'affichage, + d'exécution, de transmission ou de stockage du Logiciel qu'il est en + droit d'effectuer en vertu du Contrat. + + + 5.2 DROIT D'APPORTER DES CONTRIBUTIONS + +Le droit d'apporter des Contributions comporte le droit de traduire, +d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel +et le droit de reproduire le logiciel en résultant. + +Le Licencié est autorisé à apporter toute Contribution au Logiciel sous +réserve de mentionner, de façon explicite, son nom en tant qu'auteur de +cette Contribution et la date de création de celle-ci. + + + 5.3 DROIT DE DISTRIBUTION + +Le droit de distribution comporte notamment le droit de diffuser, de +transmettre et de communiquer le Logiciel au public sur tout support et +par tout moyen ainsi que le droit de mettre sur le marché à titre +onéreux ou gratuit, un ou des exemplaires du Logiciel par tout procédé. + +Le Licencié est autorisé à distribuer des copies du Logiciel, modifié ou +non, à des tiers dans les conditions ci-après détaillées. + + + 5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION + +Le Licencié est autorisé à distribuer des copies conformes du Logiciel, +sous forme de Code Source ou de Code Objet, à condition que cette +distribution respecte les dispositions du Contrat dans leur totalité et +soit accompagnée: + + 1. + + d'un exemplaire du Contrat, + + 2. + + d'un avertissement relatif à la restriction de garantie et de + responsabilité du Concédant telle que prévue aux articles 8 + <#responsabilite> et 9 <#garantie>, + +et que, dans le cas où seul le Code Objet du Logiciel est redistribué, +le Licencié permette un accès effectif au Code Source complet du +Logiciel pour une durée d'au moins 3 ans à compter de la distribution du +logiciel, étant entendu que le coût additionnel d'acquisition du Code +Source ne devra pas excéder le simple coût de transfert des données. + + + 5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE + +Lorsque le Licencié apporte une Contribution au Logiciel, les conditions +de distribution du Logiciel Modifié en résultant sont alors soumises à +l'intégralité des dispositions du Contrat. + +Le Licencié est autorisé à distribuer le Logiciel Modifié, sous forme de +code source ou de code objet, à condition que cette distribution +respecte les dispositions du Contrat dans leur totalité et soit +accompagnée: + + 1. + + d'un exemplaire du Contrat, + + 2. + + d'un avertissement relatif à la restriction de garantie et de + responsabilité du Concédant telle que prévue aux articles 8 + <#responsabilite> et 9 <#garantie>, + +et, dans le cas où seul le code objet du Logiciel Modifié est redistribué, + + 3. + + d'une note précisant les conditions d'accès effectif au code source + complet du Logiciel Modifié, pendant une période d'au moins 3 ans à + compter de la distribution du Logiciel Modifié, étant entendu que le + coût additionnel d'acquisition du code source ne devra pas excéder + le simple coût de transfert des données. + + + 5.3.3 DISTRIBUTION DES MODULES EXTERNES + +Lorsque le Licencié a développé un Module Externe les conditions du +Contrat ne s'appliquent pas à ce Module Externe, qui peut être distribué +sous un contrat de licence différent. + + + 5.3.4 COMPATIBILITE AVEC D'AUTRES LICENCES + +Le Licencié peut inclure un code soumis aux dispositions d'une des +versions de la licence GNU GPL, GNU Affero GPL et/ou EUPL dans le +Logiciel modifié ou non et distribuer l'ensemble sous les conditions de +la même version de la licence GNU GPL, GNU Affero GPL et/ou EUPL. + +Le Licencié peut inclure le Logiciel modifié ou non dans un code soumis +aux dispositions d'une des versions de la licence GNU GPL, GNU Affero +GPL et/ou EUPL et distribuer l'ensemble sous les conditions de la même +version de la licence GNU GPL, GNU Affero GPL et/ou EUPL. + + 5.3.5 ACCES DISTANT à UN LOGICIEL MODIFIE + +Si le Licencié apporte des contributions au Logiciel et exécute le +Logiciel Modifié sur un serveur en laissant d’autres utilisateurs +communiquer avec lui à distance via un réseau informatique, le +Licencié doit donner à ces utilisateurs de manière explicite et +sans coût additionnel, un accès au code source complet du Logiciel +Modifié, dans les conditions mentionnées à l’article 5.3.2. Cette +disposition est ajoutée à la licence CECILL originelle, et prévaut +sur les autres dispositions de cette licence en cas de conflit. + + Article 6 - PROPRIETE INTELLECTUELLE + + + 6.1 SUR LE LOGICIEL INITIAL + +Le Titulaire est détenteur des droits patrimoniaux sur le Logiciel +Initial. Toute utilisation du Logiciel Initial est soumise au respect +des conditions dans lesquelles le Titulaire a choisi de diffuser son +oeuvre et nul autre n'a la faculté de modifier les conditions de +diffusion de ce Logiciel Initial. + +Le Titulaire s'engage à ce que le Logiciel Initial reste au moins régi +par le Contrat et ce, pour la durée visée à l'article 4.2 <#duree>. + + + 6.2 SUR LES CONTRIBUTIONS + +Le Licencié qui a développé une Contribution est titulaire sur celle-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable. + + + 6.3 SUR LES MODULES EXTERNES + +Le Licencié qui a développé un Module Externe est titulaire sur celui-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable et reste libre du choix du contrat régissant +sa diffusion. + + + 6.4 DISPOSITIONS COMMUNES + +Le Licencié s'engage expressément: + + 1. + + à ne pas supprimer ou modifier de quelque manière que ce soit les + mentions de propriété intellectuelle apposées sur le Logiciel; + + 2. + + à reproduire à l'identique lesdites mentions de propriété + intellectuelle sur les copies du Logiciel modifié ou non. + +Le Licencié s'engage à ne pas porter atteinte, directement ou +indirectement, aux droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs sur le Logiciel et à prendre, le cas échéant, à +l'égard de son personnel toutes les mesures nécessaires pour assurer le +respect des dits droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs. + + + Article 7 - SERVICES ASSOCIES + +7.1 Le Contrat n'oblige en aucun cas le Concédant à la réalisation de +prestations d'assistance technique ou de maintenance du Logiciel. + +Cependant le Concédant reste libre de proposer ce type de services. Les +termes et conditions d'une telle assistance technique et/ou d'une telle +maintenance seront alors déterminés dans un acte séparé. Ces actes de +maintenance et/ou assistance technique n'engageront que la seule +responsabilité du Concédant qui les propose. + +7.2 De même, tout Concédant est libre de proposer, sous sa seule +responsabilité, à ses licenciés une garantie, qui n'engagera que lui, +lors de la redistribution du Logiciel et/ou du Logiciel Modifié et ce, +dans les conditions qu'il souhaite. Cette garantie et les modalités +financières de son application feront l'objet d'un acte séparé entre le +Concédant et le Licencié. + + + Article 8 - RESPONSABILITE + +8.1 Sous réserve des dispositions de l'article 8.2 +<#limite-responsabilite>, le Licencié a la faculté, sous réserve de +prouver la faute du Concédant concerné, de solliciter la réparation du +préjudice direct qu'il subirait du fait du Logiciel et dont il apportera +la preuve. + +8.2 La responsabilité du Concédant est limitée aux engagements pris en +application du Contrat et ne saurait être engagée en raison notamment: +(i) des dommages dus à l'inexécution, totale ou partielle, de ses +obligations par le Licencié, (ii) des dommages directs ou indirects +découlant de l'utilisation ou des performances du Logiciel subis par le +Licencié et (iii) plus généralement d'un quelconque dommage indirect. En +particulier, les Parties conviennent expressément que tout préjudice +financier ou commercial (par exemple perte de données, perte de +bénéfices, perte d'exploitation, perte de clientèle ou de commandes, +manque à gagner, trouble commercial quelconque) ou toute action dirigée +contre le Licencié par un tiers, constitue un dommage indirect et +n'ouvre pas droit à réparation par le Concédant. + + + Article 9 - GARANTIE + +9.1 Le Licencié reconnaît que l'état actuel des connaissances +scientifiques et techniques au moment de la mise en circulation du +Logiciel ne permet pas d'en tester et d'en vérifier toutes les +utilisations ni de détecter l'existence d'éventuels défauts. L'attention +du Licencié a été attirée sur ce point sur les risques associés au +chargement, à l'utilisation, la modification et/ou au développement et à +la reproduction du Logiciel qui sont réservés à des utilisateurs avertis. + +Il relève de la responsabilité du Licencié de contrôler, par tous +moyens, l'adéquation du produit à ses besoins, son bon fonctionnement et +de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens. + +9.2 Le Concédant déclare de bonne foi être en droit de concéder +l'ensemble des droits attachés au Logiciel (comprenant notamment les +droits visés à l'article 5 <#etendue>). + +9.3 Le Licencié reconnaît que le Logiciel est fourni "en l'état" par le +Concédant sans autre garantie, expresse ou tacite, que celle prévue à +l'article 9.2 <#bonne-foi> et notamment sans aucune garantie sur sa +valeur commerciale, son caractère sécurisé, innovant ou pertinent. + +En particulier, le Concédant ne garantit pas que le Logiciel est exempt +d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible +avec l'équipement du Licencié et sa configuration logicielle ni qu'il +remplira les besoins du Licencié. + +9.4 Le Concédant ne garantit pas, de manière expresse ou tacite, que le +Logiciel ne porte pas atteinte à un quelconque droit de propriété +intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout +autre droit de propriété. Ainsi, le Concédant exclut toute garantie au +profit du Licencié contre les actions en contrefaçon qui pourraient être +diligentées au titre de l'utilisation, de la modification, et de la +redistribution du Logiciel. Néanmoins, si de telles actions sont +exercées contre le Licencié, le Concédant lui apportera son expertise +technique et juridique pour sa défense. Cette expertise technique et +juridique est déterminée au cas par cas entre le Concédant concerné et +le Licencié dans le cadre d'un protocole d'accord. Le Concédant dégage +toute responsabilité quant à l'utilisation de la dénomination du +Logiciel par le Licencié. Aucune garantie n'est apportée quant à +l'existence de droits antérieurs sur le nom du Logiciel et sur +l'existence d'une marque. + + + Article 10 - RESILIATION + +10.1 En cas de manquement par le Licencié aux obligations mises à sa +charge par le Contrat, le Concédant pourra résilier de plein droit le +Contrat trente (30) jours après notification adressée au Licencié et +restée sans effet. + +10.2 Le Licencié dont le Contrat est résilié n'est plus autorisé à +utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les +licences qu'il aura concédées antérieurement à la résiliation du Contrat +resteront valides sous réserve qu'elles aient été effectuées en +conformité avec le Contrat. + + + Article 11 - DISPOSITIONS DIVERSES + + + 11.1 CAUSE EXTERIEURE + +Aucune des Parties ne sera responsable d'un retard ou d'une défaillance +d'exécution du Contrat qui serait dû à un cas de force majeure, un cas +fortuit ou une cause extérieure, telle que, notamment, le mauvais +fonctionnement ou les interruptions du réseau électrique ou de +télécommunication, la paralysie du réseau liée à une attaque +informatique, l'intervention des autorités gouvernementales, les +catastrophes naturelles, les dégâts des eaux, les tremblements de terre, +le feu, les explosions, les grèves et les conflits sociaux, l'état de +guerre... + +11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou +plusieurs occasions de se prévaloir d'une ou plusieurs dispositions du +Contrat, ne pourra en aucun cas impliquer renonciation par la Partie +intéressée à s'en prévaloir ultérieurement. + +11.3 Le Contrat annule et remplace toute convention antérieure, écrite +ou orale, entre les Parties sur le même objet et constitue l'accord +entier entre les Parties sur cet objet. Aucune addition ou modification +aux termes du Contrat n'aura d'effet à l'égard des Parties à moins +d'être faite par écrit et signée par leurs représentants dûment habilités. + +11.4 Dans l'hypothèse où une ou plusieurs des dispositions du Contrat +s'avèrerait contraire à une loi ou à un texte applicable, existants ou +futurs, cette loi ou ce texte prévaudrait, et les Parties feraient les +amendements nécessaires pour se conformer à cette loi ou à ce texte. +Toutes les autres dispositions resteront en vigueur. De même, la +nullité, pour quelque raison que ce soit, d'une des dispositions du +Contrat ne saurait entraîner la nullité de l'ensemble du Contrat. + + + 11.5 LANGUE + +Le Contrat est rédigé en langue française et en langue anglaise, ces +deux versions faisant également foi. + + + Article 12 - NOUVELLES VERSIONS DU CONTRAT + +12.1 Toute personne est autorisée à copier et distribuer des copies de +ce Contrat. + +12.2 Afin d'en préserver la cohérence, le texte du Contrat est protégé +et ne peut être modifié que par les auteurs de la licence, lesquels se +réservent le droit de publier périodiquement des mises à jour ou de +nouvelles versions du Contrat, qui posséderont chacune un numéro +distinct. Ces versions ultérieures seront susceptibles de prendre en +compte de nouvelles problématiques rencontrées par les logiciels libres. + +12.3 Tout Logiciel diffusé sous une version donnée du Contrat ne pourra +faire l'objet d'une diffusion ultérieure que sous la même version du +Contrat ou une version postérieure, sous réserve des dispositions de +l'article 5.3.4 <#compatibilite>. + + + Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE + +13.1 Le Contrat est régi par la loi française. Les Parties conviennent +de tenter de régler à l'amiable les différends ou litiges qui +viendraient à se produire par suite ou à l'occasion du Contrat. + +13.2 A défaut d'accord amiable dans un délai de deux (2) mois à compter +de leur survenance et sauf situation relevant d'une procédure d'urgence, +les différends ou litiges seront portés par la Partie la plus diligente +devant les Tribunaux compétents de Paris. + + + diff --git a/app/Main.hs b/app/Main.hs new file mode 100644 index 00000000..144dec8f --- /dev/null +++ b/app/Main.hs @@ -0,0 +1,6 @@ +module Main where + +import Hastext.Db + +main :: IO () +main = fonction diff --git a/gargantext.cabal b/gargantext.cabal new file mode 100644 index 00000000..b2f550e2 --- /dev/null +++ b/gargantext.cabal @@ -0,0 +1,99 @@ +name: gargantext +version: 0.1.0.0 +synopsis: Deep (Collaborative) Text mining project +description: Please see README.md +homepage: http://gargantext.org +license: BSD3 +license-file: LICENSE +author: Alexandre Delanoë +maintainer: gargantext@iscpif.fr +copyright: Copyright: (c) 2016,2017 CNRS Alexandre Delanoë +category: Data +build-type: Simple +-- extra-source-files: +cabal-version: >=1.10 + +library + hs-source-dirs: src + build-depends: base >= 4.7 && < 5 + , aeson + , attoparsec + , base16-bytestring + , bytestring + , case-insensitive + , containers + , contravariant + , directory + , extra + , filepath + , http-client + , lens + , opaleye + , postgresql-simple + , pretty + , product-profunctors + , profunctors + , protolude + , pureMD5 + , regex-compat + , semigroups + , servant-multipart + , servant-server + , split + -- , stemmer + , tagsoup + , text + , time + , time-locale-compat + , transformers + --, utc + , uuid + , vector + , wai + , warp + , zlib + exposed-modules: Data.Gargantext + , Data.Gargantext.Analysis + , Data.Gargantext.DSL + , Data.Gargantext.Database + , Data.Gargantext.Database.Instances + , Data.Gargantext.Database.Ngram + , Data.Gargantext.Database.Node + , Data.Gargantext.Database.NodeNgram + , Data.Gargantext.Database.NodeNgramNgram + , Data.Gargantext.Database.NodeNode + , Data.Gargantext.Database.NodeNodeNgram + , Data.Gargantext.Database.Private + , Data.Gargantext.Database.User + , Data.Gargantext.Parsers + , Data.Gargantext.Parsers.Occurrences + , Data.Gargantext.Prelude + , Data.Gargantext.Server + , Data.Gargantext.Types + , Data.Gargantext.Types.Node + , Data.Gargantext.Types.Main + , Data.Gargantext.Utils.DateUtils + , Data.Gargantext.Utils.Prefix + default-language: Haskell2010 + ghc-options: -Wall + +--executable gargantext-exe +-- hs-source-dirs: app +-- main-is: Main.hs +-- ghc-options: -threaded -rtsopts -with-rtsopts=-N +-- build-depends: base +-- , hastext +-- default-language: Haskell2010 + +test-suite garg-test-parsers + type: exitcode-stdio-1.0 + hs-source-dirs: test + main-is: Parsers.hs + build-depends: base + , extra + , text + , gargantext + , hspec + , QuickCheck + ghc-options: -threaded -rtsopts -with-rtsopts=-N + default-language: Haskell2010 diff --git a/src/Data/Gargantext.hs b/src/Data/Gargantext.hs new file mode 100644 index 00000000..60f47643 --- /dev/null +++ b/src/Data/Gargantext.hs @@ -0,0 +1,9 @@ +module Data.Gargantext ( + module Data.Gargantext.Database, +-- module Data.Gargantext.Ngrams, +-- module Data.Gargantext.Utils, + ) where + +import Data.Gargantext.Database +-- import Data.Gargantext.Ngrams +-- import Data.Gargantext.Utils diff --git a/src/Data/Gargantext/Analysis.hs b/src/Data/Gargantext/Analysis.hs new file mode 100644 index 00000000..a095e568 --- /dev/null +++ b/src/Data/Gargantext/Analysis.hs @@ -0,0 +1,23 @@ +module Data.Gargantext.Analysis where + +-- import qualified Data.Text.Lazy as DTL +import Data.Either.Extra (fromRight) +import Data.Gargantext.Database.Node +import Data.Gargantext.Parsers.Occurrences +import Data.Gargantext.Prelude +import Data.Gargantext.Types +import Data.Text +import Opaleye (Column, PGInt4) + +-- | Simple function to count Occurrences in a context of text. +occOfDocument :: Column PGInt4 -> Text -> IO Int +occOfDocument = undefined +--occOfDocument c_id txt = do +-- docs <- pm (hyperdataDocument_Abstract . node_hyperdata) <$> getCorpusDocument c_id +-- let occs = pm (\x -> maybe "" identity x) docs +-- let result = case sequence $ pm (parseOccurrences txt) occs of +-- -- TODO find a way to get nice message d'errors (file, function, line) +-- Left str -> error $ "[ERRROR] at file/function/line" ++ str +-- Right xs -> xs +-- pure (sum result) + diff --git a/src/Data/Gargantext/DSL.hs b/src/Data/Gargantext/DSL.hs new file mode 100644 index 00000000..c10e33ff --- /dev/null +++ b/src/Data/Gargantext/DSL.hs @@ -0,0 +1,54 @@ +module Data.Gargantext.DSL where + +import Data.Gargantext.Database +import Data.Gargantext.Prelude +import Data.Gargantext.Types +import Data.Text + +type Username = Text +type Password = Text + + +--user :: Username -> Maybe User +--user username = undefined +-- +-- +--getNode :: Int -> IO Node +--getNode = undefined +-- +--saveNode :: Node -> IO () +--saveNode = undefined +-- +--updateNode :: Node -> IO () +--updateNode = undefined +-- +-- +-- +-- +--parents :: Node -> [Node] +--parents = undefined +-- +--children :: Node -> [Node] +--children = undefined +-- +-- +-- + + +-- projects :: User -> [Project] +-- projects u = undefined + + + + + + + + + + + + + + + diff --git a/src/Data/Gargantext/Database.hs b/src/Data/Gargantext/Database.hs new file mode 100644 index 00000000..38c71f41 --- /dev/null +++ b/src/Data/Gargantext/Database.hs @@ -0,0 +1,29 @@ +module Data.Gargantext.Database ( module Data.Gargantext.Database.Private + , module Data.Gargantext.Database.Instances + , module Data.Gargantext.Database.User + , module Data.Gargantext.Database.Node + , module Data.Gargantext.Database.NodeNode + , module Data.Gargantext.Database.Ngram + , module Data.Gargantext.Database.NodeNgram + , module Data.Gargantext.Database.NodeNodeNgram + , module Data.Gargantext.Database.NodeNgramNgram +-- , module Data.Gargantext.Database.Gargandb +-- , module Data.Gargantext.Database.Simple +-- , module Data.Gargantext.Database.InsertNode +-- , module Data.Gargantext.Database.NodeType + ) where + +import Data.Gargantext.Database.Private +import Data.Gargantext.Database.Instances +--import Data.Gargantext.Database.Gargandb +import Data.Gargantext.Database.User +import Data.Gargantext.Database.Node +import Data.Gargantext.Database.NodeNode +import Data.Gargantext.Database.Ngram +import Data.Gargantext.Database.NodeNgram +import Data.Gargantext.Database.NodeNodeNgram +import Data.Gargantext.Database.NodeNgramNgram +--import Data.Gargantext.Database.Simple +--import Data.Gargantext.Database.NodeType +--import Data.Gargantext.Database.InsertNode + diff --git a/src/Data/Gargantext/Database/Instances.hs b/src/Data/Gargantext/Database/Instances.hs new file mode 100644 index 00000000..c183ff7c --- /dev/null +++ b/src/Data/Gargantext/Database/Instances.hs @@ -0,0 +1,27 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} + +module Data.Gargantext.Database.Instances where + +import Data.Time (UTCTime) +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , QueryRunnerColumnDefault + , queryRunnerColumnDefault + , fieldQueryRunnerColumn + ) + +instance QueryRunnerColumnDefault PGInt4 Integer where + queryRunnerColumnDefault = fieldQueryRunnerColumn + +instance QueryRunnerColumnDefault PGFloat8 (Maybe Double) where + queryRunnerColumnDefault = fieldQueryRunnerColumn + +instance QueryRunnerColumnDefault PGInt4 (Maybe Int) where + queryRunnerColumnDefault = fieldQueryRunnerColumn + +instance QueryRunnerColumnDefault PGTimestamptz (Maybe UTCTime) where + queryRunnerColumnDefault = fieldQueryRunnerColumn + + + + diff --git a/src/Data/Gargantext/Database/Ngram.hs b/src/Data/Gargantext/Database/Ngram.hs new file mode 100644 index 00000000..69c9962f --- /dev/null +++ b/src/Data/Gargantext/Database/Ngram.hs @@ -0,0 +1,82 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.Ngram where + +import Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +-- Functions only +import Data.List (find) + + +data NgramPoly id terms n = Ngram { ngram_id :: id + , ngram_terms :: terms + , ngram_n :: n + } deriving (Show) + +type NgramWrite = NgramPoly (Maybe (Column PGInt4)) (Column PGText) (Column PGInt4) +type NgramRead = NgramPoly (Column PGInt4) (Column PGText) (Column PGInt4) + +type Ngram = NgramPoly Int Text Int + +$(makeAdaptorAndInstance "pNgram" ''NgramPoly) +$(makeLensesWith abbreviatedFields ''NgramPoly) + + +ngramTable :: O.Table NgramWrite NgramRead +ngramTable = O.Table "ngrams" (pNgram Ngram { ngram_id = O.optional "id" + , ngram_terms = O.required "terms" + , ngram_n = O.required "n" + } + ) + + +queryNgramTable :: Query NgramRead +queryNgramTable = O.queryTable ngramTable + + +--selectUsers :: Query UserRead +--selectUsers = proc () -> do +-- --user@(i, p, ll, is, un, fn, ln, m, iff, ive, dj) <- queryUserTable -< () +-- row@(User i p ll is un fn ln m iff ive dj) <- queryUserTable -< () +-- O.restrict -< i .== 1 +-- --returnA -< User i p ll is un fn ln m iff ive dj +-- returnA -< row +-- + +findWith :: (Eq a1, Foldable t) => (a -> a1) -> a1 -> t a -> Maybe a +findWith f t = find (\x -> f x == t) + +--userWithUsername :: Text -> [User] -> Maybe User +--userWithUsername t xs = userWith userUsername t xs +-- +--userWithId :: Integer -> [User] -> Maybe User +--userWithId t xs = userWith userUserId t xs + +-- | not optimized (get all ngrams without filters) +ngrams :: IO [Ngram] +ngrams = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryNgramTable + diff --git a/src/Data/Gargantext/Database/Node.hs b/src/Data/Gargantext/Database/Node.hs new file mode 100644 index 00000000..6d3cc52d --- /dev/null +++ b/src/Data/Gargantext/Database/Node.hs @@ -0,0 +1,140 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.Node where + + + +import Database.PostgreSQL.Simple.FromField (Conversion, ResultError(ConversionFailed), FromField, fromField, returnError) +import Database.PostgreSQL.Simple.Internal (Field) +import Control.Arrow (returnA) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Data.Aeson +import Data.Aeson.TH +import Data.Aeson.Types +import Data.Gargantext.Database.Instances +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Prelude +import Data.Gargantext.Types +import Data.Gargantext.Utils.Prefix +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Data.Text (Text) +import Data.Time (UTCTime) +import Data.Typeable.Internal (Typeable) +import GHC.Generics (Generic) +import qualified Data.ByteString.Internal as DBI +import qualified Database.PostgreSQL.Simple as PGS +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , Table(Table), PGJsonb, Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + ) + + +-- | Types for Node Database Management + +type NodeWrite = NodePoly (Maybe (Column PGInt4)) (Column PGInt4) + (Column PGInt4) (Column PGInt4) + (Column PGText) (Maybe (Column PGTimestamptz)) + (Column PGJsonb) + +type NodeRead = NodePoly (Column PGInt4) (Column PGInt4) + (Column PGInt4) (Column PGInt4) + (Column PGText) (Column PGTimestamptz) + (Column PGJsonb) + +instance FromField HyperdataCorpus where + fromField = fromField' + +instance FromField HyperdataDocument where + fromField = fromField' + +--instance FromField HyperdataProject where +-- fromField = fromField' + +--instance FromField HyperdataUser where +-- fromField = fromField' + + +fromField' :: (Typeable b, FromJSON b) => Field -> Maybe DBI.ByteString -> Conversion b +fromField' field mb = do + v <- fromField field mb + valueToHyperdata v + where + valueToHyperdata v = case fromJSON v of + Success a -> pure a + Error err -> returnError ConversionFailed field "cannot parse hyperdata" + + +instance O.QueryRunnerColumnDefault PGJsonb HyperdataDocument where + queryRunnerColumnDefault = fieldQueryRunnerColumn + +instance O.QueryRunnerColumnDefault PGJsonb HyperdataCorpus where + queryRunnerColumnDefault = fieldQueryRunnerColumn + + + + +$(makeAdaptorAndInstance "pNode" ''NodePoly) +$(makeLensesWith abbreviatedFields ''NodePoly) + + +nodeTable :: O.Table NodeWrite NodeRead +nodeTable = O.Table "nodes" (pNode Node { node_id = O.optional "id" + , node_typename = O.required "typename" + , node_userId = O.required "user_id" + , node_parentId = O.required "parent_id" + , node_name = O.required "name" + , node_date = O.optional "date" + , node_hyperdata = O.required "hyperdata" + } + ) + + + + +selectNodes :: Column PGInt4 -> Query (Column O.PGText) +selectNodes node_id = proc () -> do + row@(Node n_id tn u p n d h) <- queryNodeTable -< () + O.restrict -< n_id .== node_id + returnA -< n + + +runGetNodes :: PGS.Connection -> Query NodeRead -> IO [Document] +runGetNodes = O.runQuery + + +queryNodeTable :: Query NodeRead +queryNodeTable = O.queryTable nodeTable + + +selectNode :: Column PGInt4 -> Query NodeRead +selectNode node_id = proc () -> do + row@(Node id tn u p_id n d h) <- queryNodeTable -< () + O.restrict -< p_id .== node_id + returnA -< row + + +getNodes :: Column PGInt4 -> IO [Document] +getNodes node_id = do + conn <- PGS.connect infoGargandb + O.runQuery conn $ selectNode node_id + +getCorpusDocument :: Column PGInt4 -> IO [Document] +getCorpusDocument node_id = PGS.connect infoGargandb >>= + \conn -> O.runQuery conn (selectNode node_id) + +getProjectCorpora :: Column PGInt4 -> IO [Corpus] +getProjectCorpora node_id = do + conn <- PGS.connect infoGargandb + O.runQuery conn $ selectNode node_id + + + diff --git a/src/Data/Gargantext/Database/NodeNgram.hs b/src/Data/Gargantext/Database/NodeNgram.hs new file mode 100644 index 00000000..116edce3 --- /dev/null +++ b/src/Data/Gargantext/Database/NodeNgram.hs @@ -0,0 +1,64 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.NodeNgram where + +import Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +data NodeNgramPoly id node_id ngram_id weight + = NodeNgram { nodeNgram_NodeNgramId :: id + , nodeNgram_NodeNgramNodeId :: node_id + , nodeNgram_NodeNgramNgramId :: ngram_id + , nodeNgram_NodeNgramWeight :: weight + } deriving (Show) + +type NodeNgramWrite = NodeNgramPoly (Maybe (Column PGInt4)) (Column PGInt4) (Column PGInt4) (Maybe (Column PGFloat8)) +type NodeNgramRead = NodeNgramPoly (Column PGInt4) (Column PGInt4) (Column PGInt4) ((Column PGFloat8)) + + +type NodeNgram = NodeNgramPoly (Maybe Int) Int Int (Maybe Double) + +$(makeAdaptorAndInstance "pNodeNgram" ''NodeNgramPoly) +$(makeLensesWith abbreviatedFields ''NodeNgramPoly) + + +nodeNgramTable :: O.Table NodeNgramWrite NodeNgramRead +nodeNgramTable = O.Table "nodes_ngrams" (pNodeNgram NodeNgram { nodeNgram_NodeNgramId = O.optional "id" + , nodeNgram_NodeNgramNodeId = O.required "node_id" + , nodeNgram_NodeNgramNgramId = O.required "ngram_id" + , nodeNgram_NodeNgramWeight = O.optional "weight" + } + ) + + +queryNodeNgramTable :: Query NodeNgramRead +queryNodeNgramTable = O.queryTable nodeNgramTable + + +-- | not optimized (get all ngrams without filters) +nodeNgrams :: IO [NodeNgram] +nodeNgrams = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryNodeNgramTable + diff --git a/src/Data/Gargantext/Database/NodeNgramNgram.hs b/src/Data/Gargantext/Database/NodeNgramNgram.hs new file mode 100644 index 00000000..78c4413f --- /dev/null +++ b/src/Data/Gargantext/Database/NodeNgramNgram.hs @@ -0,0 +1,66 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.NodeNgramNgram where + +import Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +data NodeNgramNgramPoly node_id ngram1_id ngram2_id weight + = NodeNgramNgram { nodeNgramNgram_NodeNgramNgram_NodeId :: node_id + , nodeNgramNgram_NodeNgramNgram_Ngram1Id :: ngram1_id + , nodeNgramNgram_NodeNgramNgram_Ngram2Id :: ngram2_id + , nodeNgramNgram_NodeNgramNgram_Weight :: weight + } deriving (Show) + + +type NodeNgramNgramWrite = NodeNgramNgramPoly (Maybe (Column PGInt4)) (Column PGInt4) (Column PGInt4) (Maybe (Column PGFloat8)) +type NodeNgramNgramRead = NodeNgramNgramPoly (Column PGInt4) (Column PGInt4) (Column PGInt4) (Column PGFloat8) + + +type NodeNgramNgram = NodeNgramNgramPoly (Maybe Int) Int Int (Maybe Double) + +$(makeAdaptorAndInstance "pNodeNgramNgram" ''NodeNgramNgramPoly) +$(makeLensesWith abbreviatedFields ''NodeNgramNgramPoly) + + +nodeNgramNgramTable :: O.Table NodeNgramNgramWrite NodeNgramNgramRead +nodeNgramNgramTable = O.Table "nodes_ngrams_ngrams" ( pNodeNgramNgram NodeNgramNgram + { nodeNgramNgram_NodeNgramNgram_NodeId = O.optional "node_id" + , nodeNgramNgram_NodeNgramNgram_Ngram1Id = O.required "ngram1_id" + , nodeNgramNgram_NodeNgramNgram_Ngram2Id = O.required "ngram2_id" + , nodeNgramNgram_NodeNgramNgram_Weight = O.optional "weight" + } + ) + + +queryNodeNgramNgramTable :: Query NodeNgramNgramRead +queryNodeNgramNgramTable = O.queryTable nodeNgramNgramTable + + +-- | not optimized (get all ngrams without filters) +nodeNgramNgrams :: IO [NodeNgramNgram] +nodeNgramNgrams = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryNodeNgramNgramTable + diff --git a/src/Data/Gargantext/Database/NodeNode.hs b/src/Data/Gargantext/Database/NodeNode.hs new file mode 100644 index 00000000..4d554cb8 --- /dev/null +++ b/src/Data/Gargantext/Database/NodeNode.hs @@ -0,0 +1,63 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.NodeNode where + +import Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + , required, optional + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +data NodeNodePoly node1_id node2_id score + = NodeNode { nodeNode_node1_id :: node1_id + , nodeNode_node2_id :: node2_id + , nodeNode_score :: score + } deriving (Show) + +type NodeNodeWrite = NodeNodePoly (Column PGInt4) (Column PGInt4) (Maybe (Column PGFloat8)) +type NodeNodeRead = NodeNodePoly (Column PGInt4) (Column PGInt4) (Column PGFloat8) + + +type NodeNode = NodeNodePoly Int Int (Maybe Double) + +$(makeAdaptorAndInstance "pNodeNode" ''NodeNodePoly) +$(makeLensesWith abbreviatedFields ''NodeNodePoly) + + +nodeNodeTable :: O.Table NodeNodeWrite NodeNodeRead +nodeNodeTable = O.Table "nodes_nodes" (pNodeNode NodeNode { nodeNode_node1_id = required "node1_id" + , nodeNode_node2_id = required "node2_id" + , nodeNode_score = optional "score" + } + ) + + +queryNodeNodeTable :: Query NodeNodeRead +queryNodeNodeTable = O.queryTable nodeNodeTable + + +-- | not optimized (get all ngrams without filters) +nodeNodes :: IO [NodeNode] +nodeNodes = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryNodeNodeTable + diff --git a/src/Data/Gargantext/Database/NodeNodeNgram.hs b/src/Data/Gargantext/Database/NodeNodeNgram.hs new file mode 100644 index 00000000..518280f9 --- /dev/null +++ b/src/Data/Gargantext/Database/NodeNodeNgram.hs @@ -0,0 +1,66 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.NodeNodeNgram where + +import Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz, PGFloat8 + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +data NodeNodeNgramPoly node1_id node2_id ngram_id score + = NodeNodeNgram { nodeNodeNgram_node1_id :: node1_id + , nodeNodeNgram_node2_id :: node2_id + , nodeNodeNgram_ngram_id :: ngram_id + , nodeNodeNgram_score :: score + } deriving (Show) + + +type NodeNodeNgramWrite = NodeNodeNgramPoly (Column PGInt4) (Column PGInt4) (Column PGInt4) (Maybe (Column PGFloat8)) +type NodeNodeNgramRead = NodeNodeNgramPoly (Column PGInt4) (Column PGInt4) (Column PGInt4) (Column PGFloat8) + + +type NodeNodeNgram = NodeNodeNgramPoly Int Int Int (Maybe Double) + +$(makeAdaptorAndInstance "pNodeNodeNgram" ''NodeNodeNgramPoly) +$(makeLensesWith abbreviatedFields ''NodeNodeNgramPoly) + + +nodeNodeNgramTable :: O.Table NodeNodeNgramWrite NodeNodeNgramRead +nodeNodeNgramTable = O.Table "nodes_nodes_ngrams" ( pNodeNodeNgram NodeNodeNgram + { nodeNodeNgram_node1_id = O.required "node1_id" + , nodeNodeNgram_node2_id = O.required "node2_id" + , nodeNodeNgram_ngram_id = O.required "ngram_id" + , nodeNodeNgram_score = O.optional "score" + } + ) + + +queryNodeNodeNgramTable :: Query NodeNodeNgramRead +queryNodeNodeNgramTable = O.queryTable nodeNodeNgramTable + + +-- | not optimized (get all ngrams without filters) +nodeNodeNgrams :: IO [NodeNodeNgram] +nodeNodeNgrams = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryNodeNodeNgramTable + diff --git a/src/Data/Gargantext/Database/Private.hs b/src/Data/Gargantext/Database/Private.hs new file mode 100644 index 00000000..da3eae61 --- /dev/null +++ b/src/Data/Gargantext/Database/Private.hs @@ -0,0 +1,15 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Data.Gargantext.Database.Private where + +import qualified Database.PostgreSQL.Simple as PGS + +-- TODO add a reader Monad here +infoGargandb :: PGS.ConnectInfo +infoGargandb = PGS.ConnectInfo { PGS.connectHost = "127.0.0.1" + , PGS.connectPort = 5432 + , PGS.connectUser = "gargantua" + , PGS.connectPassword = "C8kdcUrAQy66U" + , PGS.connectDatabase = "gargandb" } + + diff --git a/src/Data/Gargantext/Database/User.hs b/src/Data/Gargantext/Database/User.hs new file mode 100644 index 00000000..fa260ea0 --- /dev/null +++ b/src/Data/Gargantext/Database/User.hs @@ -0,0 +1,130 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE Arrows #-} + +module Data.Gargantext.Database.User where + +import Prelude +import Data.Gargantext.Prelude +import Data.Time (UTCTime) +import Data.Text (Text) +import Data.Maybe (Maybe) +import Data.Profunctor.Product.TH (makeAdaptorAndInstance) +import Control.Lens.TH (makeLensesWith, abbreviatedFields) +import Control.Arrow (returnA) +import qualified Database.PostgreSQL.Simple as PGS + +import qualified Opaleye as O +import Opaleye (Column, PGBool, PGInt4, PGText, PGTimestamptz + , Table(Table), Query + , QueryRunnerColumnDefault, queryRunnerColumnDefault + , fieldQueryRunnerColumn + , (.==), (.>) + , required, optional + ) + +import Data.Gargantext.Database.Private (infoGargandb) +import Data.Gargantext.Database.Instances + +-- Functions only +import Data.List (find) + + +data UserLight = UserLight { userLight_id :: Int + , userLight_username :: Text + , userLight_email :: Text + } deriving (Show) + +toUserLight :: User -> UserLight +toUserLight (User id _ _ _ u _ _ e _ _ _ ) = UserLight id u e + +data UserPoly id pass llogin suser + uname fname lname + mail staff active djoined = User { user_id :: id + , user_password :: pass + , user_lastLogin :: llogin + , user_isSuperUser :: suser + + , user_username :: uname + , user_firstName :: fname + , user_lastName :: lname + , user_email :: mail + + , user_isStaff :: staff + , user_isActive :: active + , user_dateJoined :: djoined + } deriving (Show) + +type UserWrite = UserPoly (Maybe (Column PGInt4)) (Column PGText) + (Maybe (Column PGTimestamptz)) (Column PGBool) + (Column PGText) (Column PGText) + (Column PGText) (Column PGText) + (Column PGBool) (Column PGBool) + (Column PGTimestamptz) + +type UserRead = UserPoly (Column PGInt4) (Column PGText) + (Column PGTimestamptz) (Column PGBool) + (Column PGText) (Column PGText) + (Column PGText) (Column PGText) + (Column PGBool) (Column PGBool) + (Column PGTimestamptz) + +type User = UserPoly Int Text (Maybe UTCTime) Bool Text Text Text Text Bool Bool UTCTime + +$(makeAdaptorAndInstance "pUser" ''UserPoly) +$(makeLensesWith abbreviatedFields ''UserPoly) + + +userTable :: O.Table UserWrite UserRead +userTable = O.Table "auth_user" (pUser User { user_id = optional "id" + , user_password = required "password" + , user_lastLogin = optional "last_login" + , user_isSuperUser = required "is_superuser" + , user_username = required "username" + , user_firstName = required "first_name" + , user_lastName = required "last_name" + , user_email = required "email" + , user_isStaff = required "is_staff" + , user_isActive = required "is_active" + , user_dateJoined = required "date_joined" + } + ) + + +queryUserTable :: Query UserRead +queryUserTable = O.queryTable userTable + + +selectUsersLight :: Query UserRead +selectUsersLight = proc () -> do + row@(User i p ll is un fn ln m iff ive dj) <- queryUserTable -< () + O.restrict -< i .== 1 + --returnA -< User i p ll is un fn ln m iff ive dj + returnA -< row + + +userWith :: (Eq a1, Foldable t) => (a -> a1) -> a1 -> t a -> Maybe a +userWith f t xs = find (\x -> f x == t) xs + +userWithUsername :: Text -> [User] -> Maybe User +userWithUsername t xs = userWith user_username t xs + +userWithId :: Int -> [User] -> Maybe User +userWithId t xs = userWith user_id t xs + + +users :: IO [User] +users = do + conn <- PGS.connect infoGargandb + O.runQuery conn queryUserTable + +usersLight :: IO [UserLight] +usersLight = do + conn <- PGS.connect infoGargandb + pm toUserLight <$> O.runQuery conn queryUserTable + + + + diff --git a/src/Data/Gargantext/Ngrams.hs b/src/Data/Gargantext/Ngrams.hs new file mode 100644 index 00000000..47c12a77 --- /dev/null +++ b/src/Data/Gargantext/Ngrams.hs @@ -0,0 +1,11 @@ +module Data.Gargantext.Ngrams ( + module Data.Gargantext.Ngrams.TextMining, + module Data.Gargantext.Ngrams.Words, + module Data.Gargantext.Ngrams.Hetero, + module Data.Gargantext.Ngrams.Count + ) where + +import Data.Gargantext.Ngrams.TextMining +import Data.Gargantext.Ngrams.Words +import Data.Gargantext.Ngrams.Hetero +import Data.Gargantext.Ngrams.Count diff --git a/src/Data/Gargantext/Ngrams/Count.hs b/src/Data/Gargantext/Ngrams/Count.hs new file mode 100644 index 00000000..f65901ae --- /dev/null +++ b/src/Data/Gargantext/Ngrams/Count.hs @@ -0,0 +1,47 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Data.Gargantext.Ngrams.Count where + +import System.Environment (getArgs) + +import Data.List (foldl', take) +import Data.Foldable as F + +import Data.Map (Map) +import qualified Data.Map as M + +import qualified Data.Text.Lazy.IO as DTLIO +import qualified Data.Text.Lazy as DTL + +-- | /O(n)/ Breaks a 'Text' up into each Text list of chars. +-- from slower to faster: +letters :: DTL.Text -> [DTL.Text] +letters text = DTL.chunksOf 1 text + +letters' :: DTL.Text -> [DTL.Text] +letters' text = DTL.splitOn "#" $ DTL.intersperse '#' text + +letters'' :: DTL.Text -> [DTL.Text] +letters'' = DTL.foldr (\ch xs -> DTL.singleton ch : xs) [] + + +-- words +-- lines +-- words between punctuation +-- number of punctuation + +occurrences :: Ord a => [a] -> Map a Int +occurrences xs = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty xs + +-- for optimization : +--occurrences' :: Ord a => [a] -> Map a Integer +--occurrences' xs = DTL.foldl (\x y -> M.insertWith' (+) y 1 x) M.empty xs + + +countMain = do + (fichier:rest) <- getArgs + c <- DTLIO.readFile fichier + --print $ occurrences $ DTL.chunksOf 1 c + print $ occurrences $ letters'' c + --print $ occurrences $ DTL.words $ DTL.toLower c + diff --git a/src/Data/Gargantext/Ngrams/Hetero.hs b/src/Data/Gargantext/Ngrams/Hetero.hs new file mode 100644 index 00000000..f9053017 --- /dev/null +++ b/src/Data/Gargantext/Ngrams/Hetero.hs @@ -0,0 +1,75 @@ +module Data.Gargantext.Ngrams.Hetero where + +import GHC.Real as R +import Data.Set as S +import Data.Map as M +import Data.List.Split as S +import Database.PostgreSQL.Simple as PGS +import Opaleye.PGTypes (PGInt4) +import Opaleye.Internal.Column (Column) + +import Data.Gargantext.Database.Gargandb +import Data.Gargantext.Database.Private +import Data.Gargantext.Utils.Chronos + +import Data.Gargantext.Ngrams.Words (cleanText) +import Data.Gargantext.Ngrams.Count (occurrences) + +import Data.Gargantext.Database.Simple + +--main = do +-- t <- getTextquery +-- print (Prelude.map (heterogeinity . concat) $ S.chunksOf 3 t) + +-- heterogeinity sur concat texts +heterogeinity' :: Int -> Int -> Int -> IO [Integer] +heterogeinity' corpus_id limit x = do + t <- getAbstract corpus_id limit + Prelude.mapM (dicoStruct . occurrences) $ (S.chunksOf x) . cleanText $ concat t + +heterogeinity'' :: Int -> Int -> Int -> IO [Integer] +heterogeinity'' corpus_id limit size = do + t <- getAbstract corpus_id limit + Prelude.mapM (dicoStruct . occurrences) $ (S.chunksOf size) . cleanText $ concat t + + +dicoStruct :: (Integral r, Monad m) => M.Map t r -> m r +dicoStruct dict_occ = do + let keys_size = toInteger $ length $ M.keys dict_occ + let total_occ = sum $ Prelude.map (\(x, y) -> y) $ M.toList dict_occ + return $ div total_occ (fromIntegral keys_size) + +-- heterogeinity sur UCT (Unité de Context Textuel) +heterogeinity :: [Char] -> IO Integer +heterogeinity string = do + let dict_occ = occurrences $ cleanText string + + let keys_size = toInteger $ length $ M.keys dict_occ + let total_occ = sum $ Prelude.map (\(x, y) -> y) $ M.toList dict_occ + + return $ div total_occ (fromIntegral keys_size) + + +--computeHeterogeinity +-- :: Fractional t => +-- Opaleye.Internal.Column.Column Opaleye.PGTypes.PGInt4 +-- -> IO (t, Integer, Integer) +computeHeterogeinity corpus_id = do + c <- PGS.connect infoGargandb + t <- getText c (nodeHyperdataText corpus_id) + heterogeinity $ Prelude.concat t + +main2 = do + let corpus_ids = [ + ("ALL", 272927) -- 73 + ,("Histoire", 1387736) -- 28 + ,("Sciences Po", 1296892) -- 37 + ,("Phylosophie", 1170004) -- 20 + ,("Psychologie", 1345852) -- 37 + ,("Sociologie", 1246452) -- 42 + ] + + r <- Prelude.map computeHeterogeinity $ Prelude.map (\(t,id) -> id) corpus_ids + return r + + diff --git a/src/Data/Gargantext/Ngrams/TextMining.hs b/src/Data/Gargantext/Ngrams/TextMining.hs new file mode 100644 index 00000000..182ec3dc --- /dev/null +++ b/src/Data/Gargantext/Ngrams/TextMining.hs @@ -0,0 +1,56 @@ +module Data.Gargantext.Ngrams.TextMining where + +import Data.Map (empty, Map, insertWith, toList) +import Data.List (foldl, foldl') +import qualified Data.List as L + + +sortGT (a1, b1) (a2, b2) + | a1 < a2 = GT + | a1 > a2 = LT + | a1 == a2 = compare b1 b2 + + +--histogram :: Ord a => [a] -> [(a, Int)] +--histogram = map (head &&& length) Prelude.. group Prelude.. sort Prelude.. words +--histogram = sortGT Prelude.. $ map (head &&& length) Prelude.. group Prelude.. sort Prelude.. words + +countElem :: (Ord k) => Data.Map.Map k Int -> k -> Data.Map.Map k Int +countElem m e = Data.Map.insertWith (\n o -> n + o) e 1 m + +freqList :: (Ord k) => [k] -> Data.Map.Map k Int +freqList = foldl countElem Data.Map.empty + +--getMaxFromMap :: Data.Map.Map -> Maybe -> [a] -> [a] +getMaxFromMap m = go [] Nothing (toList m) + where + go ks _ [] = ks + go ks Nothing ((k,v):rest) = go (k:ks) (Just v) rest + go ks (Just u) ((k,v):rest) + | v < u = go ks (Just u) rest + | v > u = go [k] (Just v) rest + | otherwise = go (k:ks) (Just v) rest + +merge :: [a] -> [a] -> [a] +merge [] ys = ys +merge (x:xs) ys = x:merge ys xs + +average :: [Double] -> Double +average x = L.sum x / L.genericLength x + +average' :: [Int] -> Double +average' x = (L.sum y) / (L.genericLength y) where + y = map fromIntegral x + + +countYear :: [Integer] -> Map Integer Integer +countYear [] = empty +countYear (x:xs) = insertWith (+) x 1 (countYear xs) + +countYear' :: [Integer] -> Map Integer Integer +countYear' (xs) = foldl' (\x y -> insertWith (+) y 1 x) empty xs + + +textMiningMain :: IO () +textMiningMain = do + print $ merge ["abc"] ["bcd"] diff --git a/src/Data/Gargantext/Ngrams/Utils.hs b/src/Data/Gargantext/Ngrams/Utils.hs new file mode 100644 index 00000000..3e9e252f --- /dev/null +++ b/src/Data/Gargantext/Ngrams/Utils.hs @@ -0,0 +1,32 @@ +-- module Data.Gargantext.Ngrams.Utils where + + +-- calculate levenshtein distance between two strings +levenshtein::[Char] -> [Char] -> Int +levenshtein "" "" = 0 +levenshtein "" s2 = length s2 +levenshtein s1 "" = length s1 +levenshtein s1 s2 + | last s1 == last s2 = levenshtein (init s1) (init s2) + | otherwise = minimum [ + 1 + levenshtein (init s1) s2, + 1 + levenshtein s1 (init s2), + 1 + levenshtein (init s1) (init s2) + ] + + +-- calculate levenshtein distance between two strings +levenshtein::[Char] -> [Char] -> Int +-- this part is mostly a speed optimiziation +levenshtein' s1 s2 + | length s1 > length s2 = levenshtein s2 s1 + | length s1 < length s2 = + let d = length s2 - length s1 + in d + levenshtein s1 (take (length s2 - d) s2) + -- the meat of the algorithm +levenshtein' "" "" = 0 +levenshtein' s1 s2 + | last s1 == last s2 = levenshtein (init s1) (init s2) + | otherwise = minimum [1 + levenshtein (init s1) s2, + 1 + levenshtein s1 (init s2), + 1 + levenshtein (init s1) (init s2)] diff --git a/src/Data/Gargantext/Ngrams/Words.hs b/src/Data/Gargantext/Ngrams/Words.hs new file mode 100644 index 00000000..375e36f1 --- /dev/null +++ b/src/Data/Gargantext/Ngrams/Words.hs @@ -0,0 +1,60 @@ + +module Data.Gargantext.Ngrams.Words where +import Data.List (partition) +import Data.Set (fromList, notMember, member) +import Data.Char (isPunctuation, toLower, isAlpha, isSpace) + +import NLP.Stemmer (stem, Stemmer(..)) +import Language.Aspell (check, suggest, spellChecker, spellCheckerWithOptions) +import Language.Aspell.Options (ACOption(..)) + +--import Data.Either.Utils (fromRight) +import Data.ByteString.Internal (packChars) + + +get_lang x = do + let lang = Lang (packChars x) + spell_lang <- spellCheckerWithOptions [lang] + return spell_lang + +check' lang x = check lang (packChars x) +suggest' lang x = suggest lang (packChars x) + +--spell_lang <- spellChecker +--lang = fromRight s +--suggest' lang x + +-- stem French "naturelles" + + +-- paragraphes +-- lines +-- sentences + +-- Prelude.map (\x -> stem French x) $ cleanText "Les hirondelles s envolent dans les cieux." +repl :: Char -> Char +repl x + | x == '\'' = ' ' + | x == '/' = ' ' + -- | x == '\t' = ' ' + -- | x == '\n' = ' ' + | otherwise = x + +cleanText text = do + -- pb avec \' + --words $ filter (not . isPunctuation) $ Prelude.map toLower text + words $ filter (\x -> isAlpha x || isSpace x) $ Prelude.map (repl . toLower) text + +isMiamWord word = do + let miamWord_set = fromList ["salut", "phrase"] + member word miamWord_set + +isStopWord word = do + let stopWord_set = fromList ["de", "la", "une", "avec"] + member word stopWord_set + +wordsMain = do + let text = "Salut, ceci est une phrase \n\n avec de la ponctuation !" + print $ partition (not . isStopWord) $ cleanText text + print $ filter (not . isStopWord) $ cleanText text + --print $ filter isStopWord $ words $ filter (not . isPunctuation) text diff --git a/src/Data/Gargantext/Parsers.hs b/src/Data/Gargantext/Parsers.hs new file mode 100644 index 00000000..37250ac4 --- /dev/null +++ b/src/Data/Gargantext/Parsers.hs @@ -0,0 +1,3 @@ +module Data.Gargantext.Parsers (module Data.Gargantext.Parsers.Occurrences) + where +import Data.Gargantext.Parsers.Occurrences diff --git a/src/Data/Gargantext/Parsers/Occurrences.hs b/src/Data/Gargantext/Parsers/Occurrences.hs new file mode 100644 index 00000000..de31820b --- /dev/null +++ b/src/Data/Gargantext/Parsers/Occurrences.hs @@ -0,0 +1,28 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Data.Gargantext.Parsers.Occurrences where + +import Data.Gargantext.Prelude +import Data.Attoparsec.Text +import Data.Text (Text) + + +import Data.Either.Extra(Either(..)) +import qualified Data.Text as T +import Control.Applicative + +occurrenceParser :: Text -> Parser Bool +occurrenceParser txt = manyTill anyChar (string txt) >> pure True + +occurrencesParser :: Text -> Parser Int +occurrencesParser txt = case txt of + "" -> pure 0 + _ -> many (occurrenceParser txt') >>= \matches -> pure (length matches) + where + txt' = T.toLower txt + +parseOccurrences :: Text -> Text -> Either String Int +parseOccurrences x = parseOnly (occurrencesParser x) + + + diff --git a/src/Data/Gargantext/Prelude.hs b/src/Data/Gargantext/Prelude.hs new file mode 100644 index 00000000..20149b6a --- /dev/null +++ b/src/Data/Gargantext/Prelude.hs @@ -0,0 +1,170 @@ +{-# LANGUAGE NoImplicitPrelude #-} + +module Data.Gargantext.Prelude where + +import Protolude + +-- TODO import functions optimized in Utils.Count +-- import Protolude hiding (head, last, all, any, sum, product, length) +-- import Data.Gargantext.Utils.Count + +import qualified Data.List as L hiding (head, sum) +import qualified Control.Monad as M +import qualified Data.Map as Map +import qualified Data.Vector as V + +pf = filter +pr = reverse +pm = map + +pm2 :: (t -> b) -> [[t]] -> [[b]] +pm2 fun = pm (pm fun) + +pz = zip +pd = drop +ptk = take +pzw = zipWith + +-- Exponential Average +eavg :: [Double] -> Double +eavg (x:xs) = a*x + (1-a)*(eavg xs) + where a = 0.70 +eavg [] = 0 + +-- Simple Average +mean :: Fractional a => [a] -> a +mean xs = if L.null xs then 0.0 + else sum xs / fromIntegral (length xs) + +sumMaybe :: Num a => [Maybe a] -> Maybe a +sumMaybe = fmap sum . M.sequence + +variance :: Floating a => [a] -> a +variance xs = mean $ pm (\x -> (x - m) ** 2) xs where + m = mean xs + +deviation :: [Double] -> Double +deviation = sqrt . variance + +movingAverage :: Fractional b => Int -> [b] -> [b] +movingAverage steps xs = pm mean $ chunkAlong steps 1 xs + +ma :: [Double] -> [Double] +ma = movingAverage 3 + + +-- | Function to split a range into chunks +chunkAlong :: Int -> Int -> [a] -> [[a]] +chunkAlong a b l = only (while dropAlong) + where + only = pm (take a) + while = takeWhile (\x -> length x >= a) + dropAlong = L.scanl (\x y -> drop b x) l [1..] + +-- | Optimized version (Vector) +chunkAlong' :: Int -> Int -> V.Vector a -> V.Vector (V.Vector a) +chunkAlong' a b l = only (while dropAlong) + where + only = V.map (V.take a) + while = V.takeWhile (\x -> V.length x >= a) + dropAlong = V.scanl (\x y -> V.drop b x) l (V.fromList [1..]) + +-- | TODO Inverse of chunk ? unchunkAlong ? +unchunkAlong :: Int -> Int -> [[a]] -> [a] +unchunkAlong = undefined + + +-- splitAlong [2,3,4] ("helloworld" :: [Char]) == ["he", "llo", "worl", "d"] +splitAlong :: [Int] -> [Char] -> [[Char]] +splitAlong _ [] = [] -- No list? done +splitAlong [] xs = [xs] -- No place to split at? Return the remainder +splitAlong (x:xs) ys = take x ys : splitAlong xs (drop x ys) -- take until our split spot, recurse with next split spot and list remainder + +takeWhileM :: (Monad m) => (a -> Bool) -> [m a] -> m [a] +takeWhileM _ [] = return [] +takeWhileM p (a:as) = do + v <- a + if p v + then do + vs <- takeWhileM p as + return (v:vs) + else return [] + +-- SUMS +-- To select the right algorithme according to the type: +-- https://github.com/mikeizbicki/ifcxt + +sumSimple :: Num a => [a] -> a +sumSimple = L.foldl' (+) 0 + +-- | https://en.wikipedia.org/wiki/Kahan_summation_algorithm +sumKahan :: Num a => [a] -> a +sumKahan = snd . L.foldl' go (0,0) + where + go (c,t) i = ((t'-t)-y,t') + where + y = i-c + t' = t+y + +-- | compute part of the dict +count2map :: (Ord k, Foldable t) => t k -> Map.Map k Double +count2map xs = Map.map (/ (fromIntegral (length xs))) (count2map' xs) + +-- | insert in a dict +count2map' :: (Ord k, Foldable t) => t k -> Map.Map k Double +count2map' xs = L.foldl' (\x y -> Map.insertWith' (+) y 1 x) Map.empty xs + + +trunc :: (RealFrac a, Integral c, Integral b) => b -> a -> c +trunc n = truncate . (* 10^n) + +trunc' :: Int -> Double -> Double +trunc' n x = fromIntegral $ truncate $ (x * 10^n) + + +bool2int :: Num a => Bool -> a +bool2int bool = case bool of + True -> 1 + False -> 0 + +bool2double :: Bool -> Double +bool2double bool = case bool of + True -> 1.0 + False -> 0.0 + + + +-- Normalizing && scaling data +scale = scaleMinMax + +scaleMinMax :: [Double] -> [Double] +scaleMinMax xs = pm (\x -> (x - mi / (ma - mi + 1) )) xs' + where + ma = maximum xs' + mi = minimum xs' + xs' = pm abs xs + +scaleNormalize :: [Double] -> [Double] +scaleNormalize xs = pm (\x -> (x - v / (m + 1))) xs' + where + v = variance xs' + m = mean xs' + xs' = pm abs xs + + + +normalize :: [Double] -> [Double] +normalize as = normalizeWith identity as + +normalizeWith :: Fractional b => (a -> b) -> [a] -> [b] +normalizeWith extract bs = pm (\x -> x/(sum bs')) bs' + where + bs' = pm extract bs + +-- Zip functions to add +zipFst :: ([b] -> [a]) -> [b] -> [(a, b)] +zipFst f xs = zip (f xs) xs + +zipSnd :: ([a] -> [b]) -> [a] -> [(a, b)] +zipSnd f xs = zip xs (f xs) + diff --git a/src/Data/Gargantext/Server.hs b/src/Data/Gargantext/Server.hs new file mode 100644 index 00000000..42e739f3 --- /dev/null +++ b/src/Data/Gargantext/Server.hs @@ -0,0 +1,93 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeOperators #-} +module Data.Gargantext.Server +-- ( startApp +-- , app +-- ) + where + +import Control.Concurrent +import Control.Monad +import Control.Monad.IO.Class +import Data.Aeson +import Data.Aeson.TH +import Data.Gargantext.Types +import Network.HTTP.Client.MultipartFormData +import Network.Wai +import Network.Wai.Handler.Warp +import Servant +import Servant.Multipart + +-- | TODO, use MOCK feature of Servant to generate fake data (for tests) + +data FakeNode = FakeNode + { fakeNodeId :: Int + , fakeNodeName :: String + } deriving (Eq, Show) + +$(deriveJSON defaultOptions ''FakeNode) + +type API = "nodes" :> Get '[JSON] [FakeNode] + :<|> "node" :> Capture "id" Int :> Get '[JSON] FakeNode + :<|> "echo" :> Capture "string" String :> Get '[JSON] String + :<|> "upload" :> MultipartForm MultipartData :> Post '[JSON] String + + -- :<|> "node" :> Capture "id" Int :> Get '[JSON] Node + +server :: Server API +server = pure fakeNodes + :<|> fakeNode + :<|> echo + :<|> upload + where + echo s = pure s + + +startGargantext :: IO () +startGargantext = print ("Starting server on port " ++ show port) >> run port app + where + port = 8008 + +-- | TODO App type, the main monad in which the bot code is written with. +-- Provide config, state, logs and IO +-- type App m a = ( MonadState AppState m +-- , MonadReader Conf m +-- , MonadLog (WithSeverity Doc) m +-- , MonadIO m) => m a +-- Thanks @yannEsposito for this. +app :: Application +app = serve api server + +api :: Proxy API +api = Proxy + + +fakeNode :: Monad m => Int -> m FakeNode +fakeNode id = pure (fakeNodes !! id) + +fakeNodes :: [FakeNode] +fakeNodes = [ FakeNode 1 "Poincare" + , FakeNode 2 "Grothendieck" + ] + +-- | Upload files +-- TODO Is it possible to adapt the function according to iValue input ? +upload :: MultipartData -> Handler String +upload multipartData = do + liftIO $ do + putStrLn "Inputs:" + forM_ (inputs multipartData) $ \input -> + putStrLn $ " " ++ show (iName input) + ++ " -> " ++ show (iValue input) + + forM_ (files multipartData) $ \file -> do + content <- readFile (fdFilePath file) + putStrLn $ "Content of " ++ show (fdFileName file) + ++ " at " ++ fdFilePath file + putStrLn content + pure "Data loaded" + + + + diff --git a/src/Data/Gargantext/Types.hs b/src/Data/Gargantext/Types.hs new file mode 100644 index 00000000..f65e384e --- /dev/null +++ b/src/Data/Gargantext/Types.hs @@ -0,0 +1,6 @@ +module Data.Gargantext.Types ( module Data.Gargantext.Types.Main + , module Data.Gargantext.Types.Node + ) where + +import Data.Gargantext.Types.Main +import Data.Gargantext.Types.Node diff --git a/src/Data/Gargantext/Types/Main.hs b/src/Data/Gargantext/Types/Main.hs new file mode 100644 index 00000000..76ffe7bd --- /dev/null +++ b/src/Data/Gargantext/Types/Main.hs @@ -0,0 +1,132 @@ +-- | CNRS Copyrights +-- Licence: https://gitlab.iscpif.fr/humanities/gargantext/blob/stable/LICENSE +-- Author: Alexandre Delanoë (alexandre.delanoe@iscpif.fr) + +module Data.Gargantext.Types.Main where + +import Protolude (fromMaybe) +import Data.Text (Text) +import Data.Time (UTCTime) +import Data.Gargantext.Prelude +import Data.Gargantext.Types.Node ( NodePoly + , HyperdataFolder , HyperdataCorpus , HyperdataDocument + , HyperdataFavorites, HyperdataResource + , HyperdataList , HyperdataScore + , HyperdataGraph + , HyperdataPhylo + , HyperdataNotebook + ) + +-- | TODO add Symbolic Node / Document +-- TODO make instances of Nodes + +-- All the Database is structred like a hierachical Tree +-- Where a is a NodeType: +data Tree a = Empty | Node' a (Tree a) (Tree a) deriving (Show) + +--gargTree :: Tree NodeType +--gargTree = Node' NodeUser Empty +-- (Node' Empty +-- (Project Empty Empty) +-- ) +-- + + +data NodeType = NodeUser + | Folder | Project | Corpus | Document + | Favorites + | NodeSwap + | List | StopList | MainList | MapList | GroupList + | Score | Occurrences | Cooccurrences | Specclusion | Genclusion | Cvalue + | Tficf | TfidfCorpus | TfidfGlobal | TirankLocal | TirankGlobal + + deriving (Show, Eq) + + + +-- | NodePoly indicates that Node has a Polymorphism Type +type Node json = NodePoly Integer NodeTypeId Integer Integer Text UTCTime json +-- type Node json = NodePoly NodeId NodeTypeId UserId ParentId NodeName UTCTime json +type NodeTypeId = Int + +--type NodeUser = Node HyperdataUser + +-- | Then a Node can be either a Folder or a Corpus or a Document +type Folder = Node HyperdataFolder +type Project = Folder +type Corpus = Node HyperdataCorpus +type Document = Node HyperdataDocument + +-- | Community Manager Use Case +type Annuaire = Corpus +type Individu = Document + +-- | Favorites Node enable Node categorization +type Favorites = Node HyperdataFavorites + +-- | Favorites Node enable Swap Node with some synonyms for clarity +type NodeSwap = Node HyperdataResource + +-- | Then a Node can be a List which as some synonyms +type List = Node HyperdataList +type StopList = List +type MainList = List +type MapList = List +type GroupList = List + +-- | Then a Node can be a Score which as some synonyms +type Score = Node HyperdataScore +type Occurrences = Score +type Cooccurrences = Score +type Specclusion = Score +type Genclusion = Score +type Cvalue = Score +type Tficf = Score +-- TODO All these Tfidf* will be replaced with TFICF +type TfidfCorpus = Tficf +type TfidfGlobal = Tficf +type TirankLocal = Tficf +type TirankGlobal = Tficf + +-- | Then a Node can be either a Graph or a Phylo or a Notebook +type Graph = Node HyperdataGraph +type Phylo = Node HyperdataPhylo +type Notebook = Node HyperdataNotebook + + +nodeTypes :: [(NodeType, NodeTypeId)] +nodeTypes = [ + --(NodeUser , 1) +-- + (Project , 2) + , (NodeSwap , 19) + , (Corpus , 3) + , (Document , 4) +------ Lists + , (StopList , 5) + , (GroupList , 6) + , (MainList , 7) + , (MapList ,  8) +-- Scores + , (Occurrences , 10) + , (Cooccurrences , 9) + + , (Specclusion , 11) + , (Genclusion , 18) + , (Cvalue , 12) + + , (TfidfCorpus , 13) + , (TfidfGlobal , 14) + + , (TirankLocal , 16) + , (TirankGlobal , 17) + +-- Node management + , (Favorites , 15) + + ] +-- +nodeTypeId :: NodeType -> NodeTypeId +nodeTypeId tn = fromMaybe (error ("Typename " ++ show tn ++ " does not exist")) (lookup tn nodeTypes) + + diff --git a/src/Data/Gargantext/Types/Node.hs b/src/Data/Gargantext/Types/Node.hs new file mode 100644 index 00000000..02ac19be --- /dev/null +++ b/src/Data/Gargantext/Types/Node.hs @@ -0,0 +1,117 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE DeriveGeneric #-} + +module Data.Gargantext.Types.Node where + +import Data.Text (Text) +import Data.List (lookup) +import GHC.Generics (Generic) +import Data.Time (UTCTime) +import Data.Gargantext.Utils.Prefix +import Data.Aeson.TH + + + +data NodePoly id typename userId parentId name date hyperdata = Node { node_id :: id + , node_typename :: typename + , node_userId:: userId + -- , nodeHashId :: hashId + , node_parentId :: parentId + , node_name :: name + , node_date :: date + , node_hyperdata :: hyperdata + } deriving (Show) + + +data Statut = Statut { statut_Date :: Maybe UTCTime + , statut_Error :: Maybe Text + , statut_Action :: Maybe Text + , statut_Complete :: Maybe Bool + , statut_Progress :: Maybe Int + } deriving (Show, Generic) +$(deriveJSON (unPrefix "statut_") ''Statut) + + +data HyperdataDocument = HyperdataDocument { hyperdataDocument_Bdd :: Maybe Text + , hyperdataDocument_Doi :: Maybe Text + , hyperdataDocument_Url :: Maybe Text + , hyperdataDocument_Page :: Maybe Int + , hyperdataDocument_Title :: Maybe Text + , hyperdataDocument_Authors :: Maybe Text + , hyperdataDocument_Abstract :: Maybe Text + , hyperdataDocument_Statuses :: Maybe [Statut] + , hyperdataDocument_Publication_date :: Maybe Text + , hyperdataDocument_Publication_year :: Maybe Text + , hyperdataDocument_Publication_month :: Maybe Text + , hyperdataDocument_Publication_hour :: Maybe Text + , hyperdataDocument_Publication_minute :: Maybe Text + , hyperdataDocument_Publication_second :: Maybe Text + , hyperdataDocument_LanguageIso2 :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataDocument_") ''HyperdataDocument) + +data LanguageNodes = LanguageNodes { languageNodes___unknown__ :: [Int]} + deriving (Show, Generic) +$(deriveJSON (unPrefix "languageNodes_") ''LanguageNodes) + + +data Resource = Resource { resource_Url :: Maybe Text + , resource_Path :: Maybe Text + , resource_Type :: Maybe Int + , resource_Extracted :: Maybe Bool + } deriving (Show, Generic) +$(deriveJSON (unPrefix "resource_") ''Resource) + + +data HyperdataCorpus = HyperdataCorpus { hyperdataCorpus_Action :: Maybe Text + , hyperdataCorpus_Statuses :: Maybe [Statut] + , hyperdataCorpus_Languages :: Maybe LanguageNodes + , hyperdataCorpus_Resources :: Maybe [Resource] + , hyperdataCorpus_Language_id :: Maybe Text + , hyperdataCorpus_Skipped_docs :: Maybe [Int] + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataCorpus_") ''HyperdataCorpus) + + +data HyperdataFolder = HyperdataFolder { hyperdataFolder_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataFolder_") ''HyperdataFolder) + + +data HyperdataList = HyperdataList { hyperdataList_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataList_") ''HyperdataList) + +data HyperdataScore = HyperdataScore { hyperdataScore_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataScore_") ''HyperdataScore) + + + +data HyperdataFavorites = HyperdataFavorites { hyperdataFavorites_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataFavorites_") ''HyperdataFavorites) + +data HyperdataResource = HyperdataResource { hyperdataResource_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataResource_") ''HyperdataResource) + + + +-- TODO add the Graph Structure here +data HyperdataGraph = HyperdataGraph { hyperdataGraph_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataGraph_") ''HyperdataGraph) + + +-- TODO add the Graph Structure here +data HyperdataPhylo = HyperdataPhylo { hyperdataPhylo_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataPhylo_") ''HyperdataPhylo) + +-- | TODO FEATURE: Notebook saved in the node (to work with Python or Haskell) +data HyperdataNotebook = HyperdataNotebook { hyperdataNotebook_Preferences :: Maybe Text + } deriving (Show, Generic) +$(deriveJSON (unPrefix "hyperdataNotebook_") ''HyperdataNotebook) + + diff --git a/src/Data/Gargantext/Utils.hs b/src/Data/Gargantext/Utils.hs new file mode 100644 index 00000000..c48808ab --- /dev/null +++ b/src/Data/Gargantext/Utils.hs @@ -0,0 +1,6 @@ +module Data.Gargantext.Utils ( module Data.Gargantext.Utils.Chronos + , module Data.Gargantext.Utils.Prefix + ) where + +import Data.Gargantext.Utils.Chronos +module Data.Gargantext.Utils.Prefix diff --git a/src/Data/Gargantext/Utils/Chronos.hs b/src/Data/Gargantext/Utils/Chronos.hs new file mode 100644 index 00000000..6719e89e --- /dev/null +++ b/src/Data/Gargantext/Utils/Chronos.hs @@ -0,0 +1,94 @@ +module Data.Gargantext.Utils.Chronos where + +import Data.Maybe (fromJust, isJust, isNothing) +import qualified Data.Time as DT +import qualified Data.UTC as DU + +import Data.Time +import Data.Time.Clock.POSIX +import Text.Regex + +parseDate :: String -> Maybe [String] +parseDate d = matchRegex (mkRegex "(.*)/(.*)/(.*)") d + +getDate' :: Maybe [String] -> (Integer, Int, Int) +getDate' d + | isJust d == True = toGregorian $ fromGregorian (read year) (read month) (read day) + | otherwise = toGregorian $ fromGregorian 2015 1 1 + where + Just [day, month, year] = d + +getDate :: String -> (Integer, Int, Int) +getDate = getDate' . parseDate + +--getDateDay :: Maybe [String] -> Day +--getDateDay d = fromGregorian (read year) (read month) (read day) +-- where Just [day, month, year] = matchRegex (mkRegex "(.*)/(.*)/(.*)") d + +getDateDay' :: Maybe [String] -> Day +getDateDay' d + | isJust d == True = fromGregorian (read year) (read month) (read day) + | otherwise = fromGregorian 2015 1 1 + where Just [day, month, year] = d + +getDateDay :: String -> Day +getDateDay = getDateDay' . parseDate + +getDateUTC :: String -> String +getDateUTC d = show $ DT.UTCTime (getDateDay d) (DT.timeOfDayToTime $ DT.TimeOfDay 0 0 0) + +getYear :: String -> String +getYear date = s where + (y, m, d) = getDate date + s = show y + +getMonth :: String -> String +getMonth date = s where + (y, m, d) = getDate date + s = show m + +getDay :: String -> String +getDay date = s where + (y, m, d) = getDate date + s = show d + +--for Dates exported via xls2csv tool +type MT = Maybe (DU.Local DU.DateTime) +type MS = Maybe String + +--getDate'' :: String -> String +--getDate'' gd = d where +-- start = "1900-01-01T00:00:00Z" +-- da = (DU.parseRfc3339 start :: MT) >>= DU.addDays ( (read gd :: Integer) -2) >>= DU.renderRfc3339 :: MS +-- d = fromJust da +-- +--getDate''' :: String -> String +--getDate''' gd = d where +-- start = "1900-01-01T00:00:00Z" +-- da = (DU.parseRfc3339 start :: MT) >>= DU.addDays ( (read gd :: Integer) -2) >>= DU.renderIso8601CalendarDate :: MS +-- d = fromJust da +-- +--date2greg :: String -> +date2greg date = (y, m, d) where + (y, m, d) = DT.toGregorian $ DT.addDays ((read date :: Integer) -2) $ DT.utctDay (read "1900-01-01 00:00:00" :: DT.UTCTime) + + +getYear' :: String -> String +getYear' date = s where + (y, m, d) = date2greg date + s = show y + + +getMonth' :: String -> String +getMonth' date = s where + (y, m, d) = date2greg date + s = show m + + +getDay' :: String -> String +getDay' date = s where + (y, m, d) = date2greg date + s = show d + + + diff --git a/src/Data/Gargantext/Utils/Count.hs b/src/Data/Gargantext/Utils/Count.hs new file mode 100644 index 00000000..8ef04876 --- /dev/null +++ b/src/Data/Gargantext/Utils/Count.hs @@ -0,0 +1,72 @@ +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE ExistentialQuantification #-} +{-# LANGUAGE BangPatterns #-} +{-# LANGUAGE RankNTypes #-} + +module Data.Gargantext.Utils.Count (head, last, all, any, sum, product, length) + where + +import Data.Monoid +import Protolude hiding ((<>), head, last, all, any, sum, product, length) + +import qualified Data.Foldable +import Control.Lens (Getting, foldMapOf) + +data Fold i o = forall m . Monoid m => Fold (i -> m) (m -> o) + +instance Functor (Fold i) where + fmap k (Fold tally summarize) = Fold tally (k . summarize) + +instance Applicative (Fold i) where + pure o = Fold (\_ -> ()) (\_ -> o) + + Fold tallyF summarizeF <*> Fold tallyX summarizeX = Fold tally summarize + where + tally i = (tallyF i, tallyX i) + summarize (nF, nX) = summarizeF nF (summarizeX nX) + +focus :: (forall m . Monoid m => Getting m b a) -> Fold a o -> Fold b o +focus lens (Fold tally summarize) = Fold (foldMapOf lens tally) summarize + + +fold :: Fold i o -> [i] -> o +fold (Fold tally summarize) is = summarize (reduce (map tally is)) + where + reduce = Data.Foldable.foldl' (<>) mempty + +-- +head :: Fold a (Maybe a) +head = Fold (First . Just) getFirst + +last :: Fold a (Maybe a) +last = Fold (Last . Just) getLast +-- +all :: (a -> Bool) -> Fold a Bool +all predicate = Fold (All . predicate) getAll + +any :: (a -> Bool) -> Fold a Bool +any predicate = Fold (Any . predicate) getAny +-- +sum :: Num n => Fold n n +sum = Fold Sum getSum + +product :: Num n => Fold n n +product = Fold Product getProduct + +length :: Num n => Fold i n +length = Fold (\_ -> Sum 1) getSum + + +-- | Average function optimized (/!\ need to test it) +data Average a = Average { numerator :: !a, denominator :: !Int } + +instance Num a => Monoid (Average a) where + mempty = Average 0 0 + mappend (Average xL nL) (Average xR nR) = Average (xL + xR) (nL + nR) + +average :: Fractional a => Fold a a +average = Fold tally summarize + where + tally x = Average x 1 + summarize (Average numerator denominator) = + numerator / fromIntegral denominator diff --git a/src/Data/Gargantext/Utils/DateUtils.hs b/src/Data/Gargantext/Utils/DateUtils.hs new file mode 100644 index 00000000..bb5e40da --- /dev/null +++ b/src/Data/Gargantext/Utils/DateUtils.hs @@ -0,0 +1,32 @@ +module Data.Gargantext.Utils.DateUtils where + +import Data.Time +--import Data.Dates + +-- +--readInt :: IO [Char] -> IO Int +--readInt = readLn +-- +--readBool :: IO [Char] -> IO Bool +--readBool = readLn + +utc2gregorian :: UTCTime -> (Integer, Int, Int) +utc2gregorian date = toGregorian $ utctDay date + +gregorian2year :: (Integer, Int, Int) -> Integer +gregorian2year (y, m, d) = y + +utc2year :: UTCTime -> Integer +utc2year date = gregorian2year $ utc2gregorian date + +averageLength :: Fractional a => [[a1]] -> a +averageLength l = fromIntegral (sum (map length l)) / fromIntegral (length l) + +--main :: IO () +--main = do +-- c <- getCurrentTime +-- print c -- $ toYear $ toGregorian $ utctDay c + +charToString :: Char -> String +charToString = (:[]) + diff --git a/src/Data/Gargantext/Utils/LangDetect.hs b/src/Data/Gargantext/Utils/LangDetect.hs new file mode 100644 index 00000000..37141a40 --- /dev/null +++ b/src/Data/Gargantext/Utils/LangDetect.hs @@ -0,0 +1,93 @@ + + +-- DEFINITIONS as SPECS +-- (Engineering axioms for Gargantext) + + +------------------------------------------------------------------------ +-- From file to corpus +------------------------------------------------------------------------ + +-- > A Corpus is a list of Documents +data Corpus = [Document] + +-- > A Document should have a date, some text and a maybe a language. +-- > Remarks : +-- > If no date then force one ? +-- > Analyze either text or numbers +-- > only one language per document +data Document = Document { date :: UTCTime + , uce :: Map Text $ Either (Maybe Text) (Maybe Double) + , lang :: Maybe Language + } + +parseFiles :: Maybe ParserType -> [File] -> Corpus +parseFiles = undefined + +-- This function exists already (in Python) +parseFile' :: ParserType -> File -> Maybe [Document] +parseFile' = undefined + +-- This function does not exist yet +parseFile :: Maybe ParserType -> File -> Maybe [Document] +parseFile parserType file = documents + where + documents = case parserType of + + Nothing -> case guessParserType file of + Nothing -> askUser "Answer to the question with link to $doc" + Just parserType' -> parseFile (Just parserType') file + + Just parserType'' -> case parserType'' of + UnsupportedYet -> askUser "Not supported yet, which priority ?" + otherwise -> parseFile' parserType'' file + +data ParserType = RIS | ISI | XML | CSV | Europresse | Book | UnsupportedYet +guessParserType :: File -> Maybe ParserType +guessParserType = undefined + + +------------------------------------------------------------------------ +-- What kind of interactions with our users ? +------------------------------------------------------------------------ + +-- Question is Text only +type Question = Text + +-- Possible Answers: +data Answer = ClosedAnswer | NumAnswer | OpenAnswer +-- Definitions of the Answers +type ClosedAnswer = Bool +type OpenAnswer = Text +type NumAnswer = Int +-- Un formulaire est un mapping entre question et peut-être une réponse +-- Un formulaire vide a Nothing au champs (Maybe Answer) +-- Une question répondue a la valeur (Just Response) +type Formular = Map Question (Maybe Answer) + +askUser :: Question -> ClosedAnswer +askUser = undefined + +data Advice = BugReport | WishList +askUser' :: Question -> Advice +askUser' question = case askUser question of + True -> BugReport + False -> WishList + + +------------------------------------------------------------------------ +-- Specs for Lang Detection +------------------------------------------------------------------------ +data Language = English | French + +tagDoc :: Document -> Ngrams +tagDoc doc = ngrams + where + ngrams = case lang doc of + Nothing -> case guessLang doc of + Nothing -> tag + + +------------------------------------------------------------------------ +-- Specs for ngrams Worflow +------------------------------------------------------------------------ diff --git a/src/Data/Gargantext/Utils/Prefix.hs b/src/Data/Gargantext/Utils/Prefix.hs new file mode 100644 index 00000000..7bbef68c --- /dev/null +++ b/src/Data/Gargantext/Utils/Prefix.hs @@ -0,0 +1,48 @@ +module Data.Gargantext.Utils.Prefix where + + +import Control.Monad as X (mzero) +import Data.Aeson as X +import Data.Aeson.TH as X +import Data.Aeson.Types as X +import Data.Char as X (toLower) +-- import Data.Decimal as X +import Data.Maybe as X (catMaybes) +import Data.Monoid as X ((<>)) +-- import Data.Scientific as X +import Data.String as X (IsString (..), fromString) +import Data.Text as X (Text, unpack, pack) +import Data.Text.Encoding as X +import Text.Read (readMaybe) + + +-- | Aeson Options that remove the prefix from fields +unPrefix :: String -> Options +unPrefix prefix = defaultOptions + { fieldLabelModifier = unCapitalize . dropPrefix prefix + , omitNothingFields = True + } + +-- | Lower case leading character +unCapitalize :: String -> String +unCapitalize [] = [] +unCapitalize (c:cs) = toLower c : cs + +-- | Remove given prefix +dropPrefix :: String -> String -> String +dropPrefix prefix input = go prefix input + where + go pre [] = error $ contextual $ "prefix leftover: " <> pre + go [] (c:cs) = c : cs + go (p:preRest) (c:cRest) + | p == c = go preRest cRest + | otherwise = error $ contextual $ "not equal: " <> (p:preRest) <> " " <> (c:cRest) + + contextual msg = "dropPrefix: " <> msg <> ". " <> prefix <> " " <> input + +parseJSONFromString :: (Read a) => Value -> Parser a +parseJSONFromString v = do + numString <- parseJSON v + case readMaybe (numString :: String) of + Nothing -> fail $ "Invalid number for TransactionID: " ++ show v + Just n -> return n diff --git a/src/Data/Gargantext/Utils/SaveGetHash.hs b/src/Data/Gargantext/Utils/SaveGetHash.hs new file mode 100644 index 00000000..7cc13a24 --- /dev/null +++ b/src/Data/Gargantext/Utils/SaveGetHash.hs @@ -0,0 +1,91 @@ + +module Data.Gargantext.Utils.SaveGetHash where + +import System.FilePath (addExtension, joinPath) +import Data.ByteString.Lazy.Internal (ByteString) +import Data.List (elem, intersperse, insert) +import Data.List.Extra (chunksOf) +import Data.Digest.Pure.MD5 (md5) +import System.Directory (getDirectoryContents, createDirectory, findFile, createDirectoryIfMissing) +import Control.Monad (foldM) + +import Data.List (splitAt) +import Data.ByteString.Lazy.Internal (packChars) +import qualified Data.ByteString.Lazy as BL + +import Codec.Compression.Zlib (compress, decompress) + +data Config = Config { + root :: String + , chunkSize :: Int + , compression :: Bool + } deriving Show + +conf = Config { + root="/tmp/robot" + , chunkSize=2 + , compression = True + } + +chunkUrl :: Int -> ByteString -> [[Char]] +chunkUrl a url = chunksOf a $ show $ md5 url + +-- replace it with createDirectoryIfMissing +existOrCreate :: [[Char]] -> FilePath -> IO [[Char]] +existOrCreate path_ dir = do + let path = joinPath path_ + let returnPath = return $ path_ ++ [dir] + + is <- elem dir <$> getDirectoryContents path -- ? + case is of + True -> do + returnPath + False -> do + createDirectory $ path ++ "/" ++ dir + returnPath + +doPath :: [[Char]] -> [FilePath] -> IO [[Char]] +doPath root path = foldM (\x y -> existOrCreate x y) root path + + +splitAt' :: Int -> Int -> [Char] -> ([Char], [Char], [Char]) +splitAt' i1 i2 x = (a, b, c) where + (a, a') = splitAt i1 x + (b, c) = splitAt i2 a' + + +-- ne pas écraser le fichier s'il existe +-- spliter l'url proprement +saveFile :: ByteString -> String -> IO String +saveFile url'' file = do + let url' = chunkUrl (chunkSize conf) url'' + let url = init url' + + -- add extension according to the filetype + let filename = Prelude.foldl addExtension (last url') ["html", "zlib"] + + doPath [(root conf)] url + + let path = (root conf) ++ "/" ++ joinPath url ++ "/" ++ filename + + --case (findFile ["/tmp/sdfs"] "file.hmtl.zib" + -- Nothing -> create + -- _ -> change name + case (compression conf) of + True -> BL.writeFile path (compress $ packChars file) + False -> writeFile path file + return path + + +getFile :: FilePath -> IO ByteString +getFile path = do + case (compression conf) of + True -> decompress <$> BL.readFile path + False -> packChars <$> Prelude.readFile path + + +-- resources +-- add Resource + + +-- levensthein distance... diff --git a/stack.yaml b/stack.yaml new file mode 100644 index 00000000..7766e48d --- /dev/null +++ b/stack.yaml @@ -0,0 +1,10 @@ +flags: {} +extra-package-dbs: [] +packages: +- '.' +extra-deps: +- servant-0.11 +- servant-multipart-0.10.0.1 +- servant-server-0.11 + #- utc-0.2.0.1 +resolver: lts-8.21 diff --git a/test/Parsers.hs b/test/Parsers.hs new file mode 100644 index 00000000..ee438475 --- /dev/null +++ b/test/Parsers.hs @@ -0,0 +1,54 @@ +{-# LANGUAGE OverloadedStrings #-} + +import Test.Hspec +import Test.QuickCheck +import Control.Exception (evaluate) + + +import Data.Text (Text) +import Data.Gargantext.Parsers.Occurrences (parseOccurrences) +-- import Data.Gargantext.Analysis (occOfCorpus) + + + +parsersTest = hspec $ do + describe "Parser for occurrences" $ do + + let txt = "internet" + + it "returns the result of one parsing" $ do + parseOccurrences "internet" "internet" `shouldBe` Right 1 + + -- | Context of Text should be toLower + it "returns the result of one parsing not case sensitive" $ do + let txtCase = "Internet" + parseOccurrences txtCase "internet" `shouldBe` Right 1 + + it "returns the result of one parsing after space" $ do + parseOccurrences txt " internet" + `shouldBe` Right 1 + + it "returns the result of one parsing after chars" $ do + parseOccurrences txt "l'internet" + `shouldBe` Right 1 + + it "returns the result of multiple parsing" $ do + parseOccurrences txt "internet internet of things" + `shouldBe` Right 2 + + it "returns the result of multiple parsing separated by text" $ do + parseOccurrences txt "internet in the internet of things" + `shouldBe` Right 2 + + it "returns the result of multiple parsing separated by punctuation" $ do + parseOccurrences txt "internet. In the internet of things, internet like; internet?" + `shouldBe` Right 4 + +-- describe "Parser for nodes" $ do +-- it "returns the result of one parsing after space" $ do +-- occOfCorpus 249509 "sciences" `shouldReturn` 7 + +main :: IO () +main = do + parsersTest + diff --git a/test/Spec.hs b/test/Spec.hs new file mode 100644 index 00000000..7fe5fd79 --- /dev/null +++ b/test/Spec.hs @@ -0,0 +1,47 @@ +{-# LANGUAGE OverloadedStrings #-} + +import Test.Hspec +import Test.QuickCheck +import Control.Exception (evaluate) + + +import Data.Text (Text) +import Data.Hastext.Parsers.Occurrences (parse) + +main = print "hspec $ do + describe "Parser for occurrences" $ do + + let txt = "internet" + + it "returns the result of one parsing" $ do + parse "internet" "internet" `shouldBe` Right ((txt, 1) :: (Text, Int)) + + -- | Context of Text should be toLower + it "returns the result of one parsing not case sensitive" $ do + let txtCase = "Internet" + parse txtCase "internet" `shouldBe` Right ((txtCase, 1) :: (Text, Int)) + + it "returns the result of one parsing after space" $ do + parse txt " internet" + `shouldBe` Right ((txt, 1) :: (Text, Int)) + + it "returns the result of one parsing after chars" $ do + parse txt "l'internet" + `shouldBe` (Right ((txt, 1) :: (Text, Int))) + + it "returns the result of multiple parsing" $ do + parse txt "internet internet of things" + `shouldBe` (Right ((txt, 2) :: (Text, Int))) + + it "returns the result of multiple parsing separated by text" $ do + parse txt "internet in the internet of things" + `shouldBe` (Right ((txt, 2) :: (Text, Int))) + + it "returns the result of multiple parsing separated by punctuation" $ do + parse txt "internet. In the internet of things, internet like; internet?" + `shouldBe` (Right ((txt, 4) :: (Text, Int))) + + + +main :: IO () + -- 2.44.1