Repository: ayoungprogrammer/Lango Branch: master Commit: 0c4284c153ab Files: 22 Total size: 70.2 KB Directory structure: gitextract_ngclx9sm/ ├── .gitignore ├── LICENSE.txt ├── docs/ │ ├── Makefile │ ├── conf.py │ ├── index.rst │ ├── installation.rst │ ├── lango.matcher.rst │ ├── lango.parser.rst │ ├── lango.rst │ ├── make.bat │ ├── matching.rst │ └── modules.rst ├── docs.md ├── examples/ │ ├── matching.py │ ├── multimatch.py │ └── parser_input.py ├── lango/ │ ├── __init__.py │ ├── matcher.py │ └── parser.py ├── readme.md ├── requirements.txt └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store stanford-parser* stanford-corenlp* build* dist* Lango.egg-info* _build* _templates* *.pyc ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".x Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: docs/Makefile ================================================ # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/lango.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/lango.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/lango" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/lango" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ================================================ FILE: docs/conf.py ================================================ # -*- coding: utf-8 -*- # # lango documentation build configuration file, created by # sphinx-quickstart on Wed May 25 00:07:47 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import lango # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinxcontrib.napoleon', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'lango' copyright = '2016, Michael Young' author = 'Michael Young' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = lango.__version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'langodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'lango.tex', 'lango Documentation', 'Michael Young', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'lango', 'lango Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'lango', 'lango Documentation', author, 'lango', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. #epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the Pillow. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True ================================================ FILE: docs/index.rst ================================================ .. lango documentation master file, created by sphinx-quickstart on Wed May 25 00:07:47 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Lango's documentation! ================================= .. toctree:: installation matching Reference ========== .. toctree:: :maxdepth: 4 lango Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ================================================ FILE: docs/installation.rst ================================================ Installation ================================= Install package with pip ~~~~~~~~~~~~~~~~~~~~~~~~ :: pip install lango Download Stanford CoreNLP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Make sure you have Java installed for the Stanford CoreNLP to work. `Download Stanford CoreNLP`_ Extract to any folder Run Server ~~~~~~~~~~~~~~~~~~~~~~~~~ In extracted folder, run the following command to start the server: :: java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer .. _Download Stanford CoreNLP: http://stanfordnlp.github.io/CoreNLP/#download ================================================ FILE: docs/lango.matcher.rst ================================================ lango.matcher module ==================== .. automodule:: lango.matcher :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/lango.parser.rst ================================================ lango.parser module =================== .. automodule:: lango.parser :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/lango.rst ================================================ lango package ============= Submodules ---------- .. toctree:: lango.matcher lango.parser Module contents --------------- .. automodule:: lango :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/make.bat ================================================ @ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 1>NUL 2>NUL if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\lango.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\lango.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end ================================================ FILE: docs/matching.rst ================================================ Matching -------- Matching is done by comparing a set rules and matching it with a parse tree. You can see parse trees for sentences from examples/parser\_input.py. The set of rules is recursive and can match multiple parts of the parse tree. Rules can be broken down into smaller parts: - Tag - Token - Token Tree - Rules Tag ~~~ A tag is a POS (part of speech) tag to match. A list of POS tags used by the Stanford Parser can be found `here`_. :: Format: tag = string Example: 'NP' 'VP' 'PP' Token ~~~~~ A token is a string comprising of a tag and modifiers/labels for matching. We specify a match_label to match the tag to. We can specify opts for extracting the string from a tree. We can specify eq for matching the tree to a string. :: Example string: The red car opts -o Get object by removing "a", "the", etc. (Ex. red car) -r Get raw string (Ex. The red car) :: Format: (only tag is required) token = tag:match_label-opts=eq Example: 'VP' 'NP:subject-o' 'NP:np' 'VP=run' 'VP:action=run' Token Tree ~~~~~~~~~~ A token tree is a recursive tree of tokens. The tree matches the structure of a parse tree. :: Format: token_tree = ( token token_tree token_tree ... ) Examples: '( NP ( DT ) ( NP:subject-o ) )' '( NP )' '( PP ( TO=to ) ( NP:object-o ) )' Rules ~~~~~ Rules are a dictionary of token trees to dictionaries of matching labels to a nested set of rules. :: Format: rules = {token_tree: {match_label: rules}} Example: { '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )': { 'np': { '( NP:subject-o )': {} }, 'pp': { '( PP ( TO=to ) ( NP:to_object-o ) )': {}, '( PP ( IN=from ) ( NP:from_object-o ) )': {}, } }, } When matching a rule to a parse tree, the token tree is first matched. Then, all matching tags are matched to nested rules corresponding to their matching label. All nested match labels must have a subrule match or the rules will not match. The first rule to match is returned so the order of match is based on key ordering (use OrderedDict if order matters). Once a rule is matched, it calls the callback function with the context as arguments. Example ~~~~~~~ Suppose we have the sentence “Sam ran to his house” and we wanted to match the subject (“Sam”), the object to (“his house”) and the action (“ran”). Sample parse tree for “Sam ran to his house” from the Stanford Parser. :: (S (NP (NNP Sam) ) (VP (VBD ran) (PP (TO to) (NP (PRP$ his) (NN house) ) ) ) ) Simplified image of tree: .. figure:: /_static/img/sent_tree.png :alt: tree tree :: Matching: Parse Tree: (S (NP (NNP Sam) ) (VP (VBD ran) (PP (TO to) (NP (PRP$ his) (NN house)))) Matched token tree: '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )' Matched context: np: (NP (NNP Sam)) action-o: 'ran' pp: (PP (TO to) (NP (PRP$ his) (NN house))) Rule for ‘( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )’: .. figure:: /_static/img/rule_tree_1.png :alt: tree tree Matching ‘NP’ matches the whole NP tree and converts to a word: .. _here: https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html :: Matched token tree for np: '( NP:subject-o )' Matched context: subject-o: 'Sam' Matching ‘PP’ requires matching the nested rules: :: Match token tree for pp: '( PP ( TO=to ) ( NP:to_object-o ) )' Match context: object-o: 'his house' Match token tree for pp: '( PP ( IN=from ) ( NP:from_object-o ) )' No match found PP of the sample sentence: .. figure:: /_static/img/sent_tree_pp.png :alt: tree tree Nested PP rules: |tree2| |tree3| Only the first rule matches for ‘PP’. Now that we have a match for all nested rules, we can return the context: :: Returned context: action: 'ran' subject: 'sam' to_object: 'his house' Full code: .. code:: python from lango.parser import StanfordLibParser from lango.matcher import match_rules parser = StanfordLibParser() rules = { '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )': { 'np': { '( NP:subject-o )': {} }, 'pp': { '( PP ( TO=to ) ( NP:to_object-o ) )': {}, '( PP ( IN=from ) ( NP:from_object-o ) )': {} } } } def fun(subject, action, to_object=None, from_object=None): print "%s,%s,%s,%s" % (subject, action, to_object, from_object) tree = parser.parse('Sam ran to his house') match_rules(tree, rules, fun) # output should be: sam, ran, his house, None tree = parser.parse('Billy walked from his apartment') match_rules(tree, rules, fun) # output should be: billy, walked, None, his apartment .. |tree2| image:: /_static/img/rule_tree_2.png .. |tree3| image:: /_static/img/rule_tree_3.png ================================================ FILE: docs/modules.rst ================================================ lango ===== .. toctree:: :maxdepth: 4 lango ================================================ FILE: docs.md ================================================ # Docs Pip Installs ``` sphinx-autobuild==0.6.0 sphinx-rtd-theme==0.1.9 sphinxcontrib-napoleon==0.5.0 ``` Generate docs ``` sphinx-apidoc -f -e -o docs lango cd docs make html ``` ## Development ``` python setup.py develop ``` ================================================ FILE: examples/matching.py ================================================ from collections import OrderedDict import os from lango.parser import StanfordServerParser from lango.matcher import match_rules parser = StanfordServerParser() sents = [ 'Call me an Uber.', 'Get my mother some flowers.', 'Find me a pizza with extra cheese.', 'Give Sam\'s dog a biscuit from Petshop.' ] """ me.call({'item': u'uber'}) my.mother.get({'item': u'flowers'}) me.order({'item': u'pizza', u'with': u'extra cheese'}) sam.dog.give({'item': u'biscuit', u'from': u'petshop'}) """ subj_obj_rules = { 'subj_t': OrderedDict([ # my brother / my mother ('( NP ( PRP$:subject-o=my ) ( NN:relation-o ) )', {}), # Sam's dog ('( NP ( NP ( NNP:subject-o ) ( POS ) ) ( NN:relation-o ) )', {}), # me ('( NP:subject-o )', {}), ]), 'obj_t': OrderedDict([ # pizza with onions ('( NP ( NP:item-O ) ( PP ( IN:item_in-O ) ( NP:item_addon-O ) ) )', {}), # pizza ('( NP:item-O )', {}), ]) } rules = { # Get me a pizza '( S ( VP ( VB:action-o ) ( S ( NP:subj_t ) ( NP:obj_t ) ) ) )': subj_obj_rules, # Get my mother flowers '( S ( VP ( VB:action-o ) ( NP:subj_t ) ( NP:obj_t ) ) )': subj_obj_rules, } def perform_action(action, item, subject, relation=None, item_addon=None, item_in=None): entity = subject if entity == "my": entity = "me" if relation: entity = '{0}.{1}'.format(entity, relation) item_props = {'item': item} if item_in and item_addon: item_props[item_in] = item_addon return '{0}.{1}({2})'.format(entity, action, item_props) for sent in sents: tree = parser.parse(sent) print(match_rules(tree, rules, perform_action)) ================================================ FILE: examples/multimatch.py ================================================ from collections import OrderedDict import os from lango.parser import StanfordServerParser from lango.matcher import match_rules parser = StanfordServerParser() sents = [ 'What religion is the President of the United States?' ] rules = { '( SBARQ ( WHNP/WHADVP:wh_t ) ( SQ ( VBZ ) ( NP:np_t ) ) )': { 'np_t': { '( NP ( NP:subj-o ) ( PP ( IN:subj_in-o ) ( NP:obj-o ) ) )': {}, '( NP:subj-o )': {}, }, 'wh_t': { '( WHNP:whnp ( WDT ) ( NN:prop-o ) )': {}, '( WHNP/WHADVP:qtype-o )': {}, } }, '( SBARQ:subj-o )': {}, } keys = ['subj', 'subj_in', 'obj', 'prop', 'qtype'] for sent in sents: tree = parser.parse(sent) contexts = match_rules(tree, rules, multi=True) for context in contexts: print(", ".join(['%s:%s' % (k, context.get(k)) for k in keys])) """ 5 possible matches: subj:president of united states, subj_in:None, obj:None, prop:religion, qtype:None subj:president of united states, subj_in:None, obj:None, prop:None, qtype:what religion subj:president, subj_in:of, obj:united states, prop:religion, qtype:None subj:president, subj_in:of, obj:united states, prop:None, qtype:what religion subj:what religion is president of united states ?, subj_in:None, obj:None, prop:None, qtype:None """ ================================================ FILE: examples/parser_input.py ================================================ import os from lango.parser import StanfordServerParser from lango.matcher import match_rules def main(): parser = StanfordServerParser() while True: try: line = input("Enter line: ") tree = parser.parse(line) tree.pretty_print() except EOFError: print("Bye!") sys.exit(0) if __name__ == "__main__": main() ================================================ FILE: lango/__init__.py ================================================ """ Lango is a natural language framework for matching parse trees and modeling conversations. """ __version__ = '0.21.0' ================================================ FILE: lango/matcher.py ================================================ from nltk import Tree import logging logger = logging.getLogger(__name__) def match_rules(tree, rules, fun=None, multi=False): """Matches a Tree structure with the given query rules. Query rules are represented as a dictionary of template to action. Action is either a function, or a dictionary of subtemplate parameter to rules:: rules = { 'template' : { 'key': rules } } | { 'template' : {} } Args: tree (Tree): Parsed tree structure rules (dict): A dictionary of query rules fun (function): Function to call with context (set to None if you want to return context) multi (Bool): If True, returns all matched contexts, else returns first matched context Returns: Contexts from matched rules """ if multi: context = match_rules_context_multi(tree, rules) else: context = match_rules_context(tree, rules) if not context: return None if fun: args = fun.__code__.co_varnames if multi: res = [] for c in context: action_context = {} for arg in args: if arg in c: action_context[arg] = c[arg] res.append(fun(**action_context)) return res else: action_context = {} for arg in args: if arg in context: action_context[arg] = context[arg] return fun(**action_context) else: return context def match_rules_context(tree, rules, parent_context={}): """Recursively matches a Tree structure with rules and returns context Args: tree (Tree): Parsed tree structure rules (dict): See match_rules parent_context (dict): Context of parent call Returns: dict: Context matched dictionary of matched rules or None if no match """ for template, match_rules in rules.items(): context = parent_context.copy() if match_template(tree, template, context): for key, child_rules in match_rules.items(): child_context = match_rules_context(context[key], child_rules, context) if child_context: for k, v in child_context.items(): context[k] = v else: return None return context return None def cross_context(contextss): """ Cross product of all contexts [[a], [b], [c]] -> [[a] x [b] x [c]] """ if not contextss: return [] product = [{}] for contexts in contextss: tmp_product = [] for c in contexts: for ce in product: c_copy = c.copy() c_copy.update(ce) tmp_product.append(c_copy) product = tmp_product return product def match_rules_context_multi(tree, rules, parent_context={}): """Recursively matches a Tree structure with rules and returns context Args: tree (Tree): Parsed tree structure rules (dict): See match_rules parent_context (dict): Context of parent call Returns: dict: Context matched dictionary of matched rules or None if no match """ all_contexts = [] for template, match_rules in rules.items(): context = parent_context.copy() if match_template(tree, template, context): child_contextss = [] if not match_rules: all_contexts += [context] else: for key, child_rules in match_rules.items(): child_contextss.append(match_rules_context_multi(context[key], child_rules, context)) all_contexts += cross_context(child_contextss) return all_contexts def match_template(tree, template, args=None): """Check if match string matches Tree structure Args: tree (Tree): Parsed Tree structure of a sentence template (str): String template to match. Example: "( S ( NP ) )" Returns: bool: If they match or not """ tokens = get_tokens(template.split()) cur_args = {} if match_tokens(tree, tokens, cur_args): if args is not None: for k, v in cur_args.items(): args[k] = v logger.debug('MATCHED: {0}'.format(template)) return True else: return False def match_tokens(tree, tokens, args): """Check if stack of tokens matches the Tree structure Special matching rules that can be specified in the template:: ':label': Label a token, the token will be returned as part of the context with key 'label'. '-@': Additional single letter argument determining return format of labeled token. Valid options are: '-r': Return token as word '-o': Return token as object '=word|word2|....|wordn': Force match raw lower case '$': Match end of tree Args: tree : Parsed tree structure tokens : Stack of tokens Returns: Boolean if they match or not """ arg_type_to_func = { 'r': get_raw_lower, 'R': get_raw, 'o': get_object_lower, 'O': get_object, } if len(tokens) == 0: return True if not isinstance(tree, Tree): return False root_token = tokens[0] # Equality if root_token.find('=') >= 0: eq_tokens = root_token.split('=')[1].lower().split('|') root_token = root_token.split('=')[0] word = get_raw_lower(tree) if word not in eq_tokens: return False # Get arg if root_token.find(':') >= 0: arg_tokens = root_token.split(':')[1].split('-') if len(arg_tokens) == 1: arg_name = arg_tokens[0] args[arg_name] = tree else: arg_name = arg_tokens[0] arg_type = arg_tokens[1] args[arg_name] = arg_type_to_func[arg_type](tree) root_token = root_token.split(':')[0] # Does not match wild card and label does not match if root_token != '.' and tree.label() not in root_token.split('/'): return False # Check end symbol if tokens[-1] == '$': if len(tree) != len(tokens[:-1]) - 1: return False else: tokens = tokens[:-1] # Check # of tokens if len(tree) < len(tokens) - 1: return False for i in range(len(tokens) - 1): if not match_tokens(tree[i], tokens[i + 1], args): return False return True def get_tokens(tokens): """Recursively gets tokens from a match list Args: tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')'] Returns: Stack of tokens """ tokens = tokens[1:-1] ret = [] start = 0 stack = 0 for i in range(len(tokens)): if tokens[i] == '(': if stack == 0: start = i stack += 1 elif tokens[i] == ')': stack -= 1 if stack < 0: raise Exception('Bracket mismatch: ' + str(tokens)) if stack == 0: ret.append(get_tokens(tokens[start:i + 1])) else: if stack == 0: ret.append(tokens[i]) if stack != 0: raise Exception('Bracket mismatch: ' + str(tokens)) return ret def get_object(tree): """Get the object in the tree object. Method should remove unnecessary letters and words:: the a/an 's Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "red car")`` """ if isinstance(tree, Tree): if tree.label() == 'DT' or tree.label() == 'POS': return '' words = [] for child in tree: words.append(get_object(child)) return ' '.join([_f for _f in words if _f]) else: return tree def get_object_lower(tree): return get_object(tree).lower() def get_raw(tree): """Get the exact words in lowercase in the tree object. Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "The red car")`` """ if isinstance(tree, Tree): words = [] for child in tree: words.append(get_raw(child)) return ' '.join(words) else: return tree def get_raw_lower(tree): return get_raw(tree).lower() ================================================ FILE: lango/parser.py ================================================ from nltk.parse.stanford import StanfordParser, GenericStanfordParser from nltk.internals import find_jars_within_path from nltk.tree import Tree from pycorenlp import StanfordCoreNLP class Parser: """Abstract Parser class""" def __init__(): pass def parse(self, sent): pass class OldStanfordLibParser(Parser): """For StanfordParser < 3.6.0""" def __init__(self): self.parser = StanfordParser() def parse(self, line): """Returns tree objects from a sentence Args: line: Sentence to be parsed into a tree Returns: Tree object representing parsed sentence None if parse fails """ tree = list(self.parser.raw_parse(line))[0] tree = tree[0] return tree class StanfordLibParser(OldStanfordLibParser): """For StanfordParser == 3.6.0""" def __init__(self): self.parser = StanfordParser( model_path='edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz') stanford_dir = self.parser._classpath[0].rpartition('/')[0] self.parser._classpath = tuple(find_jars_within_path(stanford_dir)) class StanfordServerParser(Parser, GenericStanfordParser): """Follow the readme to setup the Stanford CoreNLP server""" def __init__(self, host='localhost', port=9000, properties={}): url = 'http://{0}:{1}'.format(host, port) self.nlp = StanfordCoreNLP(url) if not properties: self.properties = { 'annotators': 'parse', 'outputFormat': 'json', } else: self.properties = properties def _make_tree(self, result): return Tree.fromstring(result) def parse(self, sent): output = self.nlp.annotate(sent, properties=self.properties) # Got random html, return empty tree if isinstance(output, str): return Tree('', []) parse_output = output['sentences'][0]['parse'] + '\n\n' tree = next(next(self._parse_trees_output(parse_output)))[0] return tree ================================================ FILE: readme.md ================================================ # Lango [![Gitter](https://badges.gitter.im/lango-nlp/Lobby.svg)](https://gitter.im/lango-nlp/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) Lango is a natural language processing library for working with the building blocks of language. It includes tools for: * matching [constituent parse trees](https://en.wikipedia.org/wiki/Parse_tree#Constituency-based_parse_trees). * modeling conversations (TODO) Need help? Ask me for help on [Gitter](https://gitter.im/lango-nlp/Lobby) ## Installation ### Install package with pip ``` pip install lango ``` ### Download Stanford CoreNLP Make sure you have Java installed for the Stanford CoreNLP to work. [Download Stanford CoreNLP](http://stanfordnlp.github.io/CoreNLP/#download) Extract to any folder ### Run the Stanford CoreNLP server Run the following command in the folder where you extracted Stanford CoreNLP ``` java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer ``` ## Docs - [Blog Post](http://blog.ayoungprogrammer.com/2016/07/natural-language-understanding-by.html/) - [Read the docs](http://lango.readthedocs.io/en/latest/) - [Examples](http://github.com/ayoungprogrammer/lango/tree/master/examples) ## Matching Matching is done by comparing a set rules and matching it with a parse tree. You can see parse trees for sentences from examples/parser_input.py. The set of rules is recursive and can match multiple parts of the parse tree. Rules can be broken down into smaller parts: - Tag - Token - Token Tree - Rules ### Tag A tag is a POS (part of speech) tag to match. A list of POS tags used by the Stanford Parser can be found [here](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html). ``` Format: tag = string Example: 'NP' 'VP' 'PP' ``` ### Token A token is a string comprising of a tag and modifiers/labels for matching. We specify a match_label to match the tag to. We can specify opts for extracting the string from a tree. We can specify eq for matching the tree to a string. ``` Example string: The red car opts: -o Get object by removing "a", "the", etc. (Ex. red car) -r Get raw string (Ex. The red car) ``` ``` Format: (only tag is required) token = tag:match_label-opts=eq Example: 'VP' 'NP:subject-o' 'NP:np' 'VP=run' 'VP:action=run' ``` ### Token Tree A token tree is a recursive tree of tokens. The tree matches the structure of a parse tree. ``` Format: token_tree = ( token token_tree token_tree ... ) Examples: '( NP ( DT ) ( NP:subject-o ) )' '( NP )' '( PP ( TO=to ) ( NP:object-o ) )' ``` ### Rules Rules are a dictionary of token trees to dictionaries of matching labels to a nested set of rules. ``` Format: rules = {token_tree: {match_label: rules}} Example: { '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )': { 'np': { '( NP:subject-o )': {} }, 'pp': { '( PP ( TO=to ) ( NP:to_object-o ) )': {}, '( PP ( IN=from ) ( NP:from_object-o ) )': {}, } }, } ``` When matching a rule to a parse tree, the token tree is first matched. Then, all matching tags are matched to nested rules corresponding to their matching label. All nested match labels must have a subrule match or the rules will not match. The first rule to match is returned so the order of match is based on key ordering (use OrderedDict if order matters). Once a rule is matched, it calls the callback function with the context as arguments. ### Example Suppose we have the sentence "Sam ran to his house" and we wanted to match the subject ("Sam"), the object ("his house") and the action ("ran"). Sample parse tree for "Sam ran to his house" from the Stanford Parser. ``` (S (NP (NNP Sam) ) (VP (VBD ran) (PP (TO to) (NP (PRP$ his) (NN house) ) ) ) ) ``` Simplified image of tree: ![tree](/docs/_static/img/sent_tree.png) ``` Matching: Parse Tree: (S (NP (NNP Sam) ) (VP (VBD ran) (PP (TO to) (NP (PRP$ his) (NN house)))) Matched token tree: '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )' Matched context: np: (NP (NNP Sam)) action-o: 'ran' pp: (PP (TO to) (NP (PRP$ his) (NN house))) ``` Rule for '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )': ![tree](/docs/_static/img/rule_tree_1.png) Matching 'NP' matches the whole NP tree and converts to a word: ``` Matched token tree for np: '( NP:subject-o )' Matched context: subject-o: 'Sam' ``` Matching 'PP' requires matching the nested rules: ``` Match token tree for pp: '( PP ( TO=to ) ( NP:to_object-o ) )' Match context: object-o: 'his house' Match token tree for pp: '( PP ( IN=from ) ( NP:from_object-o ) )' No match found ``` PP of the sample sentence: ![tree](/docs/_static/img/sent_tree_pp.png) Nested PP rules: ![tree](/docs/_static/img/rule_tree_2.png) ![tree](/docs/_static/img/rule_tree_3.png) Only the first rule matches for 'PP'. Now that we have a match for all nested rules, we can return the context: ``` Returned context: action: 'ran' subject: 'sam' to_object: 'his house' ``` Full code: ```python from lango.parser import StanfordServerParser from lango.matcher import match_rules parser = StanfordServerParser() rules = { '( S ( NP:np ) ( VP ( VBD:action-o ) ( PP:pp ) ) )': { 'np': { '( NP:subject-o )': {} }, 'pp': { '( PP ( TO=to ) ( NP:to_object-o ) )': {}, '( PP ( IN=from ) ( NP:from_object-o ) )': {} } } } def fun(subject, action, to_object=None, from_object=None): print "%s,%s,%s,%s" % (subject, action, to_object, from_object) tree = parser.parse('Sam ran to his house') match_rules(tree, rules, fun) # output should be: sam, ran, his house, None tree = parser.parse('Billy walked from his apartment') match_rules(tree, rules, fun) # output should be: billy, walked, None, his apartment ``` ================================================ FILE: requirements.txt ================================================ nltk==3.1 pycorenlp==0.3.0 ================================================ FILE: setup.py ================================================ from setuptools import find_packages, setup import lango setup( name='Lango', version=lango.__version__, description='Natural Language Framework for Matching Parse Trees and Modeling Conversation', packages=find_packages(), author='Michael Young', author_email='michaelyoung1995@gmail.com', url='https://github.com/ayoungprogrammer/lango', scripts=[], install_requires=[ 'nltk', 'pycorenlp' ], )