pax_global_header00006660000000000000000000000064142044512570014516gustar00rootroot0000000000000052 comment=f8240ab9d4e7a00a0ba65f4088106be969ac800f govarnam-1.9.0/000077500000000000000000000000001420445125700133375ustar00rootroot00000000000000govarnam-1.9.0/.github/000077500000000000000000000000001420445125700146775ustar00rootroot00000000000000govarnam-1.9.0/.github/workflows/000077500000000000000000000000001420445125700167345ustar00rootroot00000000000000govarnam-1.9.0/.github/workflows/go.yml000066400000000000000000000020521420445125700200630ustar00rootroot00000000000000name: Go on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-18.04 env: VARNAM_UPSTREAM: https://varnam.subinsb.com steps: - name: Checkout uses: actions/checkout@v2 with: submodules: recursive - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16 - name: Build run: make - name: Set env run: echo "VARNAM_VST_DIR=$(echo $(realpath schemes))" >> $GITHUB_ENV - name: Download schemes run: | mkdir schemes wget -O $VARNAM_VST_DIR/ml.vst "$VARNAM_UPSTREAM/languages/ml/download" wget -O $VARNAM_VST_DIR/ml-inscript.vst "$VARNAM_UPSTREAM/languages/ml-inscript/download" - name: Test run: make test - name: Make Zip run: | make make release - name: Archive production artifacts uses: actions/upload-artifact@v2 with: name: govarnam path: "*.zip" govarnam-1.9.0/.github/workflows/release.yml000066400000000000000000000013511420445125700210770ustar00rootroot00000000000000name: Publish on: push: tags: - '*' jobs: publish: name: Publish for ${{ matrix.os }} ${{ matrix.arch }} runs-on: ${{ matrix.os }} strategy: matrix: include: - os: ubuntu-18.04 file: "*.zip" steps: - uses: actions/checkout@v2 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16 - name: Build run: | make make release - name: Upload Release Binary uses: svenstaro/upload-release-action@v2 with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: ${{ matrix.file }} file_glob: true tag: ${{ github.ref }} overwrite: true govarnam-1.9.0/.gitignore000066400000000000000000000000761420445125700153320ustar00rootroot00000000000000libgovarnam.* varnam varnamcli install.sh govarnam.pc *.vst govarnam-1.9.0/.gitmodules000066400000000000000000000001321420445125700155100ustar00rootroot00000000000000[submodule "schemes"] path = schemes url = https://github.com/varnamproject/schemes.git govarnam-1.9.0/LICENSE.txt000066400000000000000000001025511420445125700151660ustar00rootroot00000000000000GNU 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 . govarnam-1.9.0/Makefile000066400000000000000000000053251420445125700150040ustar00rootroot00000000000000.DEFAULT_GOAL := build .PHONY:default default: build ; CLI_BIN := varnamcli INSTALL_PREFIX := $(or ${PREFIX},${PREFIX},/usr/local) # Try to get the commit hash from git LAST_COMMIT := $(or $(shell git rev-parse --short HEAD 2> /dev/null),"UNKNOWN") VERSION := $(or $(shell echo $$(git describe --abbrev=0 --tags || echo "latest") | sed s/v//),"v0.0.0") BUILDSTR := ${VERSION} (\#${LAST_COMMIT} $(shell date -u +"%Y-%m-%dT%H:%M:%S%z")) RELEASE_NAME := govarnam-${VERSION}-${shell uname -m} UNAME := $(shell uname) SED := sed -i LIB_NAME := libgovarnam.so ifeq ($(UNAME), Darwin) SED := sed -i "" LIB_NAME = libgovarnam.dylib endif VERSION_STAMP_LDFLAGS := -X 'github.com/varnamproject/govarnam/govarnam.BuildString=${BUILDSTR}' -X 'github.com/varnamproject/govarnam/govarnam.VersionString=${VERSION}' pc: cp govarnam.pc.in govarnam.pc ${SED} "s#@INSTALL_PREFIX@#${INSTALL_PREFIX}#g" govarnam.pc ${SED} "s#@VERSION@#${VERSION}#g" govarnam.pc # Used only for building the CLI temp-pc: cp govarnam.pc.in govarnam.pc ${SED} "s#@INSTALL_PREFIX@#$(realpath .)#g" govarnam.pc ${SED} "s#@VERSION@#${VERSION}#g" govarnam.pc ${SED} "s#/include/libgovarnam##g" govarnam.pc ${SED} "s#/lib##g" govarnam.pc install-script: cp install.sh.in install.sh ${SED} "s#@INSTALL_PREFIX@#${INSTALL_PREFIX}#g" install.sh ${SED} "s#@VERSION@#${VERSION}#g" install.sh ${SED} "s#@LIB_NAME@#${LIB_NAME}#g" install.sh chmod +x install.sh install: ./install.sh install .PHONY: cli cli: go build -o ${CLI_BIN} -ldflags "-s -w" ./cli library-nosqlite: CGO_ENABLED=1 go build -tags "fts5,libsqlite3" -buildmode=c-shared -ldflags "-s -w ${VERSION_STAMP_LDFLAGS}" -o ${LIB_NAME} . library: CGO_ENABLED=1 go build -tags "fts5" -buildmode=c-shared -ldflags "-s -w ${VERSION_STAMP_LDFLAGS}" -o ${LIB_NAME} . library-mac-universal: GOOS=darwin GOARCH=arm64 $(MAKE) library mv ${LIB_NAME} ${LIB_NAME}.arm64 GOOS=darwin GOARCH=amd64 $(MAKE) library mv ${LIB_NAME} ${LIB_NAME}.amd64 lipo -create -output ${LIB_NAME} ${LIB_NAME}.arm64 ${LIB_NAME}.amd64 .PHONY: nix nix: $(MAKE) library $(MAKE) temp-pc PKG_CONFIG_PATH=$(realpath .):$$PKG_CONFIG_PATH $(MAKE) cli $(MAKE) pc $(MAKE) install-script .PHONY: build: $(MAKE) nix release: echo "Hope you have updated version in constants.go" mkdir -p ${RELEASE_NAME} cp ${CLI_BIN} ${RELEASE_NAME}/ cp libgovarnam.so ${RELEASE_NAME}/ cp *.h ${RELEASE_NAME}/ cp *.pc ${RELEASE_NAME}/ cp install.sh ${RELEASE_NAME}/ zip -r ${RELEASE_NAME}.zip ${RELEASE_NAME}/* test-govarnamgo: $(MAKE) temp-pc PKG_CONFIG_PATH=$(realpath .):$$PKG_CONFIG_PATH LD_LIBRARY_PATH=$(realpath .):$$LD_LIBRARY_PATH govarnamgo/run_tests.sh test: go test -tags fts5 -count=1 -cover govarnam/*.go $(MAKE) library $(MAKE) test-govarnamgo govarnam-1.9.0/README.md000066400000000000000000000122221420445125700146150ustar00rootroot00000000000000# Varnam Varnam is an Indian language transliteration library. GoVarnam is a brand new Go port of [libvarnam](https://github.com/varnamproject/libvarnam) with some core architectural changes. It is stable to use daily as an input method. Try out different languages here: https://varnamproject.github.io/editor/ Malayalam has really good support in Varnam. We welcome improvements of all languages in Varnam. * An [Input Method Engine](https://en.wikipedia.org/wiki/Input_method) for GNU/Linux operating systems via IBus is available here: https://github.com/varnamproject/govarnam-ibus * For macOS, there is a [Varnam IME too](https://github.com/varnamproject/varnam-macOS). * Windows: Need Help ## Installation & Usage See instructions in website: https://varnamproject.github.io/download/ FAQ: https://varnamproject.github.io/docs/faq/
![](https://varnamproject.github.io/_index/free-to-write-anything.png) ## Development Proceed through these sections one by one: ### Videos See this video to understand more about Varnam (DebConf21): * PeerTube: https://peertube.debian.social/w/vWwMGcmTZG9n1UWv8ZdimB?s=1 * YouTube: https://www.youtube.com/watch?v=pJpOWlD_7OI ### Files & Folders * `govarnam` - The library files * `main.go, c-shared*` - Files that help in making the govarnam a C shared library * `govarnamgo` - Go bindings for the library. For use with other Go projects * `cli` - A CLI tool written in Go for Varnam. Uses `govarnamgo` to interface with the library. ### Build Library Requires minimum Go version 1.16. This repository have 3 things : 1. GoVarnam library 2. GoVarnam Command Line Utility (CLI) 3. Go bindings for GoVarnam GoVarnam is written in Go, but to be a standard library that can be used with any other programming languages, we compile it to a C library. This is done by : ```bash go build -buildmode "c-shared" -o libgovarnam.so ``` (Shortcut to doing above is `make library`) The output `libgovarnam.so` is a shared library that can be dynamically linked in any other programming languages using its header file `libgovarnam.h`. Some examples : * Go bindings for GoVarnam: See govarnam**go** folder in this repo * Java bindings for GoVarnam: https://github.com/varnamproject/govarnam-java/ Wait, it means we need to write another Go file to interface with GoVarnam library ! This is because we're interfacing with a C shared library and not the Go library directly. The `govarnamgo` acts as this interface for Go apps to use GoVarnam. ### CLI (Command Line Utility) After making `libgovarnam.so` you can make the CLI to use GoVarnam : ``` make cli ``` The command line utility (CLI) is written in Go, uses govarnamgo to interface with the library. You can build both library and CLI with just `make`. ### Language Support Varnam uses a `.vst` (Varnam Symbol Table) file for language support. You can get it from it from `schemes` folder in [a release](https://github.com/varnamproject/schemes/releases). Place VST files in **one of these** locations (from high priority to least priority locations): * `$PWD/schemes` (PWD is Present Working Directory) * `/usr/local/share/varnam/schemes` * `/usr/share/varnam/schemes` Now we can use `varnamcli`: ``` # Show linker the path to search for libgovarnam.so export LD_LIBRARY_PATH=$(realpath ./):$LD_LIBRARY_PATH ./varnamcli -s ml namaskaaram ``` The `ml` above is the scheme ID. It should match with the VST filename. You can link the library to `/usr/local/lib` to skip doing the `export LD_LIBRARY_PATH` every time: ``` sudo ln -s $PWD/libgovarnam.so /usr/local/lib/libgovarnam.so ``` Now any software can find the GoVarnam library. ### Testing You can run tests (to make sure nothing broke) with : ```bash make test ``` ### Use Varnam Live It's good to install an IME to test changes you make to the library live. * Linux IME: https://github.com/varnamproject/govarnam-ibus * Mac IME (Coming Soon...): https://github.com/varnamproject/govarnam/issues/8 * Windows IME (Coming Soon...): https://github.com/varnamproject/govarnam/issues/7 ### Changes from libvarnam * `ml.vst` has been changed to add a new `weight` column in `symbols` table. Get the new `ml.vst` here. The symbol with the least weight has more significance. This is calculated according to popularity from corpus. You can populate a `ml.vst` with weight values by a Python script. See that in the subfolder. The previous ruby script is used for making the VST. That is the same. **`ml.vst` from libvarnam is incompatible with govarnam**. * `patterns_content` is renamed to `patterns` in GoVarnam * `patterns` table in learnings DB won't store malayalam patterns. Instead, for each input, all possible malayalam words are calculated (from `symbols` VARNAM_MATCH_ALL) and searched in `words`. These are returned as suggestions. Previously, `pattern` would store every pattern to a word. english => malayalam. * `patterns` in govarnam is used solely for English words. `Computer => കമ്പ്യൂട്ടർ`. These English words won't work out with our VST tokenizer cause the words are not really transliterable in our language. It would be `kambyoottar => Computer` ### Release Process * Update version in `constants.go` * git tag * make build release govarnam-1.9.0/c-shared-general.go000066400000000000000000000005041420445125700167660ustar00rootroot00000000000000package main /* #include "c-shared.h" #include "c-shared-varray.h" #include "stdlib.h" */ import "C" //export varnam_reindex_dictionary func varnam_reindex_dictionary(varnamHandleID C.int) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.ReIndexDictionary() return checkError(handle.err) } govarnam-1.9.0/c-shared-util.c000066400000000000000000000000011420445125700161330ustar00rootroot00000000000000 govarnam-1.9.0/c-shared-util.h000066400000000000000000000006341420445125700161540ustar00rootroot00000000000000#ifndef __UTIL_H__ #define __UTIL_H__ #include #if defined (_WIN32) #if defined(varnam_EXPORTS) #define VARNAM_EXPORT __declspec(dllexport) #else #define VARNAM_EXPORT __declspec(dllimport) #endif /* varnam_EXPORTS */ #else /* defined (_WIN32) */ #define VARNAM_EXPORT #endif #ifndef __cplusplus typedef int bool; #define false 0 #define true 1 #endif #endif /* __UTIL_H__ */govarnam-1.9.0/c-shared-utils.go000066400000000000000000000022051420445125700165110ustar00rootroot00000000000000package main /* #include "c-shared.h" */ import "C" import "github.com/varnamproject/govarnam/govarnam" func cSymbolToGoSymbol(symbol C.struct_Symbol_t) govarnam.Symbol { var goSymbol govarnam.Symbol goSymbol.Identifier = int(symbol.Identifier) goSymbol.Type = int(symbol.Type) goSymbol.MatchType = int(symbol.MatchType) goSymbol.Pattern = C.GoString(symbol.Pattern) goSymbol.Value1 = C.GoString(symbol.Value1) goSymbol.Value2 = C.GoString(symbol.Value2) goSymbol.Value3 = C.GoString(symbol.Value3) goSymbol.Tag = C.GoString(symbol.Tag) goSymbol.Weight = int(symbol.Weight) goSymbol.Priority = int(symbol.Priority) goSymbol.AcceptCondition = int(symbol.AcceptCondition) goSymbol.Flags = int(symbol.Flags) return goSymbol } func goSymbolToCSymbol(symbol govarnam.Symbol) *C.struct_Symbol_t { return C.makeSymbol( C.int(symbol.Identifier), C.int(symbol.Type), C.int(symbol.MatchType), C.CString(symbol.Pattern), C.CString(symbol.Value1), C.CString(symbol.Value2), C.CString(symbol.Value3), C.CString(symbol.Tag), C.int(symbol.Weight), C.int(symbol.Priority), C.int(symbol.AcceptCondition), C.int(symbol.Flags), ) } govarnam-1.9.0/c-shared-varray.c000066400000000000000000000043441420445125700165000ustar00rootroot00000000000000/* Dynamically growing array implementation * * Copyright (C) Navaneeth.K.N * * This is part of libvarnam licensed under MPL-2.0 */ #include #include #include #include "c-shared-varray.h" #include "c-shared-util.h" varray* varray_init() { varray *array = (varray*) malloc (sizeof(varray)); array->memory = NULL; array->allocated = 0; array->used = 0; array->index = -1; return array; } void varray_push(varray *array, void *data) { size_t toallocate; size_t size = sizeof(void*); if (data == NULL) return; if ((array->allocated - array->used) < size) { toallocate = array->allocated == 0 ? size : (array->allocated * 2); array->memory = realloc(array->memory, toallocate); array->allocated = toallocate; } array->memory[++array->index] = data; array->used = array->used + size; } int varray_length(varray *array) { if (array == NULL) return 0; return array->index + 1; } bool varray_is_empty (varray *array) { return (varray_length (array) == 0); } void varray_clear(varray *array) { int i; for(i = 0; i < varray_length(array); i++) { array->memory[i] = NULL; } array->used = 0; array->index = -1; } void varray_free(varray *array, void (*destructor)(void*)) { int i; void *item; if (array == NULL) return; if (destructor != NULL) { for(i = 0; i < varray_length(array); i++) { item = varray_get (array, i); if (item != NULL) destructor(item); } } if (array->memory != NULL) free(array->memory); free(array); } void* varray_get(varray *array, int index) { if (index < 0 || index > array->index) return NULL; assert(array->memory); return array->memory[index]; } void varray_insert(varray *array, int index, void *data) { if (index < 0 || index > array->index) return; array->memory[index] = data; } bool varray_exists (varray *array, void *item, bool (*equals)(void *left, void *right)) { int i; for (i = 0; i < varray_length (array); i++) { if (equals(varray_get (array, i), item)) return true; } return false; } govarnam-1.9.0/c-shared-varray.h000066400000000000000000000015761420445125700165110ustar00rootroot00000000000000#ifndef __VARRAY_H__ #define __VARRAY_H__ #include "c-shared-util.h" /** * Array to hold pointers. This expands automatically. * **/ typedef struct varray_t { void **memory; size_t allocated; size_t used; int index; } varray; VARNAM_EXPORT extern varray* varray_init(); VARNAM_EXPORT extern void varray_push(varray *array, void *data); VARNAM_EXPORT extern int varray_length(varray *array); VARNAM_EXPORT extern bool varray_is_empty (varray *array); VARNAM_EXPORT extern bool varray_exists (varray *array, void *item, bool (*equals)(void *left, void *right)); VARNAM_EXPORT extern void varray_clear(varray *array); VARNAM_EXPORT extern void* varray_get(varray *array, int index); VARNAM_EXPORT extern void varray_insert(varray *array, int index, void *data); VARNAM_EXPORT extern void varray_free(varray *array, void (*destructor)(void*)); #endif /* VARRAY_H */govarnam-1.9.0/c-shared.c000066400000000000000000000073331420445125700151770ustar00rootroot00000000000000#include "c-shared.h" #include "stdio.h" #include "stdlib.h" #include "c-shared-varray.h" Suggestion* makeSuggestion(char* word, int weight, int learned_on) { Suggestion *sug = (Suggestion*) malloc (sizeof(Suggestion)); sug->Word = word; sug->Weight = weight; sug->LearnedOn = learned_on; return sug; } TransliterationResult* makeResult(varray* exact_words, varray* exact_matches, varray* dictionary_suggestions, varray* pattern_dictionary_suggestions, varray* tokenizer_suggestions, varray* greedy_tokenized) { TransliterationResult *result = (TransliterationResult*) malloc (sizeof(TransliterationResult)); result->ExactWords = exact_words; result->ExactMatches = exact_matches; result->DictionarySuggestions = dictionary_suggestions; result->PatternDictionarySuggestions = pattern_dictionary_suggestions; result->TokenizerSuggestions = tokenizer_suggestions; result->GreedyTokenized = greedy_tokenized; return result; } void destroySuggestions(void* pointer) { if (pointer != NULL) { Suggestion* sug = (Suggestion*) pointer; free(sug->Word); sug->Word = NULL; free(sug); sug = NULL; } } void destroySuggestionsArray(varray* pointer) { varray_free(pointer, &destroySuggestions); pointer = NULL; } void destroyTransliterationResult(TransliterationResult* result) { destroySuggestionsArray(result->ExactMatches); destroySuggestionsArray(result->DictionarySuggestions); destroySuggestionsArray(result->PatternDictionarySuggestions); destroySuggestionsArray(result->TokenizerSuggestions); destroySuggestionsArray(result->GreedyTokenized); result->ExactMatches = NULL; result->DictionarySuggestions = NULL; result->PatternDictionarySuggestions = NULL; result->TokenizerSuggestions = NULL; result->GreedyTokenized = NULL; free(result); result = NULL; } SchemeDetails* makeSchemeDetails(char* Identifier, char* LangCode, char* DisplayName, char* Author, char* CompiledDate, bool IsStable) { SchemeDetails* sd = (SchemeDetails*) malloc (sizeof(SchemeDetails)); sd->Identifier = Identifier; sd->LangCode = LangCode; sd->DisplayName = DisplayName; sd->Author = Author; sd->CompiledDate = CompiledDate; sd->IsStable = IsStable; return sd; } void destroySchemeDetails(void* pointer) { if (pointer != NULL) { Suggestion* sug = (Suggestion*) pointer; free(sug->Word); sug->Word = NULL; free(sug); sug = NULL; } } void destroySchemeDetailsArray(void* cSchemeDetails) { varray_free(cSchemeDetails, &destroySchemeDetails); } LearnStatus makeLearnStatus(int TotalWords, int FailedWords) { LearnStatus ls; ls.TotalWords = TotalWords; ls.FailedWords = FailedWords; return ls; } Symbol* makeSymbol(int Identifier, int Type, int MatchType, char* Pattern, char* Value1, char* Value2, char* Value3, char* Tag, int Weight, int Priority, int AcceptCondition, int Flags) { Symbol *symbol = (Symbol*) malloc (sizeof(Symbol)); symbol->Identifier = Identifier; symbol->Type = Type; symbol->MatchType = MatchType; symbol->Pattern = Pattern; symbol->Value1 = Value1; symbol->Value2 = Value2; symbol->Value3 = Value3; symbol->Tag = Tag; symbol->Weight = Weight; symbol->Priority = Priority; symbol->AcceptCondition = AcceptCondition; symbol->Flags = Flags; return symbol; } void destroySymbol(void* pointer) { if (pointer != NULL) { Symbol* symbol = (Symbol*) pointer; free(symbol->Pattern), free(symbol->Value1); free(symbol->Value2); free(symbol->Value3); free(symbol->Tag); symbol->Pattern = NULL; symbol->Value1 = NULL; symbol->Value2 = NULL; symbol->Value3 = NULL; symbol->Tag = NULL; free(symbol); symbol = NULL; } } void destroySymbolArray(void* cSymbols) { varray_free(cSymbols, &destroySymbol); } govarnam-1.9.0/c-shared.go000066400000000000000000000446111420445125700153620ustar00rootroot00000000000000package main /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ /* For c-shared library */ /* #include "c-shared.h" #include "c-shared-varray.h" #include "stdlib.h" */ import "C" import ( "context" "log" "sync" "unsafe" "github.com/varnamproject/govarnam/govarnam" ) var generalError error var backgroundContext = context.Background() var cancelFuncs = map[C.int]interface{}{} var cancelFuncsMapMutex = sync.RWMutex{} // Returns a C integer status code // In the C world, errors are indicated by return int status codes func checkError(err error) C.int { if err != nil { return C.VARNAM_ERROR } return C.VARNAM_SUCCESS } // In C, booleans are implemented with int 0 & int 1 func cintToBool(val C.int) bool { if val == C.int(1) { return true } return false } func makeContext(id C.int) (context.Context, func()) { ctx, cancel := context.WithCancel(backgroundContext) cancelFuncsMapMutex.Lock() cancelFuncs[id] = &cancel cancelFuncsMapMutex.Unlock() return ctx, cancel } func makeCTransliterationResult(ctx context.Context, goResult govarnam.TransliterationResult, resultPointer **C.struct_TransliterationResult_t) C.int { select { case <-ctx.Done(): return C.VARNAM_CANCELLED default: // Note that C.CString uses malloc() // They should be freed manually. GC won't pick it. // The freeing should be done by programs using govarnam cExactWords := C.varray_init() for _, sug := range goResult.ExactWords { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cExactWords, cSug) } cExactMatches := C.varray_init() for _, sug := range goResult.ExactMatches { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cExactMatches, cSug) } cDictionarySuggestions := C.varray_init() for _, sug := range goResult.DictionarySuggestions { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cDictionarySuggestions, cSug) } cPatternDictionarySuggestions := C.varray_init() for _, sug := range goResult.PatternDictionarySuggestions { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cPatternDictionarySuggestions, cSug) } cTokenizerSuggestions := C.varray_init() for _, sug := range goResult.TokenizerSuggestions { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cTokenizerSuggestions, cSug) } cGreedyTokenized := C.varray_init() for _, sug := range goResult.GreedyTokenized { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cGreedyTokenized, cSug) } *resultPointer = C.makeResult(cExactWords, cExactMatches, cDictionarySuggestions, cPatternDictionarySuggestions, cTokenizerSuggestions, cGreedyTokenized) return C.VARNAM_SUCCESS } } //export varnam_get_version func varnam_get_version() *C.char { return C.CString(govarnam.VersionString) } //export varnam_get_build func varnam_get_build() *C.char { return C.CString(govarnam.BuildString) } //export varnam_set_vst_lookup_dir func varnam_set_vst_lookup_dir(path *C.char) { govarnam.SetVSTLookupDir(C.GoString(path)) } type varnamHandle struct { varnam *govarnam.Varnam err error } // For storing varnam instances var varnamHandles = map[C.int]*varnamHandle{} var varnamHandlesMapMutex = sync.RWMutex{} //export varnam_init func varnam_init(vstFile *C.char, learningsFile *C.char, id unsafe.Pointer) C.int { handleID := C.int(len(varnamHandles)) *(*C.int)(id) = handleID varnamGo, err := govarnam.Init(C.GoString(vstFile), C.GoString(learningsFile)) varnamHandlesMapMutex.Lock() varnamHandles[handleID] = &varnamHandle{varnamGo, err} varnamHandlesMapMutex.Unlock() return checkError(err) } //export varnam_init_from_id func varnam_init_from_id(schemeID *C.char, id unsafe.Pointer) C.int { handleID := C.int(len(varnamHandles)) *(*C.int)(id) = handleID varnamGo, err := govarnam.InitFromID(C.GoString(schemeID)) varnamHandlesMapMutex.Lock() varnamHandles[handleID] = &varnamHandle{varnamGo, err} varnamHandlesMapMutex.Unlock() return checkError(err) } func getVarnamHandle(id C.int) *varnamHandle { varnamHandlesMapMutex.Lock() defer varnamHandlesMapMutex.Unlock() if handle, ok := varnamHandles[id]; ok { return handle } log.Fatal("Varnam handle not found") return &varnamHandle{} } //export varnam_close func varnam_close(varnamHandleID C.int) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Close() if handle.err != nil { return checkError(handle.err) } varnamHandlesMapMutex.Lock() delete(varnamHandles, varnamHandleID) varnamHandlesMapMutex.Unlock() return C.VARNAM_SUCCESS } //export varnam_transliterate func varnam_transliterate(varnamHandleID C.int, id C.int, word *C.char, resultPointer **C.varray) C.int { ctx, cancel := makeContext(id) defer cancel() channel := make(chan []govarnam.Suggestion) go getVarnamHandle(varnamHandleID).varnam.TransliterateWithContext(ctx, C.GoString(word), channel) select { case <-ctx.Done(): return C.VARNAM_CANCELLED case result := <-channel: // Note that C.CString uses malloc() // They should be freed manually. GC won't pick it. // The freeing should be done by programs using govarnam cResult := C.varray_init() for _, sug := range result { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cResult, cSug) } *resultPointer = cResult return C.VARNAM_SUCCESS } } //export varnam_transliterate_advanced func varnam_transliterate_advanced(varnamHandleID C.int, id C.int, word *C.char, resultPointer **C.struct_TransliterationResult_t) C.int { ctx, cancel := makeContext(id) defer cancel() channel := make(chan govarnam.TransliterationResult) go getVarnamHandle(varnamHandleID).varnam.TransliterateAdvancedWithContext(ctx, C.GoString(word), channel) select { case <-ctx.Done(): return C.VARNAM_CANCELLED case result := <-channel: return makeCTransliterationResult(ctx, result, resultPointer) } } //export varnam_transliterate_greedy_tokenized func varnam_transliterate_greedy_tokenized(varnamHandleID C.int, word *C.char, resultPointer **C.varray) C.int { handle := getVarnamHandle(varnamHandleID) result := handle.varnam.TransliterateGreedyTokenized(C.GoString(word)) ptr := C.varray_init() for _, sug := range result { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(ptr, cSug) } *resultPointer = ptr return C.VARNAM_SUCCESS } //export varnam_reverse_transliterate func varnam_reverse_transliterate(varnamHandleID C.int, word *C.char, resultPointer **C.varray) C.int { handle := getVarnamHandle(varnamHandleID) sugs, err := handle.varnam.ReverseTransliterate(C.GoString(word)) if err != nil { handle.err = err return C.VARNAM_ERROR } cResult := C.varray_init() for _, sug := range sugs { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(cResult, cSug) } *resultPointer = cResult return C.VARNAM_SUCCESS } //export varnam_debug func varnam_debug(varnamHandleID C.int, val C.int) { getVarnamHandle(varnamHandleID).varnam.Debug = cintToBool(val) } // Deprecated. Use varnam_config() //export varnam_set_indic_digits func varnam_set_indic_digits(varnamHandleID C.int, val C.int) { varnam_config(varnamHandleID, C.VARNAM_CONFIG_USE_INDIC_DIGITS, val) } // Deprecated. Use varnam_config() //export varnam_set_dictionary_suggestions_limit func varnam_set_dictionary_suggestions_limit(varnamHandleID C.int, val C.int) { getVarnamHandle(varnamHandleID).varnam.DictionarySuggestionsLimit = int(val) } // Deprecated. Use varnam_config() //export varnam_set_pattern_dictionary_suggestions_limit func varnam_set_pattern_dictionary_suggestions_limit(varnamHandleID C.int, val C.int) { getVarnamHandle(varnamHandleID).varnam.PatternDictionarySuggestionsLimit = int(val) } // Deprecated. Use varnam_config() //export varnam_set_tokenizer_suggestions_limit func varnam_set_tokenizer_suggestions_limit(varnamHandleID C.int, val C.int) { getVarnamHandle(varnamHandleID).varnam.TokenizerSuggestionsLimit = int(val) } // Deprecated. Use varnam_config() //export varnam_set_dictionary_match_exact func varnam_set_dictionary_match_exact(varnamHandleID C.int, val C.int) { if val == 0 { getVarnamHandle(varnamHandleID).varnam.DictionaryMatchExact = false } else { getVarnamHandle(varnamHandleID).varnam.DictionaryMatchExact = true } } //export varnam_learn func varnam_learn(varnamHandleID C.int, word *C.char, weight C.int) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Learn(C.GoString(word), int(weight)) return checkError(handle.err) } //export varnam_train func varnam_train(varnamHandleID C.int, pattern *C.char, word *C.char) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Train(C.GoString(pattern), C.GoString(word)) return checkError(handle.err) } //export varnam_unlearn func varnam_unlearn(varnamHandleID C.int, word *C.char) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Unlearn(C.GoString(word)) return checkError(handle.err) } //export varnam_learn_from_file func varnam_learn_from_file(varnamHandleID C.int, filePath *C.char, resultPointer **C.struct_LearnStatus_t) C.int { handle := getVarnamHandle(varnamHandleID) learnStatus, err := handle.varnam.LearnFromFile(C.GoString(filePath)) if err != nil { handle.err = err return C.VARNAM_ERROR } result := C.makeLearnStatus(C.int(learnStatus.TotalWords), C.int(learnStatus.FailedWords)) *resultPointer = &result return C.VARNAM_SUCCESS } //export varnam_train_from_file func varnam_train_from_file(varnamHandleID C.int, filePath *C.char, resultPointer **C.struct_LearnStatus_t) C.int { handle := getVarnamHandle(varnamHandleID) learnStatus, err := handle.varnam.TrainFromFile(C.GoString(filePath)) if err != nil { handle.err = err return C.VARNAM_ERROR } result := C.makeLearnStatus(C.int(learnStatus.TotalWords), C.int(learnStatus.FailedWords)) *resultPointer = &result return C.VARNAM_SUCCESS } //export varnam_get_last_error func varnam_get_last_error(varnamHandleID C.int) *C.char { var err error if varnamHandleID == -1 { err = generalError } else { err = getVarnamHandle(varnamHandleID).err } if err != nil { return C.CString(err.Error()) } else { return C.CString("") } } //export varnam_cancel func varnam_cancel(id C.int) C.int { cancelFuncsMapMutex.Lock() cancelFunc, ok := cancelFuncs[id] defer cancelFuncsMapMutex.Unlock() if ok { (*cancelFunc.(*context.CancelFunc))() delete(cancelFuncs, id) return C.VARNAM_SUCCESS } return C.VARNAM_ERROR } //export varnam_export func varnam_export(varnamHandleID C.int, filePath *C.char, wordsPerFile C.int) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Export(C.GoString(filePath), int(wordsPerFile)) return checkError(handle.err) } //export varnam_import func varnam_import(varnamHandleID C.int, filePath *C.char) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.Import(C.GoString(filePath)) return checkError(handle.err) } //export varnam_get_vst_path func varnam_get_vst_path(varnamHandleID C.int) *C.char { handle := getVarnamHandle(varnamHandleID) return C.CString(handle.varnam.VSTPath) } //export varnam_new_search_symbol func varnam_new_search_symbol(resultPointer **C.struct_Symbol_t) C.int { symbol := govarnam.NewSearchSymbol() *resultPointer = C.makeSymbol( C.int(symbol.Identifier), C.int(symbol.Type), C.int(symbol.MatchType), C.CString(symbol.Pattern), C.CString(symbol.Value1), C.CString(symbol.Value2), C.CString(symbol.Value3), C.CString(symbol.Tag), C.int(symbol.Weight), C.int(symbol.Priority), C.int(symbol.AcceptCondition), C.int(symbol.Flags), ) return C.VARNAM_SUCCESS } //export varnam_search_symbol_table func varnam_search_symbol_table(varnamHandleID C.int, id C.int, searchCriteria C.struct_Symbol_t, resultPointer **C.varray) C.int { ctx, cancel := makeContext(id) defer cancel() handle := getVarnamHandle(varnamHandleID) goSearchCriteria := cSymbolToGoSymbol(searchCriteria) var results []govarnam.Symbol select { case <-ctx.Done(): return C.VARNAM_CANCELLED default: results, handle.err = handle.varnam.SearchSymbolTable(ctx, goSearchCriteria) cResult := C.varray_init() for _, symbol := range results { cSymbol := unsafe.Pointer(goSymbolToCSymbol(symbol)) C.varray_push(cResult, cSymbol) } *resultPointer = cResult return C.VARNAM_SUCCESS } } //export varnam_get_recently_learned_words func varnam_get_recently_learned_words(varnamHandleID C.int, id C.int, offset C.int, limit C.int, resultPointer **C.varray) C.int { ctx, cancel := makeContext(id) defer cancel() handle := getVarnamHandle(varnamHandleID) result, err := handle.varnam.GetRecentlyLearntWords(ctx, int(offset), int(limit)) if err != nil { handle.err = err return C.VARNAM_ERROR } ptr := C.varray_init() for _, sug := range result { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(ptr, cSug) } *resultPointer = ptr return C.VARNAM_SUCCESS } //export varnam_get_suggestions func varnam_get_suggestions(varnamHandleID C.int, id C.int, word *C.char, resultPointer **C.varray) C.int { ctx, cancel := makeContext(id) defer cancel() handle := getVarnamHandle(varnamHandleID) result := handle.varnam.GetSuggestions(ctx, C.GoString(word)) ptr := C.varray_init() for _, sug := range result { cSug := unsafe.Pointer(C.makeSuggestion(C.CString(sug.Word), C.int(sug.Weight), C.int(sug.LearnedOn))) C.varray_push(ptr, cSug) } *resultPointer = ptr return C.VARNAM_SUCCESS } func makeGoSchemeDetails(sd *C.struct_SchemeDetails_t) govarnam.SchemeDetails { return govarnam.SchemeDetails{ Identifier: C.GoString(sd.Identifier), LangCode: C.GoString(sd.LangCode), DisplayName: C.GoString(sd.DisplayName), Author: C.GoString(sd.Author), CompiledDate: C.GoString(sd.CompiledDate), IsStable: cintToBool(sd.IsStable), } } func makeCSchemeDetails(sd govarnam.SchemeDetails) *C.struct_SchemeDetails_t { var cIsStable C.int if sd.IsStable { cIsStable = C.int(1) } else { cIsStable = C.int(0) } return C.makeSchemeDetails( C.CString(sd.Identifier), C.CString(sd.LangCode), C.CString(sd.DisplayName), C.CString(sd.Author), C.CString(sd.CompiledDate), cIsStable, ) } //export varnam_get_scheme_details func varnam_get_scheme_details(varnamHandleID C.int) *C.struct_SchemeDetails_t { handle := getVarnamHandle(varnamHandleID) return makeCSchemeDetails(handle.varnam.SchemeDetails) } //export varnam_get_vst_dir func varnam_get_vst_dir() *C.char { var dir string dir, generalError = govarnam.FindVSTDir() return C.CString(dir) } //export varnam_get_all_scheme_details func varnam_get_all_scheme_details() *C.varray { var schemeDetails []govarnam.SchemeDetails schemeDetails, generalError = govarnam.GetAllSchemeDetails() if generalError != nil { return nil } cSchemeDetails := C.varray_init() for _, sd := range schemeDetails { cSD := unsafe.Pointer(makeCSchemeDetails(sd)) C.varray_push(cSchemeDetails, cSD) } return cSchemeDetails } //export vm_init func vm_init(vstPath *C.char, id unsafe.Pointer) C.int { handleID := C.int(len(varnamHandles)) *(*C.int)(id) = handleID varnamGo, err := govarnam.VMInit(C.GoString(vstPath)) varnamHandlesMapMutex.Lock() varnamHandles[handleID] = &varnamHandle{varnamGo, err} varnamHandlesMapMutex.Unlock() return checkError(err) } //export vm_create_token func vm_create_token(varnamHandleID C.int, pattern *C.char, value1 *C.char, value2 *C.char, value3 *C.char, tag *C.char, symbolType C.int, matchType C.int, priority C.int, acceptCondition C.int, buffered C.int) C.int { handle := getVarnamHandle(varnamHandleID) // if pattern == nil { // pattern = C.CString("") // } // if value1 == nil { // value1 = C.CString("") // } // if value2 == nil { // value2 = C.CString("") // } // if value3 == nil { // value3 = C.CString("") // } // if tag == nil { // tag = C.CString("") // } handle.err = handle.varnam.VMCreateToken( C.GoString(pattern), C.GoString(value1), C.GoString(value2), C.GoString(value3), C.GoString(tag), int(symbolType), int(matchType), int(priority), int(acceptCondition), cintToBool(buffered), ) return checkError(handle.err) } //export vm_delete_token func vm_delete_token(varnamHandleID C.int, searchCriteria C.struct_Symbol_t) C.int { handle := getVarnamHandle(varnamHandleID) goSearchCriteria := cSymbolToGoSymbol(searchCriteria) handle.err = handle.varnam.VMDeleteToken(goSearchCriteria) return checkError(handle.err) } //export vm_flush_buffer func vm_flush_buffer(varnamHandleID C.int) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.VMFlushBuffer() return checkError(handle.err) } //export varnam_config func varnam_config(varnamHandleID C.int, key C.int, value C.int) C.int { handle := getVarnamHandle(varnamHandleID) switch key { case C.VARNAM_CONFIG_USE_INDIC_DIGITS: handle.varnam.LangRules.IndicDigits = cintToBool(value) break case C.VARNAM_CONFIG_USE_DEAD_CONSONANTS: handle.varnam.VSTMakerConfig.UseDeadConsonants = cintToBool(value) break case C.VARNAM_CONFIG_IGNORE_DUPLICATE_TOKEN: handle.varnam.VSTMakerConfig.IgnoreDuplicateTokens = cintToBool(value) break case C.VARNAM_CONFIG_SET_DICTIONARY_SUGGESTIONS_LIMIT: handle.varnam.DictionarySuggestionsLimit = int(value) break case C.VARNAM_CONFIG_SET_PATTERN_DICTIONARY_SUGGESTIONS_LIMIT: handle.varnam.PatternDictionarySuggestionsLimit = int(value) break case C.VARNAM_CONFIG_SET_TOKENIZER_SUGGESTIONS_LIMIT: handle.varnam.TokenizerSuggestionsLimit = int(value) break case C.VARNAM_CONFIG_SET_DICTIONARY_MATCH_EXACT: handle.varnam.DictionaryMatchExact = cintToBool(value) break } return C.VARNAM_SUCCESS } //export vm_set_scheme_details func vm_set_scheme_details(varnamHandleID C.int, sd *C.struct_SchemeDetails_t) C.int { handle := getVarnamHandle(varnamHandleID) handle.err = handle.varnam.VMSetSchemeDetails(makeGoSchemeDetails(sd)) return checkError(handle.err) } func main() {} govarnam-1.9.0/c-shared.h000066400000000000000000000045101420445125700151760ustar00rootroot00000000000000#ifndef __C_SHARED_H__ #define __C_SHARED_H__ #include "c-shared-varray.h" #define VARNAM_SUCCESS 0 #define VARNAM_MISUSE 1 #define VARNAM_ERROR 2 #define VARNAM_CANCELLED 3 #define VARNAM_CONFIG_USE_DEAD_CONSONANTS 100 #define VARNAM_CONFIG_IGNORE_DUPLICATE_TOKEN 101 // VARNAM_CONFIG_ENABLE_SUGGESTIONS hasn't been implemented yet #define VARNAM_CONFIG_ENABLE_SUGGESTIONS 102 #define VARNAM_CONFIG_USE_INDIC_DIGITS 103 #define VARNAM_CONFIG_SET_DICTIONARY_SUGGESTIONS_LIMIT 104 #define VARNAM_CONFIG_SET_PATTERN_DICTIONARY_SUGGESTIONS_LIMIT 105 #define VARNAM_CONFIG_SET_TOKENIZER_SUGGESTIONS_LIMIT 106 #define VARNAM_CONFIG_SET_DICTIONARY_MATCH_EXACT 107 typedef struct Suggestion_t { char* Word; int Weight; int LearnedOn; } Suggestion; typedef struct TransliterationResult_t { varray* ExactWords; varray* ExactMatches; varray* DictionarySuggestions; varray* PatternDictionarySuggestions; varray* TokenizerSuggestions; varray* GreedyTokenized; } TransliterationResult; Suggestion* makeSuggestion(char* word, int weight, int learned_on); TransliterationResult* makeResult(varray* exact_words, varray* exact_matches, varray* dictionary_suggestions, varray* pattern_dictionary_suggestions, varray* tokenizer_suggestions, varray* greedy_tokenized); void destroySuggestionsArray(varray* pointer); void destroyTransliterationResult(TransliterationResult*); typedef struct SchemeDetails_t { char* Identifier; char* LangCode; char* DisplayName; char* Author; char* CompiledDate; bool IsStable; } SchemeDetails; SchemeDetails* makeSchemeDetails(char* Identifier, char* LangCode, char* DisplayName, char* Author, char* CompiledDate, bool IsStable); void destroySchemeDetailsArray(void* cSchemeDetails); typedef struct LearnStatus_t { int TotalWords; int FailedWords; } LearnStatus; LearnStatus makeLearnStatus(int TotalWords, int FailedWords); typedef struct Symbol_t { int Identifier; int Type; int MatchType; char* Pattern; char* Value1; char* Value2; char* Value3; char* Tag; int Weight; int Priority; int AcceptCondition; int Flags; } Symbol; Symbol* makeSymbol(int Identifier, int Type, int MatchType, char* Pattern, char* Value1, char* Value2, char* Value3, char* Tag, int Weight, int Priority, int AcceptCondition, int Flags); void destroySymbolArray(void* cSymbols); #endif /* __C_SHARED_H__ */govarnam-1.9.0/cli/000077500000000000000000000000001420445125700141065ustar00rootroot00000000000000govarnam-1.9.0/cli/.gitignore000066400000000000000000000000221420445125700160700ustar00rootroot00000000000000cli varnam varnamcgovarnam-1.9.0/cli/main.go000066400000000000000000000125641420445125700153710ustar00rootroot00000000000000package main /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "context" "flag" "fmt" "log" "path/filepath" "time" "github.com/varnamproject/govarnam/govarnamgo" ) var varnam *govarnamgo.VarnamHandle func printSugs(sugs []govarnamgo.Suggestion) { for _, sug := range sugs { if sug.LearnedOn == 0 { fmt.Println(sug.Word + " " + fmt.Sprint(sug.Weight)) } else { fmt.Println(sug.Word + " " + fmt.Sprint(sug.Weight) + " " + time.Unix(int64(sug.LearnedOn), 0).String()) } } } func main() { versionFlag := flag.Bool("version", false, "Show version information") debugFlag := flag.Bool("debug", false, "Enable debugging outputs") schemeFlag := flag.String("s", "", "Scheme ID") reIndexFlag := flag.Bool("reindex", false, "Reindex user dictionary database") learnFlag := flag.Bool("learn", false, "Learn a word") unlearnFlag := flag.Bool("unlearn", false, "Unlearn a word") trainFlag := flag.Bool("train", false, "Train a word with a particular pattern. 2 Arguments: Pattern & Word") learnFromFileFlag := flag.Bool("learn-from-file", false, "Learn words in a file") trainFromFileFlag := flag.Bool("train-from-file", false, "Train pattern => word from a file.") exportFlag := flag.Bool("export", false, "Export learnings to file") exportWordsPerFile := flag.Int("export-words-per-file", 30000, "Words per export file") importFlag := flag.Bool("import", false, "Import learnings from file") indicDigitsFlag := flag.Bool("digits", false, "Use indic digits") advanced := flag.Bool("advanced", false, "Show transliteration result in advanced mode") reverseTransliterate := flag.Bool("reverse", false, "Reverse transliterate. Find which pattern to use for a specific word") flag.Parse() if *versionFlag { fmt.Println(govarnamgo.GetVersion()) fmt.Println(govarnamgo.GetBuild()) return } if *schemeFlag == "" { fmt.Println("Specifiy a scheme ID with -s.\n\nUse --help for all available commands.") return } var err error varnam, err = govarnamgo.InitFromID(*schemeFlag) if err != nil { log.Fatal(err.Error()) } varnam.Debug(*debugFlag) config := govarnamgo.Config{IndicDigits: *indicDigitsFlag, DictionarySuggestionsLimit: 10, PatternDictionarySuggestionsLimit: 10, TokenizerSuggestionsLimit: 10, TokenizerSuggestionsAlways: true} varnam.SetConfig(config) args := flag.Args() if *reIndexFlag { err := varnam.ReIndexDictionary() if err != nil { log.Fatal(err.Error()) } fmt.Println("Successfully re-indexed dictionary.") } else if *trainFlag { pattern := args[0] word := args[1] err := varnam.Train(pattern, word) if err != nil { log.Fatal(err.Error()) } fmt.Printf("Trained %s => %s\n", pattern, word) } else if *learnFlag { word := args[0] err := varnam.Learn(word, 0) if err == nil { fmt.Printf("Learnt %s\n", word) } else { fmt.Printf("Couldn't learn %s", word) log.Fatal(err.Error()) } } else if *unlearnFlag { word := args[0] err := varnam.Unlearn(word) if err == nil { fmt.Printf("Unlearnt %s\n", word) } else { fmt.Printf("Couldn't learn %s", word) log.Fatal(err.Error()) } } else if *learnFromFileFlag { learnStatus, err := varnam.LearnFromFile(args[0]) if err == nil { fmt.Printf("Finished learning from file. Total words: %d. Failed: %d\n", learnStatus.TotalWords, learnStatus.FailedWords) } else { log.Fatal(err.Error()) } } else if *trainFromFileFlag { learnStatus, err := varnam.TrainFromFile(args[0]) if err == nil { fmt.Printf("Finished training from file. Total words: %d. Failed: %d\n", learnStatus.TotalWords, learnStatus.FailedWords) } else { log.Fatal(err.Error()) } } else if *exportFlag { err := varnam.Export(args[0], *exportWordsPerFile) if err == nil { fmt.Println("Finished exporting to file") } else { log.Fatal(err.Error()) } } else if *importFlag { matches, err := filepath.Glob(args[0]) if err != nil { log.Fatal(err.Error()) } for _, match := range matches { err := varnam.Import(match) if err == nil { fmt.Printf("Finished importing from file %s\n", match) } else { log.Fatal(err.Error()) } } } else if *reverseTransliterate { sugs, err := varnam.ReverseTransliterate(args[0]) if err != nil { log.Fatal(err.Error()) } probMsg := false lastWeight := sugs[0].Weight fmt.Println("Exact Matches") for _, sug := range sugs { // The first exact matches will have same weight value if !probMsg && lastWeight != sug.Weight { fmt.Println("Probability Match") probMsg = true } fmt.Println(sug.Word + " " + fmt.Sprint(sug.Weight)) lastWeight = sug.Weight } } else if *advanced { var result govarnamgo.TransliterationResult result, _ = varnam.TransliterateAdvanced(context.Background(), args[0]) fmt.Println("Greedy Tokenized") printSugs(result.GreedyTokenized) fmt.Println("Exact Words") printSugs(result.ExactWords) fmt.Println("Exact Matches") printSugs(result.ExactMatches) fmt.Println("Dictionary Suggestions") printSugs(result.DictionarySuggestions) fmt.Println("Pattern Dictionary Suggestions") printSugs(result.PatternDictionarySuggestions) fmt.Println("Tokenizer Suggestions") printSugs(result.TokenizerSuggestions) } else { result, _ := varnam.Transliterate(context.Background(), args[0]) printSugs(result) } varnam.Close() } govarnam-1.9.0/go.mod000066400000000000000000000001371420445125700144460ustar00rootroot00000000000000module github.com/varnamproject/govarnam go 1.16 require github.com/mattn/go-sqlite3 v1.14.6 govarnam-1.9.0/go.sum000066400000000000000000000002571420445125700144760ustar00rootroot00000000000000github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= govarnam-1.9.0/govarnam.pc.in000066400000000000000000000004431420445125700161030ustar00rootroot00000000000000prefix=@INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include/libgovarnam Name: GoVarnam Description: A transliteration library for Indian languages URL: http://varnamproject.com Version: @VERSION@ Libs: -L${libdir} -lgovarnam Cflags: -I${includedir} govarnam-1.9.0/govarnam/000077500000000000000000000000001420445125700151515ustar00rootroot00000000000000govarnam-1.9.0/govarnam/channel.go000066400000000000000000000136311420445125700171140ustar00rootroot00000000000000package govarnam import ( "context" "fmt" "log" "time" ) type channelDictionaryResult struct { exactWords []Suggestion exactMatches []Suggestion suggestions []Suggestion } func (varnam *Varnam) channelTokenizeWord(ctx context.Context, word string, matchType int, partial bool, channel chan *[]Token) { select { case <-ctx.Done(): close(channel) return default: start := time.Now() tokens := varnam.tokenizeWord(ctx, word, matchType, partial) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelTokenizeWord", time.Since(start)) } channel <- tokens close(channel) } } func (varnam *Varnam) channelTokensToSuggestions(ctx context.Context, tokens *[]Token, limit int, channel chan []Suggestion) { select { case <-ctx.Done(): close(channel) return default: start := time.Now() sugs := varnam.tokensToSuggestions(ctx, tokens, false, limit) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelTokensToSuggestions", time.Since(start)) } channel <- sugs close(channel) } } func (varnam *Varnam) channelTokensToGreedySuggestions(ctx context.Context, tokens *[]Token, channel chan []Suggestion) { select { case <-ctx.Done(): close(channel) return default: start := time.Now() sugs := varnam.tokensToSuggestions(ctx, tokens, false, varnam.TokenizerSuggestionsLimit) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelTokensToGreedySuggestions", time.Since(start)) } channel <- sugs close(channel) } } func (varnam *Varnam) channelGetFromDictionary(ctx context.Context, word string, tokens *[]Token, channel chan channelDictionaryResult) { var ( exactWords []Suggestion exactMatches []Suggestion moreSuggestions []Suggestion ) select { case <-ctx.Done(): close(channel) return default: start := time.Now() dictResult := varnam.getFromDictionary(ctx, tokens) if varnam.Debug { fmt.Println("Dictionary results:", dictResult) } if len(dictResult.exactMatches) > 0 { start := time.Now() // Exact words can be determined finally // with help of this function's result moreFromDict := varnam.getMoreFromDictionary(ctx, dictResult.exactMatches) if varnam.Debug { fmt.Println("More dictionary results:", moreFromDict) } // dictResult.exactMatches will have both matches and exact words. // getMoreFromDictionary() will separate out the exact words. exactWords = moreFromDict.exactWords // Intersection of slices. // exactMatches shouldn't have items from exactWords hash := make(map[string]bool) for i := range exactWords { hash[exactWords[i].Word] = true } for _, sug := range dictResult.exactMatches { if _, found := hash[sug.Word]; !found { exactMatches = append(exactMatches, sug) } } for _, sugSet := range moreFromDict.moreSuggestions { moreSuggestions = append(moreSuggestions, sugSet...) } if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "getMoreFromDictionary", time.Since(start)) } } if len(dictResult.partialMatches) > 0 { // Tokenize the word after the longest match found in dictionary restOfWord := word[dictResult.longestMatchPosition+1:] start := time.Now() moreSuggestions = varnam.tokenizeRestOfWord( ctx, restOfWord, dictResult.partialMatches, varnam.DictionarySuggestionsLimit, ) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "tokenizeRestOfWord", time.Since(start)) } } if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelGetFromDictionary", time.Since(start)) } channel <- channelDictionaryResult{ exactWords, exactMatches, moreSuggestions, } close(channel) } } func (varnam *Varnam) channelGetFromPatternDictionary(ctx context.Context, word string, channel chan channelDictionaryResult) { var ( exactWords []Suggestion moreSuggestions []Suggestion ) select { case <-ctx.Done(): close(channel) return default: start := time.Now() patternDictSugs := varnam.getFromPatternDictionary(ctx, word) if len(patternDictSugs) > 0 { if varnam.Debug { fmt.Println("Pattern dictionary results:", patternDictSugs) } var partialMatches []PatternDictionarySuggestion for _, match := range patternDictSugs { if match.Length < len(word) { sug := &match.Sug // Increase weight on length matched. // 50 because half of 100% sug.Weight += match.Length * 50 for _, cb := range varnam.PatternWordPartializers { cb(sug) } partialMatches = append(partialMatches, match) } else if match.Length == len(word) { // Same length, exact word matched exactWords = append(exactWords, match.Sug) } else { moreSuggestions = append(moreSuggestions, match.Sug) } } perMatchLimit := varnam.PatternDictionarySuggestionsLimit if len(partialMatches) > 0 && perMatchLimit > len(partialMatches) { perMatchLimit = perMatchLimit / len(partialMatches) } for i := range partialMatches { restOfWord := word[partialMatches[i].Length:] filled := varnam.tokenizeRestOfWord( ctx, restOfWord, []Suggestion{partialMatches[i].Sug}, perMatchLimit, ) moreSuggestions = append(moreSuggestions, filled...) if len(moreSuggestions) >= varnam.PatternDictionarySuggestionsLimit { break } } } if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelGetFromPatternDictionary", time.Since(start)) } channel <- channelDictionaryResult{ exactWords, []Suggestion{}, // Not applicable for patterns dictionary moreSuggestions, } close(channel) } } func (varnam *Varnam) channelGetMoreFromDictionary(ctx context.Context, sugs []Suggestion, channel chan MoreDictionaryResult) { select { case <-ctx.Done(): close(channel) return default: start := time.Now() result := varnam.getMoreFromDictionary(ctx, sugs) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "channelGetMoreFromDictionary", time.Since(start)) } channel <- result close(channel) } } govarnam-1.9.0/govarnam/constants.go000066400000000000000000000074341420445125700175240ustar00rootroot00000000000000package govarnam import ( "fmt" "os" "path" ) // Compile-time variables. var ( BuildString string VersionString string ) // Go's struct int has default value 0. // For SearchSymbolTable usecase this is a problem. // Hence we use a constructor with default value setting. // https://stackoverflow.com/q/37135193/1372424 const STRUCT_INT_DEFAULT_VALUE = -1 /* General */ const ZWNJ = "\u200c" const ZWJ = "\u200d" /* Pattern matching */ const VARNAM_MATCH_EXACT = 1 const VARNAM_MATCH_POSSIBILITY = 2 const VARNAM_MATCH_ALL = 3 /* Type of tokens */ const VARNAM_TOKEN_CHAR = 1 // Non-lang characters like A, B, 1, * etc. const VARNAM_TOKEN_SYMBOL = 2 // Lang characters /* A symbol token's maximum possible weight value */ const VARNAM_TOKEN_BASIC_WEIGHT = 10 /* Available type of symbol tokens */ const VARNAM_SYMBOL_VOWEL = 1 const VARNAM_SYMBOL_CONSONANT = 2 const VARNAM_SYMBOL_DEAD_CONSONANT = 3 const VARNAM_SYMBOL_CONSONANT_VOWEL = 4 const VARNAM_SYMBOL_NUMBER = 5 const VARNAM_SYMBOL_SYMBOL = 6 const VARNAM_SYMBOL_ANUSVARA = 7 const VARNAM_SYMBOL_VISARGA = 8 const VARNAM_SYMBOL_VIRAMA = 9 const VARNAM_SYMBOL_OTHER = 10 const VARNAM_SYMBOL_NON_JOINER = 11 const VARNAM_SYMBOL_JOINER = 12 const VARNAM_SYMBOL_PERIOD = 13 /* Token acceptance rules */ const VARNAM_TOKEN_ACCEPT_ALL = 0 const VARNAM_TOKEN_ACCEPT_IF_STARTS_WITH = 1 const VARNAM_TOKEN_ACCEPT_IF_IN_BETWEEN = 2 const VARNAM_TOKEN_ACCEPT_IF_ENDS_WITH = 3 // VARNAM_LEARNT_WORD_MIN_WEIGHT Minimum weight/confidence for learnt words. const VARNAM_LEARNT_WORD_MIN_WEIGHT = 30 const CHIL_TAG = "chill" /* VST creation */ // VARNAM_SYMBOL_MAX maximum length of VST column value const VARNAM_SYMBOL_MAX = 30 const VARNAM_SYMBOL_FLAGS_MORE_MATCHES_FOR_PATTERN = (1 << 0) const VARNAM_SYMBOL_FLAGS_MORE_MATCHES_FOR_VALUE = (1 << 1) const VARNAM_SCHEMA_SYMBOLS_VERSION = 20211101 const VARNAM_METADATA_SCHEME_LANGUAGE_CODE = "lang-code" const VARNAM_METADATA_SCHEME_IDENTIFIER = "scheme-id" const VARNAM_METADATA_SCHEME_DISPLAY_NAME = "scheme-display-name" const VARNAM_METADATA_SCHEME_AUTHOR = "scheme-author" const VARNAM_METADATA_SCHEME_COMPILED_DATE = "scheme-compiled-date" const VARNAM_METADATA_SCHEME_STABLE = "scheme-stable" var VARNAM_VST_DIR = os.Getenv("VARNAM_VST_DIR") var VARNAM_LEARNINGS_DIR = os.Getenv("VARNAM_LEARNINGS_DIR") // SetVSTLookupDir This overrides the environment variable func SetVSTLookupDir(path string) { VARNAM_VST_DIR = path } // SetVSTLookupDir This overrides the environment variable func SetLearningsDir(path string) { VARNAM_LEARNINGS_DIR = path } // VARNAM_VST_DIR VST lookup directories according to priority func getVSTLookupDirs() []string { return []string{ // libvarnam used to use "vst" folder VARNAM_VST_DIR, "schemes", "/usr/local/share/varnam/schemes", "/usr/share/varnam/schemes", } } //FindVSTDir Get the VST storing directory func FindVSTDir() (string, error) { for _, loc := range getVSTLookupDirs() { if dirExists(loc) { return loc, nil } } return "", fmt.Errorf("Couldn't find VST directory") } func findVSTPath(schemeID string) (string, error) { for _, dir := range getVSTLookupDirs() { temp := path.Join(dir, schemeID+".vst") if fileExists(temp) { return temp, nil } } return "", fmt.Errorf("Couldn't find VST for %q", schemeID) } func findLearningsFilePath(langCode string) string { var ( loc string dir string ) if VARNAM_LEARNINGS_DIR != "" { dir = VARNAM_LEARNINGS_DIR } else { // libvarnam used to use "suggestions" folder home := os.Getenv("XDG_DATA_HOME") if home != "" { dir = path.Join(home, "varnam", "learnings") } else { home = os.Getenv("HOME") dir = path.Join(home, ".local", "share", "varnam", "learnings") } } loc = path.Join(dir, langCode+".vst.learnings") return loc } var LOG_TIME_TAKEN = os.Getenv("GOVARNAM_LOG_TIME_TAKEN") != "" govarnam-1.9.0/govarnam/dictionary.go000066400000000000000000000242161420445125700176520ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "context" "embed" "fmt" "io/fs" "log" "os" "path" "time" ) //go:embed migrations/*.sql var embedFS embed.FS // DictionaryResult result from dictionary search type DictionaryResult struct { // Exactly found starting word matches. exactMatches []Suggestion // Words found in dictionary with same starting partialMatches []Suggestion longestMatchPosition int } // MoreDictionaryResult result from dictionary search type MoreDictionaryResult struct { // Exactly found words exactWords []Suggestion // Words found in dictionary with same starting moreSuggestions [][]Suggestion } // PatternDictionarySuggestion longest match result type PatternDictionarySuggestion struct { Sug Suggestion Length int } type searchDictionaryResult struct { match string word string weight int learnedOn int } // InitDict open connection to dictionary func (varnam *Varnam) InitDict(dictPath string) error { var err error if !fileExists(dictPath) { log.Printf("Making Varnam Learnings Dir for %s\n", dictPath) err := os.MkdirAll(path.Dir(dictPath), 0750) if err != nil { return err } } varnam.dictConn, err = openDB(dictPath) if err != nil { return err } varnam.DictPath = dictPath // cd into migrations directory migrationsFS, err := fs.Sub(embedFS, "migrations") if err != nil { return err } mg, err := InitMigrate(varnam.dictConn, migrationsFS) if err != nil { return err } ranMigrations, err := mg.Run() if ranMigrations != 0 { log.Printf("ran %d migrations", ranMigrations) } // Since SQLite v3.12.0, default page size is 4096 varnam.dictConn.Exec("PRAGMA page_size=4096;") // WAL makes writes & reads happen concurrently => significantly fast varnam.dictConn.Exec("PRAGMA journal_mode=wal;") return err } // ReIndexDictionary re-indexes dictionary func (varnam *Varnam) ReIndexDictionary() error { _, err := varnam.dictConn.Exec("INSERT INTO words_fts(words_fts) VALUES('rebuild');") return err } type searchDictionaryType int32 const ( searchMatches searchDictionaryType = 0 // For checking whether there are words in dictionary starting with something searchStartingWith searchDictionaryType = 1 // Find all words in dictionary starting with something searchExactWords searchDictionaryType = 2 // Find exact words in dictionary ) // all - Search for words starting with the word func (varnam *Varnam) searchDictionary(ctx context.Context, words []string, searchType searchDictionaryType) []searchDictionaryResult { likes := "" var ( vals []interface{} query string results []searchDictionaryResult ) select { case <-ctx.Done(): return results default: vals = append(vals, words[0]) for i := range words { if i == 0 { continue } likes += ", (?)" vals = append(vals, words[i]) } // Thanks forpas // CC BY-SA 4.0 licensed // https://stackoverflow.com/q/68610241/1372424 if searchType == searchMatches { query = "WITH cte(match) AS (VALUES (?) " + likes + ") SELECT c.match AS match, w.word AS word, MAX(w.weight), MAX(w.learned_on) FROM words_fts w INNER JOIN cte c ON w.word MATCH c.match || '*' GROUP BY c.match" } else if searchType == searchStartingWith { query = "WITH cte(match) AS (VALUES (?) " + likes + ") SELECT c.match AS match, w.* FROM words_fts w INNER JOIN cte c ON w.word MATCH c.match || '*' AND w.word != c.match ORDER BY weight DESC LIMIT ?" vals = append(vals, varnam.DictionarySuggestionsLimit) } else if searchType == searchExactWords { query = "SELECT * FROM words WHERE word IN ((?) " + likes + ")" } rows, err := varnam.dictConn.QueryContext(ctx, query, vals...) if err != nil { log.Print(err) return results } defer rows.Close() for rows.Next() { var item searchDictionaryResult rows.Scan(&item.match, &item.word, &item.weight, &item.learnedOn) results = append(results, item) } err = rows.Err() if err != nil { log.Print(err) return results } return results } } func (varnam *Varnam) getFromDictionary(ctx context.Context, tokensPointer *[]Token) DictionaryResult { var result DictionaryResult tokens := *tokensPointer select { case <-ctx.Done(): return result default: // This is a temporary storage for words made from tokens, // which will be searched in dictionary. // Similar to 'result' usage in tokenizeWord var tokenizedWords []searchDictionaryResult // We search in dictionary by going through each token, // these vars would store the last found results var lastFoundDictWords []searchDictionaryResult var lastFoundPosition = 0 for i, t := range tokens { var tempFoundDictWords []searchDictionaryResult if t.tokenType == VARNAM_TOKEN_SYMBOL { if i == 0 { start := time.Now() var toSearch []string for j := range t.symbols { toSearch = append(toSearch, getSymbolValue(t.symbols[j], 0)) } searchResults := varnam.searchDictionary( ctx, toSearch, searchMatches, ) tempFoundDictWords = searchResults tokenizedWords = searchResults if LOG_TIME_TAKEN { log.Printf( "%s took %v\n", "getFromDictionaryToken0", time.Since(start), ) } } else { start := time.Now() for j := range tokenizedWords { if tokenizedWords[j].weight == -1 { continue } till := tokenizedWords[j].match var toSearch []string for _, symbol := range t.symbols { newTill := till + getSymbolValue(symbol, i) toSearch = append(toSearch, newTill) } searchResults := varnam.searchDictionary( ctx, toSearch, searchMatches, ) if len(searchResults) > 0 { tempFoundDictWords = append(tempFoundDictWords, searchResults...) for k := range searchResults { if k == 0 { tokenizedWords[j].match = searchResults[k].match continue } sug := searchDictionaryResult{ searchResults[k].match, searchResults[k].word, 0, 0, } tokenizedWords = append(tokenizedWords, sug) } } else { // No need of processing this word anymore, we found no match in dictionary. // weight is used as a flag here to skip processing this further. tokenizedWords[j].weight = -1 } } if LOG_TIME_TAKEN { log.Printf("%s%d took %v\n", "getFromDictionaryToken", i, time.Since(start)) } } } if len(tempFoundDictWords) > 0 { lastFoundDictWords = tempFoundDictWords lastFoundPosition = t.position } } if lastFoundPosition == tokens[len(tokens)-1].position { result.exactMatches = convertSearchDictResultToSuggestion(lastFoundDictWords, false) } else { result.partialMatches = convertSearchDictResultToSuggestion(lastFoundDictWords, false) } result.longestMatchPosition = lastFoundPosition return result } } func (varnam *Varnam) getMoreFromDictionary(ctx context.Context, words []Suggestion) MoreDictionaryResult { var result MoreDictionaryResult select { case <-ctx.Done(): return result default: wordsToSearch := []string{} for i := range words { wordsToSearch = append(wordsToSearch, words[i].Word) search := []string{words[i].Word} result.moreSuggestions = append( result.moreSuggestions, convertSearchDictResultToSuggestion( varnam.searchDictionary(ctx, search, searchStartingWith), true, ), ) } result.exactWords = convertSearchDictResultToSuggestion( varnam.searchDictionary(ctx, wordsToSearch, searchExactWords), true, ) return result } } // Gets incomplete and complete matches from pattern dictionary // Eg: If pattern = "chin" or "chinayil", will return "china" func (varnam *Varnam) getFromPatternDictionary(ctx context.Context, pattern string) []PatternDictionarySuggestion { var results []PatternDictionarySuggestion select { case <-ctx.Done(): return results default: rows, err := varnam.dictConn.QueryContext(ctx, "SELECT LENGTH(pts.pattern), w.word, w.weight, w.learned_on FROM `patterns` pts LEFT JOIN words w ON w.id = pts.word_id WHERE ? LIKE (pts.pattern || '%') OR pattern LIKE ? ORDER BY LENGTH(pts.pattern) DESC LIMIT ?", pattern, pattern+"%", varnam.PatternDictionarySuggestionsLimit) if err != nil { log.Print(err) return results } defer rows.Close() for rows.Next() { var item PatternDictionarySuggestion rows.Scan(&item.Length, &item.Sug.Word, &item.Sug.Weight, &item.Sug.LearnedOn) item.Sug.Weight += VARNAM_LEARNT_WORD_MIN_WEIGHT results = append(results, item) } err = rows.Err() if err != nil { log.Print(err) } return results } } // GetRecentlyLearntWords get recently learnt words func (varnam *Varnam) GetRecentlyLearntWords(ctx context.Context, offset int, limit int) ([]Suggestion, error) { var result []Suggestion select { case <-ctx.Done(): return result, nil default: rows, err := varnam.dictConn.QueryContext(ctx, "SELECT word, weight, learned_on FROM words ORDER BY learned_on DESC, id DESC LIMIT "+fmt.Sprint(offset)+", "+fmt.Sprint(limit)) if err != nil { return result, err } defer rows.Close() for rows.Next() { var item Suggestion rows.Scan(&item.Word, &item.Weight, &item.LearnedOn) result = append(result, item) } err = rows.Err() if err != nil { log.Print(err) return result, err } return result, nil } } // GetSuggestions get word suggestions from dictionary func (varnam *Varnam) GetSuggestions(ctx context.Context, word string) []Suggestion { var sugs []Suggestion select { case <-ctx.Done(): return sugs default: return convertSearchDictResultToSuggestion( varnam.searchDictionary(ctx, []string{word}, searchStartingWith), true, ) } } func convertSearchDictResultToSuggestion(searchResults []searchDictionaryResult, word bool) []Suggestion { var sugs []Suggestion for i := range searchResults { sug := Suggestion{ searchResults[i].match, searchResults[i].weight, searchResults[i].learnedOn, } if word { sug.Word = searchResults[i].word } sugs = append(sugs, sug) } return sugs } govarnam-1.9.0/govarnam/govarnam.go000066400000000000000000000355641420445125700173270ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "context" sql "database/sql" "fmt" "log" "sort" "strings" "time" "unicode/utf8" // sqlite3 _ "github.com/mattn/go-sqlite3" ) // LangRules language reulated config type LangRules struct { Virama string IndicDigits bool PatternLongestLength int // Longest length of pattern in VST } // SchemeDetails of VST type SchemeDetails struct { Identifier string LangCode string DisplayName string Author string CompiledDate string IsStable bool } type VSTMakerConfig struct { // Not a config. State variable Buffering bool IgnoreDuplicateTokens bool UseDeadConsonants bool } // Varnam config type Varnam struct { VSTPath string DictPath string vstConn *sql.DB dictConn *sql.DB LangRules LangRules SchemeDetails SchemeDetails Debug bool PatternWordPartializers []func(*Suggestion) // Maximum suggestions to obtain from dictionary DictionarySuggestionsLimit int // Maximum suggestions to obtain from patterns dictionary PatternDictionarySuggestionsLimit int // Maximum suggestions to be made from tokenizer TokenizerSuggestionsLimit int // Always include tokenizer made suggestions. // Tokenizer results are not exactly the best, but it's alright TokenizerSuggestionsAlways bool // Whether only exact scheme match should be considered // for dictionary search and discard possibility matches DictionaryMatchExact bool VSTMakerConfig VSTMakerConfig // See setDefaultConfig() for the default values } // Suggestion suggestion type Suggestion struct { Word string Weight int LearnedOn int } // TransliterationResult result type TransliterationResult struct { // Exactly found words in dictionary if there is any. // From both patterns and normal dict ExactWords []Suggestion // Exactly starting word matches in dictionary if there is any. // Not applicable for patterns dictionary. ExactMatches []Suggestion // Possible word suggestions from dictionary DictionarySuggestions []Suggestion // Possible words matching from patterns dictionary PatternDictionarySuggestions []Suggestion // All possible matches from tokenizer (VARNAM_MATCH_ALL) // Has a limit. The first few results will be VARNAM_MATCH_EXACT. // This will only be filled if there are no exact matches. // Related: See Config.TokenizerSuggestionsAlways TokenizerSuggestions []Suggestion // VARNAM_MATCH_EXACT results from tokenizer. // No limit, mostly gives 1 or less than 3 outputs GreedyTokenized []Suggestion } func (varnam *Varnam) log(msg string) { if varnam.Debug { fmt.Println(msg) } } /** * Convert tokens into suggestions. * partial - set true if only a part of a word is being tokenized and not an entire word */ func (varnam *Varnam) tokensToSuggestions(ctx context.Context, tokensPointer *[]Token, partial bool, limit int) []Suggestion { var results []Suggestion tokens := *tokensPointer select { case <-ctx.Done(): return results default: tokens = removeLessWeightedSymbols(tokens) addWord := func(word []string, weight int) { // TODO avoid division, performance improvement ? weight = weight / 100 results = append(results, Suggestion{strings.Join(word, ""), weight, 0}) } // Tracks index of each token possibilities // ----- // Suppose input is "vardhichu". We will try each possibilities of each token // The index of these possibilities is tracked here // [0 0 0 0] => വ ർ ധി ചു // [0 0 0 1] => വ ർ ധി ച്ചു // [0 0 1 0] => വ ർ ഥി ചു // [0 0 1 1] => വ ർ ഥി ച്ചു tokenPositions := make([]int, len(tokens)) // We go right to left. // We try possibilities from the last character (k) where there are multiple possibilities. // if it's over we shift the possibility on left, so on and on k := len(tokens) - 1 i := k for i >= 0 { if tokens[i].tokenType == VARNAM_TOKEN_SYMBOL && len(tokens[i].symbols)-1 > tokenPositions[i] { k = i break } i-- } for len(results) < limit { // One loop will make one word word := make([]string, len(tokens)) weight := 0 // i is the character position we're making i := len(tokens) - 1 for i >= 0 { t := tokens[i] if t.tokenType == VARNAM_TOKEN_SYMBOL { symbol := t.symbols[tokenPositions[i]] var ( symbolValue string symbolWeight int ) if i == 0 { if partial { // Since partial, the first character is not // the first character of word symbolValue = getSymbolValue(symbol, 1) symbolWeight = getSymbolWeight(symbol) } else { symbolValue = getSymbolValue(symbol, 0) symbolWeight = getSymbolWeight(symbol) } } else { symbolValue = getSymbolValue(symbol, i) symbolWeight = getSymbolWeight(symbol) } word[i] = symbolValue weight += symbolWeight } else if t.tokenType == VARNAM_TOKEN_CHAR { word[i] = t.character } i-- } // If no more possibilites, go to the next one if tokenPositions[k] >= len(tokens[k].symbols)-1 { // Reset the currently permuted position tokenPositions[k] = 0 // Find the next place where there are more possibilities i := k - 1 for i >= 0 { if tokens[i].tokenType == VARNAM_TOKEN_SYMBOL && len(tokens[i].symbols)-1 > tokenPositions[i] { // Set the newly gonna permuting position tokenPositions[i]++ break } else { tokenPositions[i] = 0 } i-- } addWord(word, weight) if i < 0 { break } } else { tokenPositions[k]++ addWord(word, weight) } } return results } } func (varnam *Varnam) setDefaultConfig() { varnam.DictionarySuggestionsLimit = 5 varnam.PatternDictionarySuggestionsLimit = 5 varnam.TokenizerSuggestionsLimit = 10 varnam.TokenizerSuggestionsAlways = true varnam.DictionaryMatchExact = false varnam.LangRules.IndicDigits = false varnam.LangRules.Virama, _ = varnam.getVirama() if varnam.SchemeDetails.LangCode == "ml" { varnam.RegisterPatternWordPartializer(varnam.mlPatternWordPartializer) } } // SortSuggestions by weight and learned on time func SortSuggestions(sugs []Suggestion) []Suggestion { // TODO write tests sort.SliceStable(sugs, func(i, j int) bool { if (sugs[i].LearnedOn == 0 || sugs[j].LearnedOn == 0) && !(sugs[i].LearnedOn == 0 && sugs[j].LearnedOn == 0) { return sugs[i].LearnedOn > sugs[j].LearnedOn } return sugs[i].Weight > sugs[j].Weight }) return sugs } // Returns tokens and all found suggestions func (varnam *Varnam) transliterate(ctx context.Context, word string) ( *[]Token, TransliterationResult) { var ( result TransliterationResult ) start := time.Now() tokensPointerChan := make(chan *[]Token) go varnam.channelTokenizeWord(ctx, word, VARNAM_MATCH_ALL, false, tokensPointerChan) select { case <-ctx.Done(): return nil, result case tokensPointer := <-tokensPointerChan: if len(*tokensPointer) == 0 { return nil, result } if varnam.Debug { fmt.Println(*tokensPointer) } /* Channels make things faster, getting from DB is time-consuming */ dictSugsChan := make(chan channelDictionaryResult) patternDictSugsChan := make(chan channelDictionaryResult) greedyTokenizedChan := make(chan []Suggestion) // Only exact tokens exactTokens := make([]Token, len(*tokensPointer)) copy(exactTokens, *tokensPointer) exactTokens = removeNonExactTokens(exactTokens) if varnam.DictionaryMatchExact { go varnam.channelGetFromDictionary(ctx, word, &exactTokens, dictSugsChan) } else { go varnam.channelGetFromDictionary(ctx, word, tokensPointer, dictSugsChan) } go varnam.channelGetFromPatternDictionary(ctx, word, patternDictSugsChan) go varnam.channelTokensToGreedySuggestions(ctx, &exactTokens, greedyTokenizedChan) tokenizerSugsChan := make(chan []Suggestion) tokenizerSugsCalled := false select { case <-ctx.Done(): return nil, result case channelDictResult := <-dictSugsChan: // From dictionary result.ExactWords = channelDictResult.exactWords result.ExactMatches = channelDictResult.exactMatches result.DictionarySuggestions = channelDictResult.suggestions select { case <-ctx.Done(): return nil, result case channelPatternDictResult := <-patternDictSugsChan: // From patterns dictionary result.ExactWords = append(result.ExactWords, channelPatternDictResult.exactWords...) result.PatternDictionarySuggestions = SortSuggestions(channelPatternDictResult.suggestions) if len(result.ExactMatches) == 0 || varnam.TokenizerSuggestionsAlways { go varnam.channelTokensToSuggestions(ctx, tokensPointer, varnam.TokenizerSuggestionsLimit, tokenizerSugsChan) tokenizerSugsCalled = true } select { case <-ctx.Done(): return nil, result // Add greedy tokenized suggestions. This will only give exact match (VARNAM_MATCH_EXACT) results case greedyTokenizedResult := <-greedyTokenizedChan: result.GreedyTokenized = SortSuggestions(greedyTokenizedResult) // Sort everything now result.ExactWords = SortSuggestions(result.ExactWords) result.ExactMatches = SortSuggestions(result.ExactMatches) result.DictionarySuggestions = SortSuggestions(result.DictionarySuggestions) result.PatternDictionarySuggestions = SortSuggestions(result.PatternDictionarySuggestions) if tokenizerSugsCalled { select { case <-ctx.Done(): return nil, result case tokenizerSugs := <-tokenizerSugsChan: result.TokenizerSuggestions = SortSuggestions(tokenizerSugs) if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "transliteration", time.Since(start)) } return tokensPointer, result } } else { if LOG_TIME_TAKEN { log.Printf("%s took %v\n", "transliteration", time.Since(start)) } return tokensPointer, result } } } } } } // TransliterateAdvanced transliterate with a detailed structure as result func (varnam *Varnam) TransliterateAdvanced(word string) TransliterationResult { ctx := context.Background() _, result := varnam.transliterate(ctx, word) return result } // TransliterateAdvancedWithContext transliterate with a detailed structure as result Go context func (varnam *Varnam) TransliterateAdvancedWithContext(ctx context.Context, word string, resultChannel chan<- TransliterationResult) { select { case <-ctx.Done(): return default: _, result := varnam.transliterate(ctx, word) resultChannel <- result close(resultChannel) } } // Flatten TransliterationResult struct to a suggestion array func flattenTR(result TransliterationResult) []Suggestion { var combined []Suggestion dictCombined := result.ExactWords if len(result.ExactWords) == 0 { dictCombined = append(dictCombined, result.ExactMatches...) } dictCombined = append(dictCombined, result.PatternDictionarySuggestions...) dictCombined = append(dictCombined, result.DictionarySuggestions...) /** * Show greedy tokenized first if length less than 3 */ if len(result.GreedyTokenized) > 0 && utf8.RuneCountInString(result.GreedyTokenized[0].Word) < 3 { combined = append(combined, result.GreedyTokenized...) combined = append(combined, result.ExactWords...) combined = append(combined, result.ExactMatches...) combined = append(combined, result.PatternDictionarySuggestions...) combined = append(combined, result.DictionarySuggestions...) } else { /** * Show greedy tokenized always at 2nd * And then rest of the results from exact matches or the 2 dictionary * https://github.com/varnamproject/govarnam/issues/12 */ if len(dictCombined) > 0 { combined = append(combined, dictCombined[0]) } combined = append(combined, result.GreedyTokenized...) // Insert rest of them if len(dictCombined) > 1 { combined = append(combined, dictCombined[1:]...) } } combined = append(combined, result.TokenizerSuggestions...) combined = append(combined, result.GreedyTokenized...) return combined } // Transliterate transliterate with output array func (varnam *Varnam) Transliterate(word string) []Suggestion { return flattenTR(varnam.TransliterateAdvanced(word)) } // TransliterateWithContext Transliterate but with Go context func (varnam *Varnam) TransliterateWithContext(ctx context.Context, word string, resultChannel chan<- []Suggestion) { select { case <-ctx.Done(): return default: _, result := varnam.transliterate(ctx, word) resultChannel <- flattenTR(result) close(resultChannel) } } // TransliterateGreedyTokenized transliterate word, only tokenizer results func (varnam *Varnam) TransliterateGreedyTokenized(word string) []Suggestion { ctx := context.Background() tokens := varnam.tokenizeWord(ctx, word, VARNAM_MATCH_EXACT, false) return varnam.tokensToSuggestions(ctx, tokens, false, varnam.TokenizerSuggestionsLimit) } // ReverseTransliterate do a reverse transliteration func (varnam *Varnam) ReverseTransliterate(word string) ([]Suggestion, error) { var results []Suggestion ctx := context.Background() tokens := varnam.splitTextByConjunct(ctx, word) if varnam.Debug { fmt.Println(tokens) } for i := range tokens { for j, symbol := range tokens[i].symbols { tokens[i].symbols[j].Value1 = symbol.Pattern tokens[i].symbols[j].Value2 = symbol.Pattern } } results = SortSuggestions(varnam.tokensToSuggestions(ctx, &tokens, false, varnam.TokenizerSuggestionsLimit)) return results, nil } // RegisterPatternWordPartializer A word partializer remove word ending // with proper alternative so that the word can be tokenized further. // Useful for malayalam to replace last chil letter with its root func (varnam *Varnam) RegisterPatternWordPartializer(cb func(*Suggestion)) { varnam.PatternWordPartializers = append(varnam.PatternWordPartializers, cb) } // Init Initialize varnam. Dictionary will be created if it doesn't exist func Init(vstPath string, dictPath string) (*Varnam, error) { varnam := Varnam{} err := varnam.InitVST(vstPath) if err != nil { return nil, err } err = varnam.InitDict(dictPath) if err != nil { return nil, err } varnam.setDefaultConfig() return &varnam, nil } // InitFromID Init from ID. Scheme ID doesn't necessarily be a language code func InitFromID(schemeID string) (*Varnam, error) { var ( vstPath string dictPath string ) vstPath, err := findVSTPath(schemeID) if err != nil { return nil, err } varnam := Varnam{} err = varnam.InitVST(vstPath) if err != nil { return nil, err } // One dictionary for one language, not for different scheme dictPath = findLearningsFilePath(varnam.SchemeDetails.LangCode) err = varnam.InitDict(dictPath) if err != nil { return nil, err } varnam.setDefaultConfig() return &varnam, nil } // Close close db connections func (varnam *Varnam) Close() error { if varnam.vstConn != nil { varnam.vstConn.Close() } if varnam.dictConn != nil { varnam.dictConn.Close() } return nil } govarnam-1.9.0/govarnam/govarnam_ml-inscript_test.go000066400000000000000000000156561420445125700227070ustar00rootroot00000000000000package govarnam import ( "testing" ) // Inscript = Inscript 2 func TestMLInscriptGreedyTokenizer(t *testing.T) { varnam := getVarnamInstance("ml-inscript") assertEqual(t, varnam.TransliterateAdvanced("ECs").GreedyTokenized[0].Word, "ആണേ") assertEqual(t, varnam.TransliterateAdvanced("Zhdha").GreedyTokenized[0].Word, "എപ്പോ") } func TestMLInscriptTokenizer(t *testing.T) { varnam := getVarnamInstance("ml-inscript") // TestMLInscript non lang word nonLangWord := varnam.TransliterateAdvanced("Шаблон") assertEqual(t, len(nonLangWord.ExactMatches), 0) assertEqual(t, len(nonLangWord.DictionarySuggestions), 0) assertEqual(t, len(nonLangWord.PatternDictionarySuggestions), 0) assertEqual(t, len(nonLangWord.TokenizerSuggestions), 1) assertEqual(t, len(nonLangWord.GreedyTokenized), 1) // TestMLInscript mixed words & symbol escapes with | assertEqual(t, varnam.TransliterateAdvanced(";aയ്ച്ചാclf").GreedyTokenized[0].Word, "ചോയ്ച്ചാമതി") assertEqual(t, varnam.TransliterateAdvanced("|*vgcdc").GreedyTokenized[0].Word, "*നുമ്മ") assertEqual(t, varnam.TransliterateAdvanced("|*vg@cdc").GreedyTokenized[0].Word, "*നു@മ്മ") assertEqual(t, varnam.TransliterateAdvanced("|;|\"||*|'|-|>|\\^4^k").GreedyTokenized[0].Word, ";\"|*'->\\₹^ക") // TestMLInscript some complex words assertEqual(t, varnam.TransliterateAdvanced("Gh/aif;d;g").GreedyTokenized[0].Word, "ഉപയോഗിച്ചു") assertEqual(t, varnam.TransliterateAdvanced(";a/d;d;eclf").GreedyTokenized[0].Word, "ചോയ്ച്ചാമതി") // TestMLInscript fancy words assertEqual(t, varnam.TransliterateAdvanced("leeeeUdkd/t").GreedyTokenized[0].Word, "താാാാങ്ക്യൂ") } // func TestMLInscriptLearn(t *testing.T) { // varnam := getVarnamInstance("ml-inscript") // // Non language word. Should give error // assertEqual(t, varnam.Learn("Шаблон", 0) != nil, true) // // Before learning // assertEqual(t, varnam.TransliterateAdvanced("malayalam").TokenizerSuggestions[0].Word, "മലയലം") // err := varnam.Learn("മലയാളം", 0) // checkError(err) // // After learning // assertEqual(t, varnam.TransliterateAdvanced("malayalam").ExactMatches[0].Word, "മലയാളം") // assertEqual(t, varnam.TransliterateAdvanced("malayalaththil").DictionarySuggestions[0].Word, "മലയാളത്തിൽ") // assertEqual(t, varnam.TransliterateAdvanced("malayaalar").DictionarySuggestions[0].Word, "മലയാളർ") // assertEqual(t, varnam.TransliterateAdvanced("malaykk").DictionarySuggestions[0].Word, "മലയ്ക്ക്") // start := time.Now().UTC() // err = varnam.Learn("മലയാളത്തിൽ", 0) // checkError(err) // end := time.Now().UTC() // start1SecondBefore := time.Date(start.Year(), start.Month(), start.Day(), start.Hour(), start.Minute(), start.Second()-1, 0, start.Location()) // end1SecondAfter := time.Date(end.Year(), end.Month(), end.Day(), end.Hour(), end.Minute(), end.Second()+1, 0, end.Location()) // // varnam.Debug(true) // sugs := varnam.TransliterateAdvanced("malayala").DictionarySuggestions // assertEqual(t, sugs[0], Suggestion{"മലയാളം", VARNAM_LEARNT_WORD_MIN_WEIGHT, sugs[0].LearnedOn}) // // Check the time learnt is right (UTC) ? // learnedOn := time.Unix(int64(sugs[1].LearnedOn), 0) // if !learnedOn.After(start1SecondBefore) || !learnedOn.Before(end1SecondAfter) { // t.Errorf("Learn time %v (%v) not in between %v and %v", learnedOn, sugs[1].LearnedOn, start1SecondBefore, end1SecondAfter) // } // assertEqual(t, sugs[1], Suggestion{"മലയാളത്തിൽ", VARNAM_LEARNT_WORD_MIN_WEIGHT, sugs[1].LearnedOn}) // // Learn the word again // // This word will now be at the top // // TestMLInscript if weight has increased by one now // err = varnam.Learn("മലയാളത്തിൽ", 0) // checkError(err) // sug := varnam.TransliterateAdvanced("malayala").DictionarySuggestions[0] // assertEqual(t, sug, Suggestion{"മലയാളത്തിൽ", VARNAM_LEARNT_WORD_MIN_WEIGHT + 1, sug.LearnedOn}) // // Subsequent pattern can be smaller now (no need of "thth") // assertEqual(t, varnam.TransliterateAdvanced("malayalathil").ExactMatches[0].Word, "മലയാളത്തിൽ") // // Try words with symbols that have many possibilities // // thu has 12 possibilties // err = varnam.Learn("തുടങ്ങി", 0) // checkError(err) // assertEqual(t, varnam.TransliterateAdvanced("thudangiyittE").DictionarySuggestions[0].Word, "തുടങ്ങിയിട്ടേ") // } // func TestMLInscriptTrain(t *testing.T) { // varnam := getVarnamInstance("ml-inscript") // assertEqual(t, varnam.TransliterateAdvanced("india").TokenizerSuggestions[0].Word, "ഇന്ദി") // assertEqual(t, len(varnam.TransliterateAdvanced("india").PatternDictionarySuggestions), 0) // err := varnam.Train("india", "ഇന്ത്യ") // checkError(err) // assertEqual(t, varnam.TransliterateAdvanced("india").ExactMatches[0].Word, "ഇന്ത്യ") // assertEqual(t, varnam.TransliterateAdvanced("indiayil").PatternDictionarySuggestions[0].Word, "ഇന്ത്യയിൽ") // // Word with virama at end // assertEqual(t, varnam.TransliterateAdvanced("college").TokenizerSuggestions[0].Word, "കൊല്ലെഗെ") // assertEqual(t, len(varnam.TransliterateAdvanced("college").PatternDictionarySuggestions), 0) // err = varnam.Train("college", "കോളേജ്") // checkError(err) // assertEqual(t, varnam.TransliterateAdvanced("college").ExactMatches[0].Word, "കോളേജ്") // assertEqual(t, varnam.TransliterateAdvanced("collegeil").PatternDictionarySuggestions[0].Word, "കോളേജിൽ") // // TODO without e at the end // // assertEqual(t, varnam.TransliterateAdvanced("collegil").TokenizerSuggestions[0].Word, "കോളേജിൽ") // } // // TestMLInscript zero width joiner/non-joiner things // func TestMLInscriptZW(t *testing.T) { // varnam := getVarnamInstance("ml-inscript") // assertEqual(t, varnam.TransliterateAdvanced("thaazhvara").TokenizerSuggestions[0].Word, "താഴ്വര") // // _ is ZWNJ // assertEqual(t, varnam.TransliterateAdvanced("thaazh_vara").TokenizerSuggestions[0].Word, "താഴ്‌വര") // // When _ comes after a chil, varnam explicitly generates chil without ZWNJ at end // assertEqual(t, varnam.TransliterateAdvanced("n_").TokenizerSuggestions[0].Word, "ൻ") // assertEqual(t, varnam.TransliterateAdvanced("nan_ma").TokenizerSuggestions[0].Word, "നൻമ") // assertEqual(t, varnam.TransliterateAdvanced("sam_bhavam").TokenizerSuggestions[0].Word, "സംഭവം") // } // // TestMLInscript if zwj-chils are replaced with atomic chil // func TestMLInscriptAtomicChil(t *testing.T) { // varnam := getVarnamInstance("ml-inscript") // varnam.Train("professor", "പ്രൊഫസര്‍") // assertEqual(t, varnam.TransliterateAdvanced("professor").ExactMatches[0].Word, "പ്രൊഫസർ") // } govarnam-1.9.0/govarnam/govarnam_ml.go000066400000000000000000000015231420445125700200030ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ func (varnam *Varnam) mlPatternWordPartializer(sug *Suggestion) { lastChar, size := getLastCharacter(sug.Word) if lastChar == "ർ" { // റ because english words doesn't have ര sound sug.Word = sug.Word[0:len(sug.Word)-size] + "റ" } else if lastChar == "ൻ" { sug.Word = sug.Word[0:len(sug.Word)-size] + "ന" } else if lastChar == "ൽ" { sug.Word = sug.Word[0:len(sug.Word)-size] + "ല" } else if lastChar == "ൺ" { sug.Word = sug.Word[0:len(sug.Word)-size] + "ണ" } else if lastChar == "ൾ" { sug.Word = sug.Word[0:len(sug.Word)-size] + "ള" } else if lastChar == "ം" { sug.Word = sug.Word[0:len(sug.Word)-size] + "മ" } } govarnam-1.9.0/govarnam/govarnam_ml_test.go000066400000000000000000000441471420445125700210530ustar00rootroot00000000000000package govarnam import ( "context" "io/ioutil" "log" "path" "strings" "testing" "time" ) func TestMLGreedyTokenizer(t *testing.T) { varnam := getVarnamInstance("ml") assertEqual(t, varnam.TransliterateAdvanced("namaskaaram").GreedyTokenized[0].Word, "നമസ്കാരം") assertEqual(t, varnam.TransliterateAdvanced("malayalam").GreedyTokenized[0].Word, "മലയലം") } func TestMLTokenizer(t *testing.T) { varnam := getVarnamInstance("ml") // The order of this will fail if VST weights change expected := []string{"മല", "മള", "മലാ", "മളാ", "മാല", "മാള", "മാലാ", "മാളാ"} for i, sug := range varnam.TransliterateAdvanced("mala").TokenizerSuggestions { assertEqual(t, sug.Word, expected[i]) } // TestML non lang word nonLangWord := varnam.TransliterateAdvanced("Шаблон") assertEqual(t, len(nonLangWord.ExactWords), 0) assertEqual(t, len(nonLangWord.ExactMatches), 0) assertEqual(t, len(nonLangWord.DictionarySuggestions), 0) assertEqual(t, len(nonLangWord.PatternDictionarySuggestions), 0) assertEqual(t, len(nonLangWord.TokenizerSuggestions), 1) assertEqual(t, len(nonLangWord.GreedyTokenized), 1) // TestML mixed words assertEqual(t, varnam.TransliterateAdvanced("naമസ്കാരmenthuNt").GreedyTokenized[0].Word, "നമസ്കാരമെന്തുണ്ട്") assertEqual(t, varnam.TransliterateAdvanced("*namaskaaram").GreedyTokenized[0].Word, "*നമസ്കാരം") assertEqual(t, varnam.TransliterateAdvanced("*nama@skaaram").GreedyTokenized[0].Word, "*നമ@സ്കാരം") assertEqual(t, varnam.TransliterateAdvanced("*nama@skaaram%^&").GreedyTokenized[0].Word, "*നമ@സ്കാരം%^&") // TestML some complex words assertEqual(t, varnam.TransliterateAdvanced("kambyoottar").GreedyTokenized[0].Word, "കമ്പ്യൂട്ടർ") assertEqual(t, varnam.TransliterateAdvanced("kambyoottar").GreedyTokenized[0].Word, "കമ്പ്യൂട്ടർ") // TestML fancy words assertEqual(t, varnam.TransliterateAdvanced("thaaaaaaaankyoo").GreedyTokenized[0].Word, "താാാാങ്ക്യൂ") // Test weight value sugs := varnam.TransliterateAdvanced("thuthuru").TokenizerSuggestions assertEqual(t, sugs[0].Weight, 6) // തുതുരു. Greedy. Should have highest weight assertEqual(t, sugs[1].Weight, 4) // തുതുറു. Last conjunct is VARNAM_MATCH_POSSIBILITY symbol assertEqual(t, sugs[7].Weight, 4) // തുത്തുറു. Last 2 conjuncts are VARNAM_MATCH_POSSIBILITY symbols } func TestMLLearn(t *testing.T) { varnam := getVarnamInstance("ml") // Non language word. Should give error assertEqual(t, varnam.Learn("Шаблон", 0) != nil, true) // Varnam will find the first word to find. Here it will be just "ഉ". // Since it's single conjunct, will produce an error assertEqual(t, varnam.Learn("ഉaള്ളിൽ", 0) != nil, true) assertEqual(t, varnam.Learn("Шаблонഉള്ളിൽ", 0) != nil, true) assertEqual(t, varnam.Learn("വ...", 0) != nil, true) // Before learning assertEqual(t, varnam.TransliterateAdvanced("malayalam").TokenizerSuggestions[0].Word, "മലയലം") err := varnam.Learn("മലയാളം", 0) checkError(err) // After learning result := varnam.TransliterateAdvanced("malayalam") assertEqual(t, result.ExactWords[0].Word, "മലയാളം") assertEqual(t, len(result.ExactMatches), 0) assertEqual(t, varnam.TransliterateAdvanced("malayalaththil").DictionarySuggestions[0].Word, "മലയാളത്തിൽ") assertEqual(t, varnam.TransliterateAdvanced("malayaalar").DictionarySuggestions[0].Word, "മലയാളർ") assertEqual(t, varnam.TransliterateAdvanced("malaykk").DictionarySuggestions[0].Word, "മലയ്ക്ക്") // Test exact matches result = varnam.TransliterateAdvanced("malaya") assertEqual(t, len(result.ExactWords), 0) assertEqual(t, result.ExactMatches[0].Word, "മലയ") assertEqual(t, result.ExactMatches[1].Word, "മലയാ") assertEqual(t, result.DictionarySuggestions[0].Word, "മലയാളം") assertEqual(t, len(result.PatternDictionarySuggestions), 0) start := time.Now().UTC() err = varnam.Learn("മലയാളത്തിൽ", 0) checkError(err) end := time.Now().UTC() start1SecondBefore := time.Date(start.Year(), start.Month(), start.Day(), start.Hour(), start.Minute(), start.Second()-1, 0, start.Location()) end1SecondAfter := time.Date(end.Year(), end.Month(), end.Day(), end.Hour(), end.Minute(), end.Second()+1, 0, end.Location()) // varnam.Debug(true) sugs := varnam.TransliterateAdvanced("malayala").DictionarySuggestions assertEqual(t, sugs[0], Suggestion{"മലയാളം", VARNAM_LEARNT_WORD_MIN_WEIGHT, sugs[0].LearnedOn}) // Check the time learnt is right (UTC) ? learnedOn := time.Unix(int64(sugs[1].LearnedOn), 0) if !learnedOn.After(start1SecondBefore) || !learnedOn.Before(end1SecondAfter) { t.Errorf("Learn time %v (%v) not in between %v and %v", learnedOn, sugs[1].LearnedOn, start1SecondBefore, end1SecondAfter) } assertEqual(t, sugs[1], Suggestion{"മലയാളത്തിൽ", VARNAM_LEARNT_WORD_MIN_WEIGHT, sugs[1].LearnedOn}) // Learn the word again // This word will now be at the top // Test if weight has increased by one now err = varnam.Learn("മലയാളത്തിൽ", 0) checkError(err) sug := varnam.TransliterateAdvanced("malayala").DictionarySuggestions[0] assertEqual(t, sug, Suggestion{"മലയാളത്തിൽ", VARNAM_LEARNT_WORD_MIN_WEIGHT + 1, sug.LearnedOn}) // Subsequent pattern can be smaller now (no need of "thth") assertEqual(t, varnam.TransliterateAdvanced("malayalathil").ExactWords[0].Word, "മലയാളത്തിൽ") // Try words with symbols that have many possibilities // thu has 12 possibilties err = varnam.Learn("തുടങ്ങി", 0) checkError(err) assertEqual(t, varnam.TransliterateAdvanced("thudangiyittE").DictionarySuggestions[0].Word, "തുടങ്ങിയിട്ടേ") // Shouldn't learn single conjucnts as a word. Should give error assertEqual(t, varnam.Learn("കാ", 0) != nil, true) // Test unlearn varnam.Unlearn("തുടങ്ങി") assertEqual(t, len(varnam.TransliterateAdvanced("thudangiyittE").DictionarySuggestions), 0) } func TestMLTrain(t *testing.T) { varnam := getVarnamInstance("ml") assertEqual(t, varnam.TransliterateAdvanced("india").TokenizerSuggestions[0].Word, "ഇന്ദി") assertEqual(t, len(varnam.TransliterateAdvanced("india").PatternDictionarySuggestions), 0) err := varnam.Train("india", "ഇന്ത്യ") checkError(err) assertEqual(t, varnam.TransliterateAdvanced("india").ExactWords[0].Word, "ഇന്ത്യ") assertEqual(t, varnam.TransliterateAdvanced("ind").PatternDictionarySuggestions[0].Word, "ഇന്ത്യ") assertEqual(t, varnam.TransliterateAdvanced("indiayil").PatternDictionarySuggestions[0].Word, "ഇന്ത്യയിൽ") // Word with virama at end assertEqual(t, varnam.TransliterateAdvanced("college").TokenizerSuggestions[0].Word, "കൊല്ലെഗെ") assertEqual(t, len(varnam.TransliterateAdvanced("college").PatternDictionarySuggestions), 0) err = varnam.Train("college", "കോളേജ്") checkError(err) assertEqual(t, varnam.TransliterateAdvanced("college").ExactWords[0].Word, "കോളേജ്") assertEqual(t, varnam.TransliterateAdvanced("collegeil").PatternDictionarySuggestions[0].Word, "കോളേജിൽ") // TODO without e at the end // assertEqual(t, varnam.TransliterateAdvanced("collegil").TokenizerSuggestions[0].Word, "കോളേജിൽ") // Word with chil at end err = varnam.Train("computer", "കമ്പ്യൂട്ടർ") checkError(err) // This used to be an issue in libvarnam https://github.com/varnamproject/libvarnam/issues/166 // GoVarnam don't have this issue because we don't use pattern_content DB for malayalam words. // So the problem exist for english words in pattern_content err = varnam.Train("kilivaathil", "കിളിവാതിൽ") checkError(err) assertEqual(t, varnam.TransliterateAdvanced("computeril").PatternDictionarySuggestions[0].Word, "കമ്പ്യൂട്ടറിൽ") assertEqual(t, varnam.TransliterateAdvanced("kilivaathilil").PatternDictionarySuggestions[0].Word, "കിളിവാതിലിൽ") err = varnam.Train("chrome", "ക്രോം") checkError(err) assertEqual(t, varnam.TransliterateAdvanced("chromeil").PatternDictionarySuggestions[0].Word, "ക്രോമിൽ") // Unlearning should remove pattern from DB too varnam.Unlearn("കോളേജ്") assertEqual(t, len(varnam.TransliterateAdvanced("collegeil").PatternDictionarySuggestions), 0) // Unlearn by pattern english varnam.Unlearn("computer") assertEqual(t, len(varnam.TransliterateAdvanced("computeril").PatternDictionarySuggestions), 0) err = varnam.Unlearn("computer") assertEqual(t, err.Error(), "nothing to unlearn") } // TestML zero width joiner/non-joiner things func TestMLZW(t *testing.T) { varnam := getVarnamInstance("ml") assertEqual(t, varnam.TransliterateAdvanced("thaazhvara").TokenizerSuggestions[0].Word, "താഴ്വര") // _ is ZWNJ assertEqual(t, varnam.TransliterateAdvanced("thaazh_vara").TokenizerSuggestions[0].Word, "താഴ്‌വര") // When _ comes after a chil in between a word, varnam explicitly generates chil. This chil won't have a ZWNJ at end assertEqual(t, varnam.TransliterateAdvanced("nan_ma").TokenizerSuggestions[0].Word, "നൻമ") assertEqual(t, varnam.TransliterateAdvanced("sam_bhavam").TokenizerSuggestions[0].Word, "സംഭവം") } // TestML if zwj-chils are replaced with atomic chil func TestMLAtomicChil(t *testing.T) { varnam := getVarnamInstance("ml") err := varnam.Train("professor", "പ്രൊഫസര്‍") checkError(err) assertEqual(t, varnam.TransliterateAdvanced("professor").ExactWords[0].Word, "പ്രൊഫസർ") } func TestMLReverseTransliteration(t *testing.T) { varnam := getVarnamInstance("ml") oldLimit := varnam.TokenizerSuggestionsLimit varnam.TokenizerSuggestionsLimit = 30 sugs, err := varnam.ReverseTransliterate("മലയാളം") checkError(err) // The order of this will fail if VST weights change expected := []string{"malayaaLam", "malayaaLam_", "malayALam", "malayALam_", "malayaalam", "malayaalam_", "malayAlam", "malayAlam_", "malayaLam", "malayaLam_", "malayalam", "malayalam_"} assertEqual(t, len(sugs), len(expected)) for i, expectedWord := range expected { assertEqual(t, sugs[i].Word, expectedWord) } sugs, err = varnam.ReverseTransliterate("2019 ഏപ്രിൽ 17-ന് മലയാളം വിക്കിപീഡിയയിലെ ലേഖനങ്ങളുടെ എണ്ണം 63,000 പിന്നിട്ടു.") assertEqual(t, sugs[0].Word, "2019 Epril 17-n~ malayaaLam vikkipeeDiyayile lEkhanangaLuTe eNNam 63,000 pinnittu.") varnam.TokenizerSuggestionsLimit = oldLimit } func TestDictionaryLimit(t *testing.T) { varnam := getVarnamInstance("ml") words := []string{"മല", "മലയോരം", "മലയാളചലച്ചിത്രം", "മലപ്പുറം", "മലയാളത്തിൽ", "മലയ്ക്ക്", "മലയിൽ", "മലയാളം"} for _, word := range words { varnam.Learn(word, 0) } varnam.DictionarySuggestionsLimit = 2 assertEqual(t, len(varnam.TransliterateAdvanced("mala").DictionarySuggestions), 2) patternsAndWords := map[string]string{ "collateral": "കോലാറ്ററൽ", "collective": "കളക്ടീവ്", "collector": "കളക്ടർ", "college": "കോളേജ്", "colombia": "കൊളംബിയ", "commons": "കോമൺസ്", } for pattern, word := range patternsAndWords { varnam.Train(pattern, word) } varnam.PatternDictionarySuggestionsLimit = 4 assertEqual(t, len(varnam.TransliterateAdvanced("co").PatternDictionarySuggestions), 4) // Test multiple matching words while partializing patternsAndWords = map[string]string{ "edit": "എഡിറ്റ്", "editing": "എഡിറ്റിംഗ്", "edition": "എഡിഷൻ", } for pattern, word := range patternsAndWords { varnam.Train(pattern, word) } varnam.PatternDictionarySuggestionsLimit = 2 // Tokenizer will work on 2 words: എഡിറ്റ് & എഡിറ്റിംഗ് // Total results = 4+ assertEqual(t, len(varnam.TransliterateAdvanced("editingil").PatternDictionarySuggestions), 2) } func TestMLLearnFromFile(t *testing.T) { varnam := getVarnamInstance("ml") // CC BY-SA 3.0 licensed // https://ml.wikipedia.org/wiki/National_parks_of_Taiwan filePath := makeFile("text.txt", "തായ്‌വാനിലെ ദേശീയോദ്യാനങ്ങൾ സംരക്ഷിതപ്രദേശങ്ങളാണ്. 7,489.49 ചതുരശ്ര കിലോമീറ്റർ (2,891.71 sq mi) വിസ്തീർണ്ണത്തിൽ വ്യാപിച്ചുകിടക്കുന്ന ഒൻപത് ദേശീയോദ്യാനങ്ങളാണ് ഇവിടെയുള്ളത്. എല്ലാ ദേശീയോദ്യാനങ്ങളും മിനിസ്ട്രി ഓഫ് ദ ഇന്റീരിയർ ഭരണത്തിൻകീഴിലാണ് നിലനിൽക്കുന്നത്. 1937-ൽ തായ്‌വാനിലെ ജാപ്പനീസ് ഭരണത്തിൻ കീഴിലായിരുന്നു ആദ്യത്തെ ദേശീയോദ്യാനം നിലവിൽവന്നത്.") varnam.LearnFromFile(filePath) assertEqual(t, len(varnam.TransliterateAdvanced("thaay_vaanile").ExactWords) != 0, true) // Try learning from a frequency report filePath = makeFile("report.txt", ` നിത്യഹരിത 120 വൃക്ഷമാണ് 89 ഒരേയൊരു 45 ഏഷ്യയുടെ 100 മേലാപ്പും 12 aadc 10 `, ) learnStatus, err := varnam.LearnFromFile(filePath) checkError(err) assertEqual(t, learnStatus.TotalWords, 6) assertEqual(t, learnStatus.FailedWords, 1) assertEqual(t, varnam.TransliterateAdvanced("nithyaharitha").ExactWords[0].Weight, 120) assertEqual(t, varnam.TransliterateAdvanced("melaappum").ExactWords[0].Weight, 12) } func TestMLTrainFromFile(t *testing.T) { varnam := getVarnamInstance("ml") // Try learning from a frequency report filePath := makeFile("patterns.txt", ` kunnamkulam കുന്നംകുളം mandalamkunnu മന്ദലാംകുന്ന് something aadc `, ) learnStatus, err := varnam.TrainFromFile(filePath) checkError(err) assertEqual(t, learnStatus.TotalWords, 3) assertEqual(t, learnStatus.FailedWords, 1) assertEqual(t, varnam.TransliterateAdvanced("mandalamkunnu").ExactWords[0].Word, "മന്ദലാംകുന്ന്") assertEqual(t, len(varnam.TransliterateAdvanced("something").ExactWords), 0) } func TestMLExportAndImport(t *testing.T) { varnam := getVarnamInstance("ml") words := []WordInfo{ WordInfo{0, "മനുഷ്യൻ", 0, 0}, WordInfo{0, "മണ്ഡലം", 0, 0}, WordInfo{0, "മിലാൻ", 0, 0}, } varnam.LearnMany(words) exportFileIntendedPath := path.Join(testTempDir, "export") exportFilePath := exportFileIntendedPath + "-1.vlf" varnam.Export(exportFileIntendedPath, 300) // read the whole file at once b, err := ioutil.ReadFile(exportFilePath) if err != nil { panic(err) } exportFileContents := string(b) for _, wordInfo := range words { assertEqual(t, strings.Contains(exportFileContents, wordInfo.word), true) // Unlearn so that we can import next varnam.Unlearn(wordInfo.word) } varnam.Import(exportFilePath) for _, wordInfo := range words { results := varnam.searchDictionary(context.Background(), []string{wordInfo.word}, searchMatches) assertEqual(t, len(results) > 0, true) } // Test if importing file with a JSON work filePath := makeFile("custom.json", ` { "words": [ { "w": "അൾജീരിയ", "c": 25, "l": 1531131220 } ], "patterns": [ { "p": "algeria", "w": "അൾജീരിയ" } ] } `) varnam.Import(filePath) assertEqual(t, varnam.TransliterateAdvanced("algeria").ExactWords[0], Suggestion{ Word: "അൾജീരിയ", Weight: VARNAM_LEARNT_WORD_MIN_WEIGHT + 25, LearnedOn: 1531131220, }) } func TestMLSearchSymbolTable(t *testing.T) { varnam := getVarnamInstance("ml") search := NewSearchSymbol() search.Value1 = "ക" results, err := varnam.SearchSymbolTable(context.Background(), search) checkError(err) for _, result := range results { assertEqual(t, result.Value1, "ക") } search.Value1 = "LIKE ക%" search.Pattern = "ka" results, err = varnam.SearchSymbolTable(context.Background(), search) checkError(err) assertEqual(t, results[0].Value1, "ക") assertEqual(t, results[1].Value1, "കാ") } func TestMLDictionaryMatchExact(t *testing.T) { varnam := getVarnamInstance("ml") varnam.DictionaryMatchExact = true varnam.Learn("പനിയിൽ", 0) varnam.Learn("പണിയിൽ", 0) result := varnam.TransliterateAdvanced("pani") assertEqual(t, len(result.DictionarySuggestions), 1) varnam.DictionaryMatchExact = false } func TestMLRecentlyLearnedWords(t *testing.T) { varnam := getVarnamInstance("ml") words := []string{"ആലപ്പുഴ", "എറണാകുളം", "തൃശ്ശൂർ", "പാലക്കാട്", "കോഴിക്കോട്"} for _, word := range words { varnam.Learn(word, 0) } result, err := varnam.GetRecentlyLearntWords(context.Background(), 0, len(words)) checkError(err) assertEqual(t, len(result), len(words)) log.Println(result, words) for i, sug := range result { assertEqual(t, sug.Word, words[len(words)-i-1]) } result, err = varnam.GetRecentlyLearntWords(context.Background(), 4, len(words)) assertEqual(t, result[0].Word, "ആലപ്പുഴ") } func TestMLGetSuggestions(t *testing.T) { varnam := getVarnamInstance("ml") words := []string{"ആലപ്പുഴ", "ആലം", "ആലാപനം"} for _, word := range words { varnam.Learn(word, 0) } varnam.DictionarySuggestionsLimit = 5 result := varnam.GetSuggestions(context.Background(), "ആല") assertEqual(t, len(result), 3) assertEqual(t, result[0].Word, "ആലപ്പുഴ") } govarnam-1.9.0/govarnam/govarnam_test.go000066400000000000000000000042361420445125700203560ustar00rootroot00000000000000package govarnam import ( "io/ioutil" "log" "os" "path" "reflect" "runtime/debug" "sync" "testing" ) var varnamInstances = map[string]*Varnam{} var mutex = sync.RWMutex{} var testTempDir string // AssertEqual checks if values are equal // Thanks https://gist.github.com/samalba/6059502#gistcomment-2710184 func assertEqual(t *testing.T, value interface{}, expected interface{}) { if value == expected { return } debug.PrintStack() t.Errorf("Received %v (type %v), expected %v (type %v)", value, reflect.TypeOf(value), expected, reflect.TypeOf(expected)) } func checkError(err error) { if err != nil { log.Panic(err) } } func makeFile(name string, contents string) string { filePath := path.Join(testTempDir, name) file, err := os.Create(filePath) if err != nil { log.Println(err) return "" } defer file.Close() file.WriteString(contents) return filePath } func setUp(schemeID string) { SetLearningsDir(testTempDir) varnam, err := InitFromID(schemeID) checkError(err) mutex.Lock() varnamInstances[schemeID] = varnam mutex.Unlock() } func getVarnamInstance(schemeID string) *Varnam { mutex.Lock() instance, ok := varnamInstances[schemeID] mutex.Unlock() if ok { return instance } log.Fatalf("Varnam instance for %s not found", schemeID) return nil } func tearDownVarnam(schemeID string) { getVarnamInstance(schemeID).Close() } func tearDown() { os.RemoveAll(testTempDir) } func TestEnv(t *testing.T) { // Making a dummy VST file makeFile("ml.vst", "dummy") prevEnvValue := os.Getenv("VARNAM_VST_DIR") SetVSTLookupDir(testTempDir) _, err := InitFromID("ml") assertEqual(t, err != nil, true) SetVSTLookupDir(prevEnvValue) _, err = InitFromID("ml") checkError(err) assertEqual(t, fileExists(path.Join(testTempDir, "ml.vst.learnings")), true) } func TestMain(m *testing.M) { schemeDetails, err := GetAllSchemeDetails() if err != nil { log.Fatal(err) } testTempDir, err = ioutil.TempDir("", "govarnam_test") checkError(err) for _, schemeDetail := range schemeDetails { setUp(schemeDetail.Identifier) } m.Run() for _, schemeDetail := range schemeDetails { tearDownVarnam(schemeDetail.Identifier) } tearDown() } govarnam-1.9.0/govarnam/learn.go000066400000000000000000000416241420445125700166100ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "bufio" "context" sql "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "math" "os" "strconv" "strings" "time" "github.com/mattn/go-sqlite3" ) // WordInfo represent a item in words table type WordInfo struct { id int word string weight int learnedOn int } // LearnStatus output of bulk learn type LearnStatus struct { TotalWords int FailedWords int } // Learnings file export format type exportFormat struct { WordsDict []map[string]interface{} `json:"words"` PatternsDict []map[string]interface{} `json:"patterns"` } func (varnam *Varnam) languageSpecificSanitization(word string) string { if varnam.SchemeDetails.LangCode == "ml" { /* Malayalam has got two ways to write chil letters. Converting the old style to new atomic chil one */ word = strings.Replace(word, "ന്‍", "ൻ", -1) word = strings.Replace(word, "ണ്‍", "ൺ", -1) word = strings.Replace(word, "ല്‍", "ൽ", -1) word = strings.Replace(word, "ള്‍", "ൾ", -1) word = strings.Replace(word, "ര്‍", "ർ", -1) } if varnam.SchemeDetails.LangCode == "hi" { /* Hindi's DANDA (Purna viram) */ word = strings.Replace(word, "।", "", -1) } return word } // Sanitize a word, remove unwanted characters before learning func (varnam *Varnam) sanitizeWord(word string) string { // Remove leading & trailing whitespaces word = strings.TrimSpace(word) word = varnam.languageSpecificSanitization(word) // Remove leading ZWJ & ZWNJ firstChar, size := getFirstCharacter(word) if firstChar == ZWJ || firstChar == ZWNJ { word = word[size:] } // Remove trailing ZWNJ lastChar, size := getLastCharacter(word) if lastChar == ZWNJ { word = word[0 : len(word)-size] } return word } // Learn a word. If already exist, increases weight func (varnam *Varnam) Learn(word string, weight int) error { word = varnam.sanitizeWord(word) conjuncts := varnam.splitWordByConjunct(word) if len(conjuncts) == 0 { return fmt.Errorf("Nothing to learn") } if len(conjuncts) == 1 { return fmt.Errorf("Can't learn a single conjunct") } // reconstruct word word = strings.Join(conjuncts, "") if weight == 0 { weight = VARNAM_LEARNT_WORD_MIN_WEIGHT - 1 } query := "INSERT OR IGNORE INTO words(word, weight, learned_on) VALUES (trim(?), ?, strftime('%s', 'now'))" bgContext := context.Background() ctx, cancelFunc := context.WithTimeout(bgContext, 5*time.Second) defer cancelFunc() stmt, err := varnam.dictConn.PrepareContext(ctx, query) if err != nil { return err } defer stmt.Close() _, err = stmt.ExecContext(ctx, word, weight) if err != nil { return err } query = "UPDATE words SET weight = weight + 1, learned_on = strftime('%s', 'now') WHERE word = ?" ctx, cancelFunc = context.WithTimeout(bgContext, 5*time.Second) defer cancelFunc() stmt, err = varnam.dictConn.PrepareContext(ctx, query) if err != nil { return err } defer stmt.Close() _, err = stmt.ExecContext(ctx, word) if err != nil { return err } return nil } // Unlearn a word, remove from words DB and pattern if there is func (varnam *Varnam) Unlearn(word string) error { conjuncts := varnam.splitWordByConjunct(strings.TrimSpace(word)) if len(conjuncts) == 0 { // Word must be english ? See if that's the case stmt, err := varnam.dictConn.Prepare("DELETE FROM patterns WHERE pattern = ?") if err != nil { return err } defer stmt.Close() result, err := stmt.Exec(word) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return fmt.Errorf("nothing to unlearn") } return nil } varnam.dictConn.Exec("PRAGMA foreign_keys = ON") query := "DELETE FROM words WHERE word = ?" stmt, err := varnam.dictConn.Prepare(query) if err != nil { return err } defer stmt.Close() _, err = stmt.Exec(word) if err != nil { return err } // No need to remove from `patterns` since FOREIGN KEY ON DELETE CASCADE will work if varnam.Debug { fmt.Printf("Removed %s\n", word) } varnam.dictConn.Exec("PRAGMA foreign_keys = OFF") return nil } // LearnMany words in bulk. Faster learning func (varnam *Varnam) LearnMany(words []WordInfo) (LearnStatus, error) { var ( insertionValues []string insertionArgs []interface{} updationValues []string updationArgs []interface{} learnStatus LearnStatus = LearnStatus{len(words), 0} ) for _, wordInfo := range words { word := varnam.sanitizeWord(wordInfo.word) weight := wordInfo.weight conjuncts := varnam.splitWordByConjunct(word) if len(conjuncts) == 0 { log.Printf("Nothing to learn from %s", word) learnStatus.FailedWords++ continue } if len(conjuncts) == 1 { log.Printf("Can't learn a single conjunct: %s", word) learnStatus.FailedWords++ continue } // reconstruct word word = strings.Join(conjuncts, "") // We have a weight + 1 in SQL query later if weight == 0 { weight = VARNAM_LEARNT_WORD_MIN_WEIGHT - 1 } else { weight-- } insertionValues = append(insertionValues, "(trim(?), ?, strftime('%s', 'now'))") insertionArgs = append(insertionArgs, word, weight) updationValues = append(updationValues, "word = ?") updationArgs = append(updationArgs, word) } if len(insertionArgs) == 0 { return learnStatus, nil } query := fmt.Sprintf( "INSERT OR IGNORE INTO words(word, weight, learned_on) VALUES %s", strings.Join(insertionValues, ", "), ) stmt, err := varnam.dictConn.Prepare(query) if err != nil { return learnStatus, err } _, err = stmt.Exec(insertionArgs...) if err != nil { return learnStatus, err } // There is a limit on number of OR that can be done // Reference: https://stackoverflow.com/questions/9570197/sqlite-expression-maximum-depth-limit depthLimit := sqlite3Conn.GetLimit(sqlite3.SQLITE_LIMIT_EXPR_DEPTH) - 1 for len(updationValues) > 0 { lastIndex := int(math.Min(float64(depthLimit), float64(len(updationValues)))) query = "UPDATE words SET weight = weight + 1, learned_on = strftime('%s', 'now') WHERE " + strings.Join(updationValues[0:lastIndex], " OR ") stmt, err = varnam.dictConn.Prepare(query) if err != nil { return learnStatus, err } defer stmt.Close() _, err = stmt.Exec(updationArgs[0:lastIndex]...) if err != nil { return learnStatus, err } updationValues = updationValues[lastIndex:] updationArgs = updationArgs[lastIndex:] } return learnStatus, nil } // Train a word with a particular pattern. Pattern => word func (varnam *Varnam) Train(pattern string, word string) error { word = varnam.sanitizeWord(word) err := varnam.Learn(word, 0) if err != nil { return err } wordInfo, err := varnam.getWordInfo(word) if wordInfo == nil { return fmt.Errorf("Word %s couldn't be inserted (%s)", word, err.Error()) } ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) defer cancelFunc() query := "INSERT OR IGNORE INTO patterns(pattern, word_id) VALUES (?, ?)" stmt, err := varnam.dictConn.PrepareContext(ctx, query) if err != nil { return err } defer stmt.Close() _, err = stmt.ExecContext(ctx, pattern, wordInfo.id) if err != nil { return err } return nil } func (varnam *Varnam) getWordInfo(word string) (*WordInfo, error) { rows, err := varnam.dictConn.Query("SELECT id, weight, learned_on FROM words WHERE word = ?", word) if err != nil { return nil, err } defer rows.Close() var wordInfo WordInfo wordExists := false for rows.Next() { // This loop will only work if there is a word wordExists = true rows.Scan(&wordInfo.id, &wordInfo.weight, &wordInfo.learnedOn) } if wordExists { return &wordInfo, nil } return nil, fmt.Errorf("Word doesn't exist") } // LearnFromFile Learn all words in a file func (varnam *Varnam) LearnFromFile(filePath string) (LearnStatus, error) { learnStatus := LearnStatus{0, 0} file, err := os.Open(filePath) if err != nil { return learnStatus, err } defer file.Close() limitVariableNumber := sqlite3Conn.GetLimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) log.Printf("default SQLITE_LIMIT_VARIABLE_NUMBER: %d", limitVariableNumber) // We have 2 fields per item, word and weight insertsPerTransaction := int(float64(limitVariableNumber) / 2) // io.Reader is a stream, so only one time iteration possible scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanWords) // First, see if this is a frequency report file // A frequency report file has the format : // word frequency // Here the frequency will be the weight frequencyReport := false fileFormatDetermined := false var words []WordInfo word := "" insertions := 0 count := 0 for scanner.Scan() { curWord := scanner.Text() if !fileFormatDetermined { // Check the first 2 words. If it's of format // Then treat rest of words as frequency report // Set the first word if count == 0 { word = curWord count++ continue } // Then check the next word to see if it's a number weight, err := strconv.Atoi(curWord) if err == nil { // It's a number. It is a frequency report frequencyReport = true words = append(words, WordInfo{0, word, weight, 0}) word = "" // count is now 1 } else { // Second word is not a number but a string. // Not a frequency report, so attempt to learn those 2 words words = append(words, WordInfo{0, word, 0, 0}) words = append(words, WordInfo{0, curWord, 0, 0}) count++ } fileFormatDetermined = true if varnam.Debug { fmt.Println("Frequency report :", frequencyReport) } } else if frequencyReport { number, numberErr := strconv.Atoi(curWord) if word == "" { // Sometimes word will be characters like <0xa0> // which won't be detected by Go's bufio.ScanWords if numberErr != nil { word = curWord } continue } else { if numberErr == nil { words = append(words, WordInfo{0, word, number, 0}) count++ } word = "" } } else { words = append(words, WordInfo{0, curWord, 0, 0}) count++ } if count == insertsPerTransaction { learnStatusBatch, err := varnam.LearnMany(words) if err != nil { return learnStatus, err } learnStatus.TotalWords += learnStatusBatch.TotalWords learnStatus.FailedWords += learnStatusBatch.FailedWords insertions += learnStatusBatch.TotalWords count = 0 words = []WordInfo{} fmt.Printf("Processed %d words\n", insertions) } } if len(words) != 0 { learnStatusBatch, err := varnam.LearnMany(words) if err != nil { return learnStatus, err } learnStatus.TotalWords += learnStatusBatch.TotalWords learnStatus.FailedWords += learnStatusBatch.FailedWords insertions += len(words) fmt.Printf("Processed %d words\n", insertions) } if err := scanner.Err(); err != nil { return learnStatus, err } return learnStatus, nil } // TrainFromFile Train words with a particular pattern in bulk func (varnam *Varnam) TrainFromFile(filePath string) (LearnStatus, error) { // The file should have the format : // pattern word // The separation between pattern and word should just be a single whitespace learnStatus := LearnStatus{0, 0} file, err := os.Open(filePath) if err != nil { return learnStatus, err } defer file.Close() scanner := bufio.NewScanner(file) lineCount := 0 for scanner.Scan() { line := scanner.Text() wordsInLine := strings.Fields(line) if len(wordsInLine) == 2 { learnStatus.TotalWords++ err := varnam.Train(wordsInLine[0], wordsInLine[1]) if err != nil { learnStatus.FailedWords++ fmt.Printf("Couldn't train %s => %s (%s) \n", wordsInLine[0], wordsInLine[1], err.Error()) } } else if lineCount > 2 { fmt.Printf("Line %d is not in correct format \n", lineCount+1) } lineCount++ if lineCount%500 == 0 { fmt.Printf("Trained %d words\n", lineCount) } } if err := scanner.Err(); err != nil { return learnStatus, err } return learnStatus, nil } // Get full data from DB func rowsToJSON(rows *sql.Rows) ([]map[string]interface{}, error) { // Dumping rows from SQL to JSON // Thanks lucidquiet https://stackoverflow.com/a/17885636/1372424 // Thanks turkenh https://stackoverflow.com/a/29164115/1372424 // Licensed CC-BY-SA 4.0 columns, err := rows.Columns() if err != nil { return nil, err } count := len(columns) tableData := make([]map[string]interface{}, 0) values := make([]interface{}, count) valuePtrs := make([]interface{}, count) for rows.Next() { for i := 0; i < count; i++ { valuePtrs[i] = &values[i] } rows.Scan(valuePtrs...) entry := make(map[string]interface{}) for i, col := range columns { var v interface{} val := values[i] b, ok := val.([]byte) if ok { v = string(b) } else { v = val } entry[col] = v } tableData = append(tableData, entry) } return tableData, nil } // Export learnings as JSON to a file func (varnam *Varnam) Export(filePath string, wordsPerFile int) error { if fileExists(filePath) { return fmt.Errorf("Output file already exists") } patternsCount := -1 wordsCount := -1 countRows, err := varnam.dictConn.Query("SELECT COUNT(*) AS patternsCount FROM patterns UNION SELECT COUNT(*) AS wordsCount FROM words") if err != nil { return err } defer countRows.Close() for countRows.Next() { if patternsCount == -1 { countRows.Scan(&patternsCount) } else { countRows.Scan(&wordsCount) } } totalPages := int(math.Ceil(float64(wordsCount) / float64(wordsPerFile))) if varnam.Debug { log.Printf("Words: %d. Patterns: %d", wordsCount, patternsCount) log.Printf("Pages: %d", totalPages) } page := 1 for page <= totalPages { wordsTableQuery := fmt.Sprintf("SELECT word AS w, weight AS c, learned_on AS l FROM words ORDER BY c DESC LIMIT %d OFFSET %d", wordsPerFile, (page-1)*wordsPerFile) wordsRows, err := varnam.dictConn.Query(wordsTableQuery) if err != nil { return err } defer wordsRows.Close() wordsData, err := rowsToJSON(wordsRows) patternsRows, err := varnam.dictConn.Query( ` SELECT pattern AS p, ( SELECT word FROM words WHERE words.id = patterns.word_id ) AS w FROM patterns WHERE patterns.word_id IN ( SELECT id FROM words WHERE word IN ( SELECT w FROM ( ` + wordsTableQuery + ` ) ) ) `, ) if err != nil { return err } defer patternsRows.Close() patternsData, err := rowsToJSON(patternsRows) output := exportFormat{wordsData, patternsData} jsonData, err := json.Marshal(output) filePathWithPageNumber := filePath + "-" + fmt.Sprint(page) + ".vlf" err = ioutil.WriteFile(filePathWithPageNumber, jsonData, 0644) if err != nil { return err } page++ } return nil } // Import learnings from file func (varnam *Varnam) Import(filePath string) error { if !fileExists(filePath) { return fmt.Errorf("Import file not found") } // TODO better reading of JSON. This loads entire file into memory fileContent, _ := ioutil.ReadFile(filePath) var dbData exportFormat if err := json.Unmarshal(fileContent, &dbData); err != nil { return fmt.Errorf("Parsing JSON failed, err: %s", err.Error()) } limitVariableNumber := sqlite3Conn.GetLimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) log.Printf("default SQLITE_LIMIT_VARIABLE_NUMBER: %d", limitVariableNumber) insertsPerTransaction := int(math.Min( float64(limitVariableNumber)/4, // We have 4 fields per item float64(len(dbData.WordsDict)), )) var ( args []interface{} values []string ) insertions := 0 count := 0 for i, item := range dbData.WordsDict { values = append(values, "(trim(?), ?, ?)") args = append(args, item["w"], item["c"], item["l"]) count++ if count == insertsPerTransaction || i == len(dbData.WordsDict)-1 { query := fmt.Sprintf( "INSERT OR IGNORE INTO words(word, weight, learned_on) VALUES %s", strings.Join(values, ", "), ) stmt, err := varnam.dictConn.Prepare(query) if err != nil { return err } _, err = stmt.Exec(args...) if err != nil { return err } args = nil values = nil insertions += count count = 0 fmt.Printf("Inserted %d words\n", insertions) } } args = nil values = nil insertsPerTransaction = int(math.Min( float64(limitVariableNumber)/2, // We have 2 fields per item float64(len(dbData.PatternsDict)), )) insertions = 0 count = 0 for i, item := range dbData.PatternsDict { values = append(values, "(?, (SELECT id FROM words WHERE word = ?))") args = append(args, item["p"], item["w"]) count++ if count == insertsPerTransaction || i == len(dbData.WordsDict)-1 { query := fmt.Sprintf( "INSERT OR IGNORE INTO patterns(pattern, word_id) VALUES %s", strings.Join(values, ", "), ) stmt, err := varnam.dictConn.Prepare(query) if err != nil { return err } _, err = stmt.Exec(args...) if err != nil { return err } args = nil values = nil insertions += count count = 0 fmt.Printf("Inserted %d patterns\n", insertions) } } return nil } govarnam-1.9.0/govarnam/migrate.go000066400000000000000000000042041420445125700171300ustar00rootroot00000000000000package govarnam import ( sql "database/sql" "io/fs" "strings" ) type migrate struct { db *sql.DB fs fs.FS } type migrationStatus struct { lastRun string lastMigration string } func InitMigrate(db *sql.DB, fs fs.FS) (*migrate, error) { _, err := db.Exec(` CREATE TABLE IF NOT EXISTS migrations ( id INTEGER PRIMARY KEY, name VARCHAR(200) ); `) if err != nil { return nil, err } return &migrate{db, fs}, nil } func (mg *migrate) Status() (*migrationStatus, error) { var lastRun string = "" mg.db.QueryRow("SELECT name FROM migrations ORDER BY id DESC LIMIT 1").Scan(&lastRun) files, err := fs.ReadDir(mg.fs, ".") if err != nil { return nil, err } lastMigration := files[len(files)-1].Name() return &migrationStatus{lastRun, lastMigration}, nil } func (mg *migrate) Run() (int, error) { ranMigrations := 0 status, err := mg.Status() if err != nil { return 0, err } if status.lastRun != status.lastMigration { ranMigrations, err = mg.runMigrations(status) if err != nil { return 0, err } } return ranMigrations, nil } func (mg *migrate) runMigrations(status *migrationStatus) (int, error) { files, err := fs.ReadDir(mg.fs, ".") if err != nil { return 0, err } ranMigrations := 0 // lastRun will be empty if no migrations have been run var foundLastRunMigration bool = (status.lastRun == "") for _, file := range files { fileNameParts := strings.Split(file.Name(), ".") migrationName := fileNameParts[0] // Run all migrations after the last ran migration if !foundLastRunMigration { foundLastRunMigration = (status.lastRun == migrationName) } else { fileContents, err := fs.ReadFile(mg.fs, file.Name()) if err != nil { return 0, err } tx, err := mg.db.Begin() if err != nil { return 0, err } _, err = tx.Exec(string(fileContents)) if err != nil { return 0, err } stmt, err := tx.Prepare("INSERT INTO migrations (name) VALUES(?)") if err != nil { tx.Rollback() return 0, err } _, err = stmt.Exec(migrationName) if err != nil { tx.Rollback() } tx.Commit() ranMigrations++ } } return ranMigrations, nil } govarnam-1.9.0/govarnam/migrate_test.go000066400000000000000000000022051420445125700201660ustar00rootroot00000000000000package govarnam import ( "database/sql" "embed" "io/fs" "testing" ) //go:embed testdata/*.sql var testdataFS embed.FS func TestMigration(t *testing.T) { db, err := sql.Open("sqlite3", ":memory:") checkError(err) testdataDirFS, err := fs.Sub(testdataFS, "testdata") checkError(err) dirFiles, err := fs.ReadDir(testdataDirFS, ".") checkError(err) mg, err := InitMigrate(db, testdataDirFS) checkError(err) _, err = db.Query("SELECT * FROM words") assertEqual(t, err != nil, true) ranMigrations, err := mg.Run() assertEqual(t, err, nil) assertEqual(t, ranMigrations, len(dirFiles)) _, err = db.Query("SELECT * FROM words") assertEqual(t, err, nil) // Part 2 : New Migrations _, err = db.Query("SELECT * FROM words_fts") assertEqual(t, err != nil, true) migrationsFS, err := fs.Sub(embedFS, "migrations") checkError(err) dirFiles, err = fs.ReadDir(migrationsFS, ".") checkError(err) mg, err = InitMigrate(db, migrationsFS) checkError(err) ranMigrations, err = mg.Run() assertEqual(t, err, nil) assertEqual(t, ranMigrations, len(dirFiles)) _, err = db.Query("SELECT * FROM words_fts") assertEqual(t, err, nil) } govarnam-1.9.0/govarnam/migrations/000077500000000000000000000000001420445125700173255ustar00rootroot00000000000000govarnam-1.9.0/govarnam/migrations/2021-04-10-init.sql000066400000000000000000000006341420445125700220350ustar00rootroot00000000000000CREATE TABLE IF NOT EXISTS metadata ( key TEXT UNIQUE, value TEXT ); CREATE TABLE IF NOT EXISTS words ( id INTEGER PRIMARY KEY, word TEXT UNIQUE, weight INTEGER DEFAULT 1, learned_on INTEGER ); CREATE TABLE IF NOT EXISTS patterns ( pattern TEXT NOT NULL COLLATE NOCASE, word_id INTEGER NOT NULL, FOREIGN KEY(word_id) REFERENCES words(id) ON DELETE CASCADE, PRIMARY KEY(pattern, word_id) ); govarnam-1.9.0/govarnam/migrations/2021-08-01-fts.sql000066400000000000000000000004531420445125700216710ustar00rootroot00000000000000-- Note: FTS can't be applied on patterns because -- we require partial word search which FTS doesn't support CREATE VIRTUAL TABLE IF NOT EXISTS words_fts USING FTS5( word, weight UNINDEXED, learned_on UNINDEXED, content='words', content_rowid='id', tokenize='ascii', prefix='1 2', );govarnam-1.9.0/govarnam/migrations/2022-02-20-add-fts-triggers.sql000066400000000000000000000012671420445125700242430ustar00rootroot00000000000000-- FTS Triggers was added on August 2021 but the delete triggers wasn't being executed -- https://github.com/varnamproject/govarnam/issues/24 CREATE TRIGGER IF NOT EXISTS words_ai AFTER INSERT ON words BEGIN INSERT INTO words_fts (rowid, word) VALUES (new.id, new.word); END; CREATE TRIGGER IF NOT EXISTS words_ad AFTER DELETE ON words BEGIN INSERT INTO words_fts (words_fts, rowid, word) VALUES ('delete', old.id, old.word); END; CREATE TRIGGER IF NOT EXISTS words_au AFTER UPDATE ON words BEGIN INSERT INTO words_fts (words_fts, rowid, word) VALUES ('delete', old.id, old.word); INSERT INTO words_fts (rowid, word) VALUES (new.id, new.word); END;govarnam-1.9.0/govarnam/misc.go000066400000000000000000000022171420445125700164350ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "io/fs" "log" "path/filepath" ) // GetAllSchemePaths get available IDs' location as a string array func GetAllSchemePaths() ([]string, error) { vstsDir, err := FindVSTDir() if err != nil { return nil, err } var schemeIDs []string filepath.WalkDir(vstsDir, func(s string, d fs.DirEntry, e error) error { if e != nil { return e } if filepath.Ext(d.Name()) == ".vst" { schemeIDs = append(schemeIDs, s) } return nil }) return schemeIDs, nil } // GetAllSchemeDetails get information of all schemes available func GetAllSchemeDetails() ([]SchemeDetails, error) { schemePaths, err := GetAllSchemePaths() if err != nil { return nil, err } var schemeDetails []SchemeDetails for _, vstPath := range schemePaths { varnam := Varnam{} err := varnam.InitVST(vstPath) if err == nil { schemeDetails = append(schemeDetails, varnam.SchemeDetails) varnam.Close() } else { log.Println(err) } } return schemeDetails, nil } govarnam-1.9.0/govarnam/symbol.go000066400000000000000000000377751420445125700170300ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "context" sql "database/sql" "fmt" "log" "strings" "github.com/mattn/go-sqlite3" ) // Symbol result from VST type Symbol struct { Identifier int Type int MatchType int Pattern string Value1 string Value2 string Value3 string Tag string Weight int Priority int AcceptCondition int Flags int } // Token info for making a suggestion type Token struct { tokenType int symbols []Symbol // Will be empty for non language character position int character string // Non language character } var sqlite3Conn *sqlite3.SQLiteConn func openDB(path string) (*sql.DB, error) { if sqlite3Conn == nil { sql.Register("sqlite3_with_limit", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { sqlite3Conn = conn return nil }, }) } conn, err := sql.Open("sqlite3_with_limit", path) if err != nil { return nil, err } return conn, nil } // InitVST initialize func (varnam *Varnam) InitVST(vstPath string) error { var err error varnam.vstConn, err = openDB(vstPath + "?_case_sensitive_like=on") if err != nil { return err } err = varnam.setPatternLongestLength() if err != nil { return err } varnam.vstConn.Exec("PRAGMA TEMP_STORE=2;") varnam.vstConn.Exec("PRAGMA LOCKING_MODE=EXCLUSIVE;") varnam.VSTPath = vstPath varnam.setSchemeInfo() return nil } // Find the longest pattern length func (varnam *Varnam) setPatternLongestLength() error { rows, err := varnam.vstConn.Query("SELECT MAX(LENGTH(pattern)) FROM symbols") if err != nil { return err } length := 0 for rows.Next() { err := rows.Scan(&length) if err != nil { return err } } if length == 0 { return fmt.Errorf("couldn't find longest pattern length") } varnam.LangRules.PatternLongestLength = length return nil } func (varnam *Varnam) setSchemeInfo() { rows, err := varnam.vstConn.Query("SELECT * FROM metadata") if err != nil { log.Print(err) } defer rows.Close() for rows.Next() { var ( key string value string ) rows.Scan(&key, &value) if key == "scheme-id" { varnam.SchemeDetails.Identifier = value } else if key == "lang-code" { varnam.SchemeDetails.LangCode = value } else if key == "scheme-display-name" { varnam.SchemeDetails.DisplayName = value } else if key == "scheme-author" { varnam.SchemeDetails.Author = value } else if key == "scheme-compiled-date" { varnam.SchemeDetails.CompiledDate = value } else if key == "scheme-stable" { if value == "1" { varnam.SchemeDetails.IsStable = true } else { varnam.SchemeDetails.IsStable = false } } } } func (varnam *Varnam) searchPattern(ctx context.Context, ch string, matchType int, acceptCondition int) []Symbol { var ( rows *sql.Rows err error results []Symbol ) select { case <-ctx.Done(): return results default: if matchType == VARNAM_MATCH_ALL { rows, err = varnam.vstConn.QueryContext(ctx, "SELECT * FROM symbols WHERE (value1 = ? OR value2 = ?) AND (accept_condition = 0 OR accept_condition = ?) ORDER BY match_type ASC, weight DESC, priority DESC", ch, ch, acceptCondition) } else { rows, err = varnam.vstConn.QueryContext(ctx, "SELECT * FROM symbols WHERE (value1 = ? OR value2 = ?) AND match_type = ? AND (accept_condition = 0 OR accept_condition = ?)", ch, ch, matchType, acceptCondition) } if err != nil { log.Print(err) return results } defer rows.Close() for rows.Next() { var item Symbol rows.Scan(&item.Identifier, &item.Type, &item.Pattern, &item.Value1, &item.Value2, &item.Value3, &item.Tag, &item.MatchType, &item.Priority, &item.AcceptCondition, &item.Flags, &item.Weight) results = append(results, item) } err = rows.Err() if err != nil { log.Print(err) } return results } } // Find longest pattern prefix matching symbols from VST func (varnam *Varnam) findLongestPatternMatchSymbols(ctx context.Context, pattern []rune, matchType int, acceptCondition int) []Symbol { var ( query string results []Symbol patternINs string vals []interface{} ) if matchType != VARNAM_MATCH_ALL { vals = append(vals, matchType) } vals = append(vals, acceptCondition) vals = append(vals, string(pattern[0])) for i := range pattern { if i == 0 { continue } patternINs += ", ?" vals = append(vals, string(pattern[0:i+1])) } if varnam.Debug { // The query will be made like : // SELECT * FROM symbols WHERE pattern IN ('e', 'en', 'ent', 'enth', 'entho') // Will fetch the longest prefix match // Idea from https://stackoverflow.com/a/1860279/1372424 fmt.Println(patternINs, vals) } select { case <-ctx.Done(): return results default: if matchType == VARNAM_MATCH_ALL { query = "SELECT * FROM `symbols` WHERE (accept_condition = 0 OR accept_condition = ?) AND pattern IN (? " + patternINs + ") ORDER BY LENGTH(pattern) DESC, match_type ASC, weight DESC, priority DESC" } else { query = "SELECT * FROM `symbols` WHERE match_type = ? AND (accept_condition = 0 OR accept_condition = ?) AND pattern IN (? " + patternINs + ") ORDER BY LENGTH(pattern) DESC" } rows, err := varnam.vstConn.QueryContext(ctx, query, vals...) if err != nil { log.Print(err) return results } defer rows.Close() for rows.Next() { var item Symbol rows.Scan(&item.Identifier, &item.Type, &item.Pattern, &item.Value1, &item.Value2, &item.Value3, &item.Tag, &item.MatchType, &item.Priority, &item.AcceptCondition, &item.Flags, &item.Weight) results = append(results, item) } err = rows.Err() if err != nil { log.Print(err) } return results } } // Convert a string into Tokens for later processing func (varnam *Varnam) tokenizeWord(ctx context.Context, word string, matchType int, partial bool) *[]Token { var results []Token select { case <-ctx.Done(): return &results default: runes := []rune(word) i := 0 for i < len(runes) { end := i + varnam.LangRules.PatternLongestLength if len(runes) < end { end = len(runes) } // Get characters after 'i'th position sequence := runes[i:end] acceptCondition := VARNAM_TOKEN_ACCEPT_IF_IN_BETWEEN if len(results) == 0 && !partial { // Trying to make the first token acceptCondition = VARNAM_TOKEN_ACCEPT_IF_STARTS_WITH } else if i == len(runes)-1 { acceptCondition = VARNAM_TOKEN_ACCEPT_IF_ENDS_WITH } matches := varnam.findLongestPatternMatchSymbols(ctx, sequence, matchType, acceptCondition) if len(matches) == 0 { // No matches, add a character token // Note that we just add 1 character, and move on token := Token{VARNAM_TOKEN_CHAR, matches, i, string(sequence[:1])} results = append(results, token) i++ } else { if matches[0].Type == VARNAM_SYMBOL_NUMBER && !varnam.LangRules.IndicDigits { // Skip numbers // Note that we just add 1 character, and move on token := Token{VARNAM_TOKEN_CHAR, []Symbol{}, i, string(sequence[:1])} results = append(results, token) i += len(matches[0].Pattern) } else { // Add matches var refinedMatches []Symbol longestPatternLength := 0 for _, match := range matches { if longestPatternLength == 0 { // Sort is by length of pattern, so we will get length from first iterations. longestPatternLength = len(match.Pattern) refinedMatches = append(refinedMatches, match) } else { if len(match.Pattern) != longestPatternLength { break } refinedMatches = append(refinedMatches, match) } } i += longestPatternLength token := Token{VARNAM_TOKEN_SYMBOL, refinedMatches, i - 1, string(refinedMatches[0].Pattern)} results = append(results, token) } } } return &results } } // Tokenize end part of a word and append it to results func (varnam *Varnam) tokenizeRestOfWord(ctx context.Context, word string, sugs []Suggestion, limit int) []Suggestion { var results []Suggestion if varnam.Debug { fmt.Printf("Tokenizing %s\n", word) } tokensPointerChan := make(chan *[]Token) go varnam.channelTokenizeWord(ctx, word, VARNAM_MATCH_ALL, true, tokensPointerChan) select { case <-ctx.Done(): return results case restOfWordTokens := <-tokensPointerChan: for _, sug := range sugs { sugWord := varnam.removeLastVirama(sug.Word) tokensWithWord := []Token{{VARNAM_TOKEN_CHAR, []Symbol{}, 0, sugWord}} tokensWithWord = append(tokensWithWord, *restOfWordTokens...) restOfWordSugs := varnam.tokensToSuggestions(ctx, &tokensWithWord, true, limit) if varnam.Debug { fmt.Println("Tokenized & Added:", restOfWordSugs) } for _, restOfWordSug := range restOfWordSugs { // Preserve original word's weight and timestamp restOfWordSug.Weight += sug.Weight restOfWordSug.LearnedOn = sug.LearnedOn results = append(results, restOfWordSug) } } return results } } // Split an input string into tokens of symbols (conjuncts) and characters func (varnam *Varnam) splitTextByConjunct(ctx context.Context, inputStr string) []Token { var results []Token var prevSequence string var prevSequenceMatches []Symbol var sequence string // Not using len() because it will be wrong for non ASCII characters var sequenceLength int input := []rune(inputStr) position := 0 i := 0 for i < len(input) { ch := string(input[i]) sequence += ch sequenceLength++ acceptCondition := VARNAM_TOKEN_ACCEPT_IF_IN_BETWEEN if i == 0 { // Trying to make the first token acceptCondition = VARNAM_TOKEN_ACCEPT_IF_STARTS_WITH } else if i == len(input)-1 { acceptCondition = VARNAM_TOKEN_ACCEPT_IF_ENDS_WITH } symbols := varnam.searchPattern(ctx, sequence, VARNAM_MATCH_ALL, acceptCondition) if len(symbols) == 0 { // No more matches if sequenceLength == 1 { // Has non language characters, add char token results = append(results, Token{VARNAM_TOKEN_CHAR, []Symbol{}, position, sequence}) } else if len(prevSequenceMatches) > 0 { // Backtrack and add the previous sequence matches i-- results = append(results, Token{VARNAM_TOKEN_SYMBOL, prevSequenceMatches, position, prevSequence}) } sequence = "" sequenceLength = 0 position++ } else { if i == len(input)-1 { // Last character results = append(results, Token{VARNAM_TOKEN_SYMBOL, symbols, position, sequence}) position++ } else { prevSequence = sequence prevSequenceMatches = symbols } } i++ } return results } // Split a word by conjuncts. Returns string of conjuncts of first full word found func (varnam *Varnam) splitWordByConjunct(word string) []string { ctx := context.Background() var result []string tokens := varnam.splitTextByConjunct(ctx, word) if varnam.Debug { log.Println(tokens) } for _, token := range tokens { if token.tokenType == VARNAM_TOKEN_SYMBOL { ok := true for _, symbol := range token.symbols { if symbol.Type == VARNAM_SYMBOL_NUMBER || symbol.Type == VARNAM_SYMBOL_PERIOD || symbol.Type == VARNAM_SYMBOL_SYMBOL { ok = false break } } if ok { result = append(result, token.character) } } else { break } } return result } func getSymbolValue(symbol Symbol, position int) string { // Ignore render_value2 tag. It's only applicable for libvarnam // https://gitlab.com/subins2000/govarnam/-/issues/3 if symbol.Type == VARNAM_SYMBOL_VOWEL && position > 0 { // If in between word, we use the vowel and not the consonant return symbol.Value2 // ാ } return symbol.Value1 // ആ } func getSymbolWeight(symbol Symbol) int { if symbol.MatchType == VARNAM_MATCH_EXACT { // 200 because there might be possibility matches having weight 100 return 200 } return symbol.Weight } // Removes less weighted symbols func removeLessWeightedSymbols(tokens []Token) []Token { for i := range tokens { var reducedSymbols []Symbol for _, symbol := range tokens[i].symbols { // TODO should 0 be fixed for all languages ? // Because this may differ according to data source // from where symbol frequency was found out if getSymbolWeight(symbol) == 0 && len(reducedSymbols) > 0 { break } reducedSymbols = append(reducedSymbols, symbol) } tokens[i].symbols = nil tokens[i].symbols = reducedSymbols } return tokens } // Remove non-exact matching tokens func removeNonExactTokens(tokens []Token) []Token { // Remove non-exact symbols for i, token := range tokens { if token.tokenType == VARNAM_TOKEN_SYMBOL { var reducedSymbols []Symbol for _, symbol := range token.symbols { if symbol.MatchType == VARNAM_MATCH_EXACT { reducedSymbols = append(reducedSymbols, symbol) } else { if len(reducedSymbols) == 0 { // No exact matches, so add the first possibility match reducedSymbols = append(reducedSymbols, symbol) } // If a possibility result, then rest of them will also be same // so save time by skipping rest break } } tokens[i].symbols = reducedSymbols } } return tokens } // NewSearchSymbol a constructor for making Symbol. // We're doing this because default int value in // go structs is 0. This won't work with searching // because fields can have 0 value. // https://stackoverflow.com/q/37135193/137242 func NewSearchSymbol() Symbol { symbol := Symbol{} symbol.Identifier = STRUCT_INT_DEFAULT_VALUE symbol.Type = STRUCT_INT_DEFAULT_VALUE symbol.MatchType = STRUCT_INT_DEFAULT_VALUE symbol.Weight = STRUCT_INT_DEFAULT_VALUE symbol.Priority = STRUCT_INT_DEFAULT_VALUE symbol.AcceptCondition = STRUCT_INT_DEFAULT_VALUE symbol.Flags = STRUCT_INT_DEFAULT_VALUE return symbol } func (varnam *Varnam) makeSearchSymbolQuery(queryPrefix string, searchCriteria Symbol) (string, []interface{}) { var ( clauses []string values []interface{} ) addItem := func(name string, val interface{}) { if valString, isString := val.(string); isString { if valString == "" { return } // Format should be LIKE value if len(valString) > 5 && valString[0:5] == "LIKE " { valString = valString[5:] clauses = append(clauses, name+" LIKE ?") values = append(values, valString) return } } else { if valInt, ok := val.(int); !ok || valInt == STRUCT_INT_DEFAULT_VALUE { return } } clauses = append(clauses, name+" = ?") values = append(values, val) } addItem("id", searchCriteria.Identifier) addItem("type", searchCriteria.Type) addItem("match_type", searchCriteria.MatchType) addItem("pattern", searchCriteria.Pattern) addItem("value1", searchCriteria.Value1) addItem("value2", searchCriteria.Value2) addItem("value3", searchCriteria.Value3) addItem("tag", searchCriteria.Tag) addItem("weight", searchCriteria.Weight) addItem("priority", searchCriteria.Priority) addItem("accept_condition", searchCriteria.AcceptCondition) addItem("flags", searchCriteria.Flags) query := queryPrefix if len(values) > 0 { query += " WHERE " + strings.Join(clauses, " AND ") } if varnam.Debug { fmt.Println(query, values) } return query, values } // SearchSymbolTable For searching symbol table func (varnam *Varnam) SearchSymbolTable(ctx context.Context, searchCriteria Symbol) ([]Symbol, error) { var results []Symbol select { case <-ctx.Done(): return results, nil default: query, values := varnam.makeSearchSymbolQuery("SELECT * FROM symbols", searchCriteria) rows, err := varnam.vstConn.QueryContext(ctx, query, values...) if err != nil { return nil, err } for rows.Next() { var item Symbol rows.Scan(&item.Identifier, &item.Type, &item.Pattern, &item.Value1, &item.Value2, &item.Value3, &item.Tag, &item.MatchType, &item.Priority, &item.AcceptCondition, &item.Flags, &item.Weight) results = append(results, item) } return results, nil } } func (varnam *Varnam) getVirama() (string, error) { viramaSymbol := NewSearchSymbol() viramaSymbol.Pattern = "~" results, _ := varnam.SearchSymbolTable(context.Background(), viramaSymbol) if len(results) == 0 { return "", fmt.Errorf("virama not found") } return results[0].Value1, nil } govarnam-1.9.0/govarnam/testdata/000077500000000000000000000000001420445125700167625ustar00rootroot00000000000000govarnam-1.9.0/govarnam/testdata/2021-04-10-init.sql000066400000000000000000000006341420445125700214720ustar00rootroot00000000000000CREATE TABLE IF NOT EXISTS metadata ( key TEXT UNIQUE, value TEXT ); CREATE TABLE IF NOT EXISTS words ( id INTEGER PRIMARY KEY, word TEXT UNIQUE, weight INTEGER DEFAULT 1, learned_on INTEGER ); CREATE TABLE IF NOT EXISTS patterns ( pattern TEXT NOT NULL COLLATE NOCASE, word_id INTEGER NOT NULL, FOREIGN KEY(word_id) REFERENCES words(id) ON DELETE CASCADE, PRIMARY KEY(pattern, word_id) ); govarnam-1.9.0/govarnam/util.go000066400000000000000000000016251420445125700164610ustar00rootroot00000000000000package govarnam import ( "os" "unicode/utf8" ) func getFirstCharacter(input string) (string, int) { r, size := utf8.DecodeRuneInString(input) if r == utf8.RuneError && (size == 0 || size == 1) { size = 0 } return input[0:size], size } func getLastCharacter(input string) (string, int) { r, size := utf8.DecodeLastRuneInString(input) if r == utf8.RuneError && (size == 0 || size == 1) { size = 0 } return input[len(input)-size:], size } func (varnam *Varnam) removeLastVirama(input string) string { char, size := getLastCharacter(input) if char == varnam.LangRules.Virama { return input[0 : len(input)-size] } return input } func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } func dirExists(loc string) bool { info, err := os.Stat(loc) if os.IsNotExist(err) { return false } return info.IsDir() } govarnam-1.9.0/govarnam/vst_maker.go000066400000000000000000000247771420445125700175140ustar00rootroot00000000000000package govarnam /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ import ( "context" sql "database/sql" "fmt" "time" ) // VM, vm = Vst Maker // Ported from libvarnam. Some are not ported: // * stem rules // * symbols flag setting // VMInit init func VMInit(vstPath string) (*Varnam, error) { varnam := Varnam{} var err error varnam.vstConn, err = openDB(vstPath + "?_case_sensitive_like=on") if err != nil { return nil, err } err = varnam.vmEnsureSchemaExists() if err != nil { return nil, err } return &varnam, nil } func (varnam *Varnam) vmEnsureSchemaExists() error { queries := []string{ ` create table if not exists metadata (key TEXT UNIQUE, value TEXT); `, ` create table if not exists symbols (id INTEGER PRIMARY KEY AUTOINCREMENT, type INTEGER, pattern TEXT, value1 TEXT, value2 TEXT, value3 TEXT, tag TEXT, match_type INTEGER, priority INTEGER DEFAULT 0, accept_condition INTEGER, flags INTEGER DEFAULT 0, weight INTEGER); `, ` create table if not exists stemrules (id INTEGER PRIMARY KEY AUTOINCREMENT, old_ending TEXT, new_ending TEXT); `, ` create table if not exists stem_exceptions (id INTEGER PRIMARY KEY AUTOINCREMENT, stem TEXT, exception TEXT) `, ` create index if not exists index_metadata on metadata (key); `, ` create index if not exists index_pattern on symbols (pattern); `, ` create index if not exists index_value1 on symbols (value1); `, ` create index if not exists index_value2 on symbols (value2); `, ` create index if not exists index_value3 on symbols (value3); `} for _, query := range queries { ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) defer cancelFunc() stmt, err := varnam.vstConn.PrepareContext(ctx, query) if err != nil { return err } defer stmt.Close() _, err = stmt.ExecContext(ctx) if err != nil { return err } } return nil } func (varnam *Varnam) vmStartBuffering() error { if varnam.VSTMakerConfig.Buffering { return nil } varnam.vstConn.Exec("BEGIN;") varnam.VSTMakerConfig.Buffering = true return nil } func (varnam *Varnam) vmFlushChanges() error { if !varnam.VSTMakerConfig.Buffering { return nil } varnam.log("Writing changes to file...") _, err := varnam.vstConn.Exec("COMMIT;") if err != nil { return fmt.Errorf("failed to flush changes: " + err.Error()) } varnam.VSTMakerConfig.Buffering = false varnam.log("Compacting file...") _, err = varnam.vstConn.Exec("VACUUM") if err != nil { return fmt.Errorf("failed to compact db: " + err.Error()) } return nil } // This function is called when something went wrong. Rollback VST DB func (varnam *Varnam) vmDiscardChanges() error { if !varnam.VSTMakerConfig.Buffering { return nil } varnam.vstConn.Exec("ROLLBACK;") varnam.VSTMakerConfig.Buffering = false return nil } // VMCreateToken Create Token func (varnam *Varnam) VMCreateToken(pattern string, value1 string, value2 string, value3 string, tag string, symbolType int, matchType int, priority int, acceptCondition int, buffered bool) error { if pattern == "" || value1 == "" { return fmt.Errorf("pattern or value1 is empty") } if len(pattern) > VARNAM_SYMBOL_MAX || len(value1) > VARNAM_SYMBOL_MAX || (value2 != "" && len(value2) > VARNAM_SYMBOL_MAX) || (value3 != "" && len(value3) > VARNAM_SYMBOL_MAX) || (tag != "" && len(tag) > VARNAM_SYMBOL_MAX) { return fmt.Errorf("length of pattern, tag, value1 or value2, value3 should be less than VARNAM_SYMBOL_MAX") } if matchType != VARNAM_MATCH_EXACT && matchType != VARNAM_MATCH_POSSIBILITY { return fmt.Errorf("matchType should be either VARNAM_MATCH_EXACT or VARNAM_MATCH_POSSIBILITY") } if acceptCondition != VARNAM_TOKEN_ACCEPT_ALL && acceptCondition != VARNAM_TOKEN_ACCEPT_IF_STARTS_WITH && acceptCondition != VARNAM_TOKEN_ACCEPT_IF_IN_BETWEEN && acceptCondition != VARNAM_TOKEN_ACCEPT_IF_ENDS_WITH { return fmt.Errorf("invalid accept condition specified. It should be one of VARNAM_TOKEN_ACCEPT_XXX") } if buffered { varnam.vmStartBuffering() } if symbolType == VARNAM_SYMBOL_CONSONANT && varnam.VSTMakerConfig.UseDeadConsonants { virama, err := varnam.getVirama() if err != nil { return fmt.Errorf("virama needs to be set before auto generating dead consonants") } patternRune := []rune(pattern) lastChar, _ := getLastCharacter(value1) if lastChar == virama { symbolType = VARNAM_SYMBOL_DEAD_CONSONANT } else if canGenerateDeadConsonant(patternRune) { patternExceptLastChar := string(patternRune[:len(patternRune)-1]) var ( value1WithVirama = value1 + virama value2WithVirama = "" ) if value2 != "" { value2WithVirama += virama } err := varnam.vmPersistToken(patternExceptLastChar, value1WithVirama, value2WithVirama, value3, tag, VARNAM_SYMBOL_DEAD_CONSONANT, matchType, priority, acceptCondition) if err != nil { varnam.vmDiscardChanges() return err } } } if symbolType == VARNAM_SYMBOL_NON_JOINER { value1 = ZWNJ value2 = ZWNJ } if symbolType == VARNAM_SYMBOL_JOINER { value1 = ZWJ value2 = ZWJ } err := varnam.vmPersistToken(pattern, value1, value2, value3, tag, symbolType, matchType, priority, acceptCondition) if err != nil { if buffered { varnam.vmDiscardChanges() } return err } if !buffered { // TODO flags is not used in govarnam // err = varnam.vmMakePrefixTree() // if err != nil { // return err // } err = varnam.vmStampVersion() if err != nil { return err } } return nil } func (varnam *Varnam) vmPersistToken(pattern string, value1 string, value2 string, value3 string, tag string, symbolType int, matchType int, priority int, acceptCondition int) error { if pattern == "" || value1 == "" || !(symbolType >= VARNAM_SYMBOL_VOWEL && symbolType <= VARNAM_SYMBOL_PERIOD) { return fmt.Errorf("arguments invalid") } persisted, err := varnam.vmAlreadyPersisted(pattern, value1, matchType, acceptCondition) if err != nil { return err } if persisted { if varnam.VSTMakerConfig.IgnoreDuplicateTokens { varnam.log(fmt.Sprintf("%s => %s is already available. Ignoring duplicate tokens", pattern, value1)) return nil } return fmt.Errorf("there is already a match available for '%s => %s'. Duplicate entries are not allowed", pattern, value1) } query := "INSERT OR IGNORE INTO symbols (type, pattern, value1, value2, value3, tag, match_type, priority, accept_condition) VALUES (?, trim(?), trim(?), trim(?), trim(?), trim(?), ?, ?, ?)" bgContext := context.Background() ctx, cancelFunc := context.WithTimeout(bgContext, 5*time.Second) defer cancelFunc() stmt, err := varnam.vstConn.PrepareContext(ctx, query) if err != nil { return err } defer stmt.Close() _, err = stmt.ExecContext(ctx, symbolType, pattern, value1, value2, value3, tag, matchType, priority, acceptCondition) if err != nil { return fmt.Errorf("Failed to persist token: %s", err.Error()) } return nil } func (varnam *Varnam) vmAlreadyPersisted(pattern string, value1 string, matchType int, acceptCondition int) (bool, error) { searchCriteria := NewSearchSymbol() searchCriteria.Pattern = pattern searchCriteria.AcceptCondition = acceptCondition if matchType == VARNAM_MATCH_EXACT { searchCriteria.MatchType = matchType } else { searchCriteria.Value1 = value1 } result, err := varnam.SearchSymbolTable(context.Background(), searchCriteria) if err != nil { return false, err } return len(result) > 0, nil } // VMDeleteToken Removes a token from VST func (varnam *Varnam) VMDeleteToken(searchCriteria Symbol) error { query, values := varnam.makeSearchSymbolQuery("DELETE FROM symbols", searchCriteria) _, err := varnam.vstConn.Exec(query, values...) if err != nil { return err } return nil } // Makes a prefix tree. This fills up the flags column // TODO incomplete func (varnam *Varnam) vmMakePrefixTree() error { for _, columnName := range []string{"pattern", "value1", "value2"} { stmt, err := varnam.vstConn.Prepare(fmt.Sprintf("SELECT id, %s FROM symbols GROUP BY %s ORDER BY LENGTH(%s) ASC", columnName, columnName, columnName)) if err != nil { varnam.log(err.Error()) return nil } var mask int if columnName == "pattern" { mask = VARNAM_SYMBOL_FLAGS_MORE_MATCHES_FOR_PATTERN } else { mask = VARNAM_SYMBOL_FLAGS_MORE_MATCHES_FOR_VALUE } updateStmt, err := varnam.vstConn.Prepare(fmt.Sprintf("UPDATE symbols SET flags = flags | %d WHERE %s = ?", mask, columnName)) if err != nil { varnam.log(err.Error()) } varnam.vmFindPrefixesAndUpdateFlags(stmt, updateStmt) stmt.Close() updateStmt.Close() } return nil } func (varnam *Varnam) vmFindPrefixesAndUpdateFlags(stmt *sql.Stmt, updateStmt *sql.Stmt) { type symbolIDMap struct { symbol string id int } // TODO incomplete } func (varnam *Varnam) vmStampVersion() error { _, err := varnam.vstConn.Exec(fmt.Sprintf("PRAGMA user_version=%d", VARNAM_SCHEMA_SYMBOLS_VERSION)) return err } func (varnam *Varnam) vmAddMetadata(key string, value string) error { _, err := varnam.vstConn.Exec("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)", key, value) return err } // VMSetSchemeDetails set scheme details func (varnam *Varnam) VMSetSchemeDetails(sd SchemeDetails) error { if len(sd.LangCode) != 2 { return fmt.Errorf("language code should be one of ISO 639-1 two letter codes") } isStable := "1" if !sd.IsStable { isStable = "0" } type item struct { name string key string value string } items := []item{ {"language code", VARNAM_METADATA_SCHEME_LANGUAGE_CODE, sd.LangCode}, {"language identifier", VARNAM_METADATA_SCHEME_IDENTIFIER, sd.Identifier}, {"language display name", VARNAM_METADATA_SCHEME_DISPLAY_NAME, sd.DisplayName}, {"author", VARNAM_METADATA_SCHEME_AUTHOR, sd.Author}, {"compiled date", VARNAM_METADATA_SCHEME_COMPILED_DATE, sd.CompiledDate}, {"stable", VARNAM_METADATA_SCHEME_STABLE, isStable}, } for _, o := range items { err := varnam.vmAddMetadata(o.key, o.value) if err != nil { return err } varnam.log("Set " + o.name + " to: " + string(o.value)) } return nil } // VMFlushBuffer flush func (varnam *Varnam) VMFlushBuffer() error { // varnam.vmMakePrefixTree() err := varnam.vmStampVersion() if err != nil { return err } return varnam.vmFlushChanges() } // Checks if the string has inherent 'a' sound. If yes, we can infer dead consonant from it func canGenerateDeadConsonant(input []rune) bool { if len(input) <= 1 { return false } return string(input[len(input)-2]) != "a" && string(input[len(input)-1]) == "a" } govarnam-1.9.0/govarnamgo/000077500000000000000000000000001420445125700154775ustar00rootroot00000000000000govarnam-1.9.0/govarnamgo/general.go000066400000000000000000000004021420445125700174370ustar00rootroot00000000000000package govarnamgo // #cgo pkg-config: govarnam // #include "libgovarnam.h" // #include "stdlib.h" import "C" func (handle *VarnamHandle) ReIndexDictionary() error { err := C.varnam_reindex_dictionary(handle.connectionID) return handle.checkError(err) } govarnam-1.9.0/govarnamgo/general_test.go000066400000000000000000000002521420445125700205010ustar00rootroot00000000000000package govarnamgo import "testing" func TestReIndex(t *testing.T) { varnam := getVarnamInstance("ml") err := varnam.ReIndexDictionary() assertEqual(t, err, nil) } govarnam-1.9.0/govarnamgo/govarnamgo.go000066400000000000000000000456221420445125700201770ustar00rootroot00000000000000package govarnamgo /** * govarnam - An Indian language transliteration library * Copyright Subin Siby , 2021 * Licensed under AGPL-3.0-only. See LICENSE.txt */ /* Golang bindings for govarnam library */ // #cgo pkg-config: govarnam // #include "libgovarnam.h" // #include "stdlib.h" import "C" import ( "context" "fmt" "log" "unsafe" ) // Config config values type Config struct { IndicDigits bool DictionaryMatchExact bool DictionarySuggestionsLimit int PatternDictionarySuggestionsLimit int TokenizerSuggestionsLimit int TokenizerSuggestionsAlways bool } // VarnamHandle for making things easier type VarnamHandle struct { connectionID C.int } // Suggestion suggestion type Suggestion struct { Word string Weight int LearnedOn int } // TransliterationResult result type TransliterationResult struct { ExactWords []Suggestion ExactMatches []Suggestion DictionarySuggestions []Suggestion PatternDictionarySuggestions []Suggestion TokenizerSuggestions []Suggestion GreedyTokenized []Suggestion } // SchemeDetails of VST type SchemeDetails struct { Identifier string LangCode string DisplayName string Author string CompiledDate string IsStable bool } // LearnStatus output of bulk learn type LearnStatus struct { TotalWords int FailedWords int } // Symbol result from VST type Symbol struct { Identifier int Type int MatchType int Pattern string Value1 string Value2 string Value3 string Tag string Weight int Priority int AcceptCondition int Flags int } var contextOperationCount = C.int(0) func makeContextOperation() C.int { operationID := contextOperationCount contextOperationCount++ return operationID } // Convert a C Suggestion to Go func makeSuggestion(cSug *C.struct_Suggestion_t) Suggestion { var sug Suggestion sug.Word = C.GoString(cSug.Word) sug.Weight = int(cSug.Weight) sug.LearnedOn = int(cSug.LearnedOn) return sug } func makeGoTransliterationResult(ctx context.Context, cResult *C.struct_TransliterationResult_t) TransliterationResult { var result TransliterationResult select { case <-ctx.Done(): return result default: var i int var exactWords []Suggestion i = 0 for i < int(C.varray_length(cResult.ExactWords)) { cSug := (*C.Suggestion)(C.varray_get(cResult.ExactWords, C.int(i))) sug := makeSuggestion(cSug) exactWords = append(exactWords, sug) i++ } result.ExactWords = exactWords var exactMatches []Suggestion i = 0 for i < int(C.varray_length(cResult.ExactMatches)) { cSug := (*C.Suggestion)(C.varray_get(cResult.ExactMatches, C.int(i))) sug := makeSuggestion(cSug) exactMatches = append(exactMatches, sug) i++ } result.ExactMatches = exactMatches var dictionarySuggestions []Suggestion i = 0 for i < int(C.varray_length(cResult.DictionarySuggestions)) { cSug := (*C.Suggestion)(C.varray_get(cResult.DictionarySuggestions, C.int(i))) sug := makeSuggestion(cSug) dictionarySuggestions = append(dictionarySuggestions, sug) i++ } result.DictionarySuggestions = dictionarySuggestions var patternDictionarySuggestions []Suggestion i = 0 for i < int(C.varray_length(cResult.PatternDictionarySuggestions)) { cSug := (*C.Suggestion)(C.varray_get(cResult.PatternDictionarySuggestions, C.int(i))) sug := makeSuggestion(cSug) patternDictionarySuggestions = append(patternDictionarySuggestions, sug) i++ } result.PatternDictionarySuggestions = patternDictionarySuggestions var tokenizerSuggestions []Suggestion i = 0 for i < int(C.varray_length(cResult.TokenizerSuggestions)) { cSug := (*C.Suggestion)(C.varray_get(cResult.TokenizerSuggestions, C.int(i))) sug := makeSuggestion(cSug) tokenizerSuggestions = append(tokenizerSuggestions, sug) i++ } result.TokenizerSuggestions = tokenizerSuggestions var greedyTokenized []Suggestion i = 0 for i < int(C.varray_length(cResult.GreedyTokenized)) { cSug := (*C.Suggestion)(C.varray_get(cResult.GreedyTokenized, C.int(i))) sug := makeSuggestion(cSug) greedyTokenized = append(greedyTokenized, sug) i++ } result.GreedyTokenized = greedyTokenized go C.destroyTransliterationResult(cResult) return result } } //VarnamError Custom error for varnam type VarnamError struct { ErrorCode int Message string } // Error mimicking error package's function func (err VarnamError) Error() string { return err.Message } func (handle *VarnamHandle) checkError(code C.int) error { if code == C.VARNAM_SUCCESS { return nil } return &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } // GetVersion get library version func GetVersion() string { return C.GoString(C.varnam_get_version()) } // GetBuild get library build version func GetBuild() string { return C.GoString(C.varnam_get_build()) } // Init Initialize func Init(vstLoc string, dictLoc string) (*VarnamHandle, error) { handleID := C.int(0) cVSTFile := C.CString(vstLoc) cDictLoc := C.CString(dictLoc) err := C.varnam_init(cVSTFile, cDictLoc, unsafe.Pointer(&handleID)) C.free(unsafe.Pointer(cVSTFile)) C.free(unsafe.Pointer(cDictLoc)) if err != C.VARNAM_SUCCESS { return nil, fmt.Errorf(C.GoString(C.varnam_get_last_error(handleID))) } return &VarnamHandle{handleID}, nil } // InitFromID Initialize func InitFromID(id string) (*VarnamHandle, error) { handleID := C.int(0) cID := C.CString(id) err := C.varnam_init_from_id(cID, unsafe.Pointer(&handleID)) C.free(unsafe.Pointer(cID)) if err != C.VARNAM_SUCCESS { return nil, fmt.Errorf(C.GoString(C.varnam_get_last_error(handleID))) } return &VarnamHandle{handleID}, nil } // GetLastError get last error func (handle *VarnamHandle) GetLastError() string { cStr := C.varnam_get_last_error(handle.connectionID) goStr := C.GoString(cStr) C.free(unsafe.Pointer(cStr)) return goStr } // Close db connections and end varnam func (handle *VarnamHandle) Close() error { err := C.varnam_close(handle.connectionID) return handle.checkError(err) } // Debug turn debug on/off func (handle *VarnamHandle) Debug(val bool) { if val { C.varnam_debug(handle.connectionID, C.int(1)) } else { C.varnam_debug(handle.connectionID, C.int(0)) } } // SetConfig set config func (handle *VarnamHandle) SetConfig(config Config) { C.varnam_set_dictionary_suggestions_limit(handle.connectionID, C.int(config.DictionarySuggestionsLimit)) C.varnam_set_pattern_dictionary_suggestions_limit(handle.connectionID, C.int(config.PatternDictionarySuggestionsLimit)) C.varnam_set_tokenizer_suggestions_limit(handle.connectionID, C.int(config.TokenizerSuggestionsLimit)) if config.IndicDigits { C.varnam_set_indic_digits(handle.connectionID, C.int(1)) } else { C.varnam_set_indic_digits(handle.connectionID, C.int(0)) } if config.DictionaryMatchExact { C.varnam_set_dictionary_match_exact(handle.connectionID, C.int(1)) } else { C.varnam_set_dictionary_match_exact(handle.connectionID, C.int(0)) } } type cgoVarnamTransliterateResult struct { result *C.varray err error } func (handle *VarnamHandle) cgoVarnamTransliterate(operationID C.int, resultChannel chan<- cgoVarnamTransliterateResult, word string) { cWord := C.CString(word) defer C.free(unsafe.Pointer(cWord)) var resultPointer *C.varray code := C.varnam_transliterate(handle.connectionID, operationID, cWord, &resultPointer) if code == C.VARNAM_SUCCESS { resultChannel <- cgoVarnamTransliterateResult{ resultPointer, nil, } } else { resultChannel <- cgoVarnamTransliterateResult{ resultPointer, fmt.Errorf(handle.GetLastError()), } } close(resultChannel) } // Transliterate transilterate func (handle *VarnamHandle) Transliterate(ctx context.Context, word string) ([]Suggestion, error) { var result []Suggestion operationID := makeContextOperation() channel := make(chan cgoVarnamTransliterateResult) go handle.cgoVarnamTransliterate(operationID, channel, word) select { case <-ctx.Done(): C.varnam_cancel(operationID) return result, nil case channelResult := <-channel: if channelResult.err != nil { return result, channelResult.err } i := 0 for i < int(C.varray_length(channelResult.result)) { cSug := (*C.Suggestion)(C.varray_get(channelResult.result, C.int(i))) sug := makeSuggestion(cSug) result = append(result, sug) i++ } go C.destroySuggestionsArray(channelResult.result) return result, nil } } type cgoVarnamTransliterateAdvancedResult struct { result *C.struct_TransliterationResult_t err error } func (handle *VarnamHandle) cgoVarnamTransliterateAdvanced(operationID C.int, resultChannel chan<- cgoVarnamTransliterateAdvancedResult, word string) { cWord := C.CString(word) defer C.free(unsafe.Pointer(cWord)) var resultPointer *C.struct_TransliterationResult_t code := C.varnam_transliterate_advanced(handle.connectionID, operationID, cWord, &resultPointer) if code == C.VARNAM_SUCCESS { resultChannel <- cgoVarnamTransliterateAdvancedResult{ resultPointer, nil, } } else { resultChannel <- cgoVarnamTransliterateAdvancedResult{ resultPointer, fmt.Errorf(handle.GetLastError()), } } close(resultChannel) } // TransliterateAdvanced transilterate func (handle *VarnamHandle) TransliterateAdvanced(ctx context.Context, word string) (TransliterationResult, error) { var result TransliterationResult operationID := makeContextOperation() channel := make(chan cgoVarnamTransliterateAdvancedResult) go handle.cgoVarnamTransliterateAdvanced(operationID, channel, word) select { case <-ctx.Done(): C.varnam_cancel(operationID) return result, nil case channelResult := <-channel: if channelResult.err != nil { return result, channelResult.err } result = makeGoTransliterationResult(ctx, channelResult.result) return result, nil } } // TransliterateGreedyTokenized transliterate but only tokenizer output func (handle *VarnamHandle) TransliterateGreedyTokenized(word string) []Suggestion { var result []Suggestion var resultPointer *C.varray cWord := C.CString(word) defer C.free(unsafe.Pointer(cWord)) code := C.varnam_transliterate_greedy_tokenized(handle.connectionID, cWord, &resultPointer) if code != C.VARNAM_SUCCESS { log.Print(handle.GetLastError()) return result } i := 0 for i < int(C.varray_length(resultPointer)) { cSug := (*C.Suggestion)(C.varray_get(resultPointer, C.int(i))) sug := makeSuggestion(cSug) result = append(result, sug) i++ } return result } // ReverseTransliterate reverse transilterate func (handle *VarnamHandle) ReverseTransliterate(word string) ([]Suggestion, error) { var sugs []Suggestion cWord := C.CString(word) defer C.free(unsafe.Pointer(cWord)) var resultPointer *C.varray defer C.destroySuggestionsArray(resultPointer) code := C.varnam_reverse_transliterate(handle.connectionID, cWord, &resultPointer) if code != C.VARNAM_SUCCESS { return sugs, &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } i := 0 for i < int(C.varray_length(resultPointer)) { cSug := (*C.Suggestion)(C.varray_get(resultPointer, C.int(i))) sug := makeSuggestion(cSug) sugs = append(sugs, sug) i++ } return sugs, nil } // Train train a pattern => word func (handle *VarnamHandle) Train(pattern string, word string) error { cPattern := C.CString(pattern) cWord := C.CString(word) err := C.varnam_train(handle.connectionID, cPattern, cWord) C.free(unsafe.Pointer(cPattern)) C.free(unsafe.Pointer(cWord)) return handle.checkError(err) } // Learn a word func (handle *VarnamHandle) Learn(word string, weight int) error { cWord := C.CString(word) err := C.varnam_learn(handle.connectionID, cWord, C.int(weight)) C.free(unsafe.Pointer(cWord)) return handle.checkError(err) } // Unlearn a word func (handle *VarnamHandle) Unlearn(word string) error { cWord := C.CString(word) err := C.varnam_unlearn(handle.connectionID, cWord) C.free(unsafe.Pointer(cWord)) return handle.checkError(err) } // LearnFromFile learn words from a file func (handle *VarnamHandle) LearnFromFile(filePath string) (LearnStatus, error) { var learnStatus LearnStatus cFilePath := C.CString(filePath) defer C.free(unsafe.Pointer(cFilePath)) var resultPointer *C.LearnStatus defer C.free(unsafe.Pointer(resultPointer)) code := C.varnam_learn_from_file(handle.connectionID, cFilePath, &resultPointer) if code != C.VARNAM_SUCCESS { return learnStatus, &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } learnStatus = LearnStatus{ int((*resultPointer).TotalWords), int((*resultPointer).FailedWords), } return learnStatus, nil } // TrainFromFile train pattern => word from a file func (handle *VarnamHandle) TrainFromFile(filePath string) (LearnStatus, error) { var learnStatus LearnStatus cFilePath := C.CString(filePath) defer C.free(unsafe.Pointer(cFilePath)) var resultPointer *C.LearnStatus defer C.free(unsafe.Pointer(resultPointer)) code := C.varnam_train_from_file(handle.connectionID, cFilePath, &resultPointer) if code != C.VARNAM_SUCCESS { return learnStatus, &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } learnStatus = LearnStatus{ int((*resultPointer).TotalWords), int((*resultPointer).FailedWords), } return learnStatus, nil } // Export learnigns to a file func (handle *VarnamHandle) Export(filePath string, wordsPerFile int) error { cFilePath := C.CString(filePath) err := C.varnam_export(handle.connectionID, cFilePath, C.int(wordsPerFile)) return handle.checkError(err) } // Import learnigns to a file func (handle *VarnamHandle) Import(filePath string) error { cFilePath := C.CString(filePath) err := C.varnam_import(handle.connectionID, cFilePath) return handle.checkError(err) } // GetRecentlyLearntWords get recently learn words func (handle *VarnamHandle) GetRecentlyLearntWords(ctx context.Context, offset int, limit int) ([]Suggestion, error) { var result []Suggestion operationID := makeContextOperation() select { case <-ctx.Done(): C.varnam_cancel(operationID) return result, nil default: var resultPointer *C.varray code := C.varnam_get_recently_learned_words(handle.connectionID, operationID, C.int(offset), C.int(limit), &resultPointer) if code != C.VARNAM_SUCCESS { return result, &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } i := 0 for i < int(C.varray_length(resultPointer)) { cSug := (*C.Suggestion)(C.varray_get(resultPointer, C.int(i))) sug := makeSuggestion(cSug) result = append(result, sug) i++ } return result, nil } } // GetSuggestions get suggestions for a word func (handle *VarnamHandle) GetSuggestions(ctx context.Context, word string) ([]Suggestion, error) { var result []Suggestion operationID := makeContextOperation() select { case <-ctx.Done(): C.varnam_cancel(operationID) return result, nil default: var resultPointer *C.varray cWord := C.CString(word) defer C.free(unsafe.Pointer(cWord)) code := C.varnam_get_suggestions(handle.connectionID, operationID, cWord, &resultPointer) if code != C.VARNAM_SUCCESS { return result, &VarnamError{ ErrorCode: int(code), Message: handle.GetLastError(), } } i := 0 for i < int(C.varray_length(resultPointer)) { cSug := (*C.Suggestion)(C.varray_get(resultPointer, C.int(i))) sug := makeSuggestion(cSug) result = append(result, sug) i++ } return result, nil } } func makeGoSchemeDetails(cSD *C.struct_SchemeDetails_t) SchemeDetails { isStable := true if cSD.IsStable == 0 { isStable = false } return SchemeDetails{ C.GoString(cSD.Identifier), C.GoString(cSD.LangCode), C.GoString(cSD.DisplayName), C.GoString(cSD.Author), C.GoString(cSD.CompiledDate), isStable, } } // GetSchemeDetails get scheme details func (handle *VarnamHandle) GetSchemeDetails() SchemeDetails { return makeGoSchemeDetails(C.varnam_get_scheme_details(handle.connectionID)) } // GetVSTPath Get path to VST of current handle func (handle *VarnamHandle) GetVSTPath() string { cStr := C.varnam_get_vst_path(handle.connectionID) defer C.free(unsafe.Pointer(cStr)) return C.GoString(cStr) } func makeGoSymbol(cSymbol *C.Symbol) Symbol { var goSymbol Symbol goSymbol.Identifier = int(cSymbol.Identifier) goSymbol.Type = int(cSymbol.Type) goSymbol.MatchType = int(cSymbol.MatchType) goSymbol.Pattern = C.GoString(cSymbol.Pattern) goSymbol.Value1 = C.GoString(cSymbol.Value1) goSymbol.Value2 = C.GoString(cSymbol.Value2) goSymbol.Value3 = C.GoString(cSymbol.Value3) goSymbol.Tag = C.GoString(cSymbol.Tag) goSymbol.Weight = int(cSymbol.Weight) goSymbol.Priority = int(cSymbol.Priority) goSymbol.AcceptCondition = int(cSymbol.AcceptCondition) goSymbol.Flags = int(cSymbol.Flags) return goSymbol } func NewSearchSymbol() Symbol { var resultPointer *C.Symbol C.varnam_new_search_symbol(&resultPointer) return makeGoSymbol(resultPointer) } // SearchSymbolTable search VST func (handle *VarnamHandle) SearchSymbolTable(ctx context.Context, searchCriteria Symbol) []Symbol { var goResults []Symbol operationID := makeContextOperation() select { case <-ctx.Done(): return goResults default: Identifier := C.int(searchCriteria.Identifier) Type := C.int(searchCriteria.Type) MatchType := C.int(searchCriteria.MatchType) Pattern := C.CString(searchCriteria.Pattern) Value1 := C.CString(searchCriteria.Value1) Value2 := C.CString(searchCriteria.Value2) Value3 := C.CString(searchCriteria.Value3) Tag := C.CString(searchCriteria.Tag) Weight := C.int(searchCriteria.Weight) Priority := C.int(searchCriteria.Priority) AcceptCondition := C.int(searchCriteria.AcceptCondition) Flags := C.int(searchCriteria.Flags) symbol := C.makeSymbol(Identifier, Type, MatchType, Pattern, Value1, Value2, Value3, Tag, Weight, Priority, AcceptCondition, Flags) var resultPointer *C.varray defer C.destroySymbolArray(unsafe.Pointer(resultPointer)) code := C.varnam_search_symbol_table(handle.connectionID, operationID, *symbol, &resultPointer) if code != C.VARNAM_SUCCESS { return goResults } i := 0 for i < int(C.varray_length(resultPointer)) { result := (*C.Symbol)(C.varray_get(resultPointer, C.int(i))) goResults = append(goResults, makeGoSymbol(result)) i++ } return goResults } } // GetVSTDir Get path to directory containging the VSTs func GetVSTDir() string { cStr := C.varnam_get_vst_dir() defer C.free(unsafe.Pointer(cStr)) return C.GoString(cStr) } // GetAllSchemeDetails get all available scheme details. The bool is for error func GetAllSchemeDetails() ([]SchemeDetails, bool) { cSchemeDetails := C.varnam_get_all_scheme_details() if cSchemeDetails == nil { return nil, true } var schemeDetails []SchemeDetails i := 0 for i < int(C.varray_length(cSchemeDetails)) { cSD := (*C.SchemeDetails)(C.varray_get(cSchemeDetails, C.int(i))) schemeDetails = append(schemeDetails, makeGoSchemeDetails(cSD)) i++ } go C.destroySchemeDetailsArray(unsafe.Pointer(cSchemeDetails)) return schemeDetails, false } govarnam-1.9.0/govarnamgo/govarnamgo_ml_inscript_test.go000066400000000000000000000011331420445125700236260ustar00rootroot00000000000000package govarnamgo import ( "context" "testing" ) func TestMLInscriptTransilterateGreedyTokenized(t *testing.T) { varnam := getVarnamInstance("ml-inscript") assertEqual(t, varnam.TransliterateGreedyTokenized("EnhdhgB")[0].Word, "ആലപ്പുഴ") } func TestMLInscriptGetSuggestions(t *testing.T) { varnam := getVarnamInstance("ml-inscript") varnam.Learn("ഇടുക്കി", 0) sugs, err := varnam.GetSuggestions( context.Background(), varnam.TransliterateGreedyTokenized("F'")[0].Word, // ഇട ) checkError(err) assertEqual(t, sugs[0].Word, "ഇടുക്കി") } govarnam-1.9.0/govarnamgo/govarnamgo_ml_test.go000066400000000000000000000047451420445125700217270ustar00rootroot00000000000000package govarnamgo import ( "context" "os" "path" "testing" ) func TestSchemeDetails(t *testing.T) { varnam := getVarnamInstance("ml") assertEqual(t, varnam.GetSchemeDetails().Identifier, "ml") assertEqual(t, varnam.GetSchemeDetails().DisplayName, "Malayalam") } func TestTransliterate(t *testing.T) { varnam := getVarnamInstance("ml") result, err := varnam.Transliterate(context.Background(), "nithyam") checkError(err) assertEqual(t, result[0].Word, "നിത്യം") } func TestTransliterateAdvanced(t *testing.T) { varnam := getVarnamInstance("ml") result, err := varnam.TransliterateAdvanced(context.Background(), "nithyam") checkError(err) assertEqual(t, result.TokenizerSuggestions[0].Word, "നിത്യം") } func TestReverseTransliterate(t *testing.T) { varnam := getVarnamInstance("ml") rt, err := varnam.ReverseTransliterate("നിത്യം") checkError(err) assertEqual(t, rt[0].Word, "nithyam") } func TestLearn(t *testing.T) { varnam := getVarnamInstance("ml") filePath := path.Join(testTempDir, "report.txt") file, err := os.Create(filePath) if err != nil { return } defer file.Close() file.WriteString(`നിത്യഹരിത 120 വൃക്ഷമാണ് 89 ഒരേയൊരു 45 ഏഷ്യയുടെ 100 മേലാപ്പും 12 aadc 10`) learnStatus, verr := varnam.LearnFromFile(filePath) checkError(verr) assertEqual(t, learnStatus.TotalWords, 6) assertEqual(t, learnStatus.FailedWords, 1) result, err := varnam.TransliterateAdvanced(context.Background(), "nithyaharitha") assertEqual(t, result.ExactWords[0].Weight, 120) result, err = varnam.TransliterateAdvanced(context.Background(), "melaappum") assertEqual(t, result.ExactWords[0].Weight, 12) } func TestRecentlyLearnedWords(t *testing.T) { varnam := getVarnamInstance("ml") words := []string{"ആലപ്പുഴ", "എറണാകുളം", "തൃശ്ശൂർ", "മലപ്പുറം", "കോഴിക്കോട്"} for _, word := range words { varnam.Learn(word, 0) } result, err := varnam.GetRecentlyLearntWords(context.Background(), 0, len(words)) checkError(err) assertEqual(t, len(result), len(words)) for i, sug := range result { assertEqual(t, sug.Word, words[len(words)-i-1]) } } func TestSearchSymbolTable(t *testing.T) { varnam := getVarnamInstance("ml") symbol := NewSearchSymbol() symbol.Pattern = "la" result := varnam.SearchSymbolTable(context.Background(), symbol) assertEqual(t, result[0].Value1, "ല") } govarnam-1.9.0/govarnamgo/govarnamgo_test.go000066400000000000000000000027351420445125700212340ustar00rootroot00000000000000package govarnamgo import ( "io/ioutil" "log" "os" "os/exec" "reflect" "runtime/debug" "strings" "sync" "testing" ) var varnamInstances = map[string]*VarnamHandle{} var mutex = sync.RWMutex{} var testTempDir string func checkError(err error) { if err != nil { log.Fatal(err.Error()) } } // AssertEqual checks if values are equal // Thanks https://gist.github.com/samalba/6059502#gistcomment-2710184 func assertEqual(t *testing.T, a interface{}, b interface{}) { if a == b { return } debug.PrintStack() t.Errorf("Received %v (type %v), expected %v (type %v)", a, reflect.TypeOf(a), b, reflect.TypeOf(b)) } func setUp(schemeID string) { varnam, err := InitFromID(schemeID) checkError(err) mutex.Lock() varnamInstances[schemeID] = varnam mutex.Unlock() } func getVarnamInstance(schemeID string) *VarnamHandle { mutex.Lock() instance, ok := varnamInstances[schemeID] mutex.Unlock() if ok { return instance } return nil } func TestVersion(t *testing.T) { cmd := "echo $(git describe --abbrev=0 --tags || echo 'latest') | sed s/v//" cmdRun, buff := exec.Command("bash", "-c", cmd), new(strings.Builder) cmdRun.Stdout = buff cmdRun.Run() tagVersion := strings.TrimRight(buff.String(), "\n") assertEqual(t, GetVersion(), tagVersion) } func tearDown() { os.RemoveAll(testTempDir) } func TestMain(m *testing.M) { var err error testTempDir, err = ioutil.TempDir("", "govarnam_test") checkError(err) setUp("ml") setUp("ml-inscript") m.Run() tearDown() } govarnam-1.9.0/govarnamgo/run_tests.sh000077500000000000000000000006031420445125700200630ustar00rootroot00000000000000#!/bin/bash tmpDir=$(mktemp -d -t govarnamgo-test-XXXXXX) # We do this bash scripting way to set environment dir because # Go makes the environment while a C library loads, hence dynamic # environment variable setting won't work # https://github.com/golang/go/wiki/cgo#environmental-variables export VARNAM_LEARNINGS_DIR=$tmpDir go test -count=1 -cover govarnamgo/*.go rm -rf $tmpDirgovarnam-1.9.0/install.sh.in000077500000000000000000000024001420445125700157450ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" ARG1=${1:-install} if [ "$ARG1" == "install" ]; then sudo cp "$SCRIPT_DIR/varnamcli" "@INSTALL_PREFIX@/bin/varnamcli" sudo mkdir -p "@INSTALL_PREFIX@/lib/pkgconfig" sudo cp "$SCRIPT_DIR/@LIB_NAME@" "@INSTALL_PREFIX@/lib/@LIB_NAME@.@VERSION@" sudo ln -s "@INSTALL_PREFIX@/lib/@LIB_NAME@.@VERSION@" "@INSTALL_PREFIX@/lib/@LIB_NAME@" sudo cp "$SCRIPT_DIR/govarnam.pc" "@INSTALL_PREFIX@/lib/pkgconfig/" sudo mkdir -p "@INSTALL_PREFIX@/include/libgovarnam" sudo cp "$SCRIPT_DIR/"*.h "@INSTALL_PREFIX@/include/libgovarnam/" sudo ldconfig sudo mkdir -p "@INSTALL_PREFIX@/share/varnam/schemes" msg="Installation finished" echo "$msg" notify-send "$msg" &> /dev/null || true elif [ "$ARG1" == "uninstall" ]; then sudo rm "@INSTALL_PREFIX@/bin/varnamcli" "@INSTALL_PREFIX@/lib/@LIB_NAME@.@VERSION@" "@INSTALL_PREFIX@/lib/@LIB_NAME@" "@INSTALL_PREFIX@/lib/pkgconfig/govarnam.pc" sudo rm "@INSTALL_PREFIX@/include/libgovarnam/"* sudo rmdir "@INSTALL_PREFIX@/include/libgovarnam" sudo rm "@INSTALL_PREFIX@/share/varnam/schemes/"* sudo rmdir "@INSTALL_PREFIX@/share/varnam/schemes/" msg="Uninstallation finished" echo $msg else echo "Unknown argument" fi govarnam-1.9.0/quick-installer.sh000077500000000000000000000106171420445125700170120ustar00rootroot00000000000000#!/usr/bin/env bash set -e # Varnam Installer # Make a temp dir workDir=`mktemp -d -t "varnam-installerXXXX"` # Credits: https://gist.github.com/lukechilds/a83e1d7127b78fef38c2914c4ececc3c get_latest_release() { curl --silent "https://api.github.com/repos/varnamproject/$1/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' } version=0 versionNumber=0 schemesVersion=0 imeVersion=0 imeVersionNumber=0 arch=$(uname -m) confirm() { [[ "$1" == [yY] || "$1" == [yY][eE][sS] ]] } init_version() { version=$(get_latest_release "govarnam") schemesVersion=$(get_latest_release "schemes") imeVersion=$(get_latest_release "govarnam-ibus") if [ -z $version ] || [ -z $schemesVersion ] || [ -z $imeVersion ]; then echo "Couldn't find latest Varnam version. Possible reasons:" echo "1. No internet connection" echo "2. GitHub API Rate Limit (wait an hour for the rate limit to expire)" exit 1 fi versionNumber=${version/v/} imeVersionNumber=${imeVersion/v/} } install_govarnam() { cd $workDir releaseName="govarnam-$versionNumber-$arch" url="https://github.com/varnamproject/govarnam/releases/download/$version/$releaseName.zip" echo "Downloading $releaseName from $url" curl -L -o govarnam.zip "$url" unzip govarnam.zip echo "Installing $releaseName" cd $releaseName if [ -f /usr/local/lib/libgovarnam.so ]; then read -p "Found an existing GoVarnam installation. Replace it ? (yes/NO): " answer2 if confirm "$answer2"; then sudo rm /usr/local/lib/libgovarnam.so* else echo "Not installing $releaseName" fi fi ./install.sh } step1="Step 1: Install GoVarnam" step2="Step 2: Install your language support for GoVarnam" step3="Step 3: Install Varnam IBus Engine" echo "Welcome to Varnam Installer. https://varnamproject.github.io/" echo "" echo "This installation is a 3-step process." echo "" echo $step1 echo $step2 echo $step3 echo "" read -p "Start Step 1 ? (yes/NO): " answer init_version if confirm "$answer"; then install_govarnam fi langs="" list_schemes() { assetsURL=$(curl --silent 'https://api.github.com/repos/varnamproject/schemes/releases/latest' | grep '"assets_url":' | sed -E 's/.*"([^"]+)".*/\1/') langs=$(curl --silent $assetsURL | grep -E 'name(.*?).zip' | sed -E 's/.*"([^"]+)".*/\1/' | sed s/.zip//) echo $"$langs" echo "---" echo "all" } install_scheme() { cd $workDir schemeID="$1" releaseName="$schemeID" url="https://github.com/varnamproject/schemes/releases/download/$schemesVersion/$releaseName.zip" echo "Downloading $releaseName from $url" curl -L -o "$releaseName.zip" "$url" unzip "$releaseName.zip" echo "Installing $releaseName" cd $releaseName ./install.sh if ls */*.vlf >/dev/null 2>&1; then # At least 1 file read -p "Found Varnam Learnings File (.vlf) to import words from. Import for '$schemeID' ? (yes/no): " answer2 if confirm "$answer2"; then ./import.sh fi fi } echo "" echo $step2 echo "" list_schemes echo "" read -p "Which language would you like to install ? (Separate by comma if there are multiple): " answer if [[ "$answer" == "all" ]]; then for lang in $langs; do # Trim whitespaces lang=`echo $lang | sed 's/ *$//g'` echo "Setup $lang" install_scheme "$lang" done else for lang in ${answer//,/ }; do # Trim whitespaces lang=`echo $lang | sed 's/ *$//g'` echo "Setup $lang" install_scheme "$lang" done fi install_govarnam_ibus_engine() { cd $workDir releaseName="varnam-ibus-engine-$imeVersionNumber-$arch" url="https://github.com/varnamproject/govarnam-ibus/releases/download/$imeVersion/$releaseName.zip" echo "Downloading $releaseName from $url" curl -L -o "$releaseName.zip" "$url" unzip "$releaseName.zip" echo "Installing $releaseName" cd $releaseName ./install.sh } echo "" echo $step3 echo "" read -p "Start Step 3 ? (yes/NO): " answer if confirm "$answer"; then install_govarnam_ibus_engine fi echo "" echo "-----------------------------" echo "Varnam Installation Finished!" echo "" echo "Log Out & Log In again for changes to take effect !!" echo "" echo "Getting Started: https://varnamproject.github.io/docs/getting-started/" echo "" echo "For help contact:" echo "Telegram Group: https://t.me/varnamproject" echo "Matrix Group: https://matrix.to/#/#varnamproject:poddery.com" echo "" echo "Website: https://varnamproject.github.io" echo "-----------------------------"