├── .coveragerc ├── .dockerignore ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CHANGES.rst ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── ISSUE_TEMPLATE.md ├── LICENSE.txt ├── NOTES.md ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── docker-compose.yml ├── docs ├── ARCHI.md ├── CONTRIBUTING.md ├── Makefile ├── _static │ └── .gitignore ├── adam_arch.png ├── adam_qa_pipeline.png ├── adam_qa_research_paper.pdf ├── authors.rst ├── changes.rst ├── conf.py ├── index.rst ├── license.rst └── resources.rst ├── qas ├── __init__.py ├── about.py ├── adam.py ├── anaphora_res.py ├── candidate_ans.py ├── classifier │ ├── __init__.py │ ├── question_classifier.py │ └── question_classifier_trainer.py ├── constants.py ├── corpus │ ├── WikiQA.tsv │ ├── __init__.py │ ├── data.py │ ├── feature_trainer.csv │ ├── know_corp.txt │ ├── know_corp_raw.txt │ ├── qa_test.db │ ├── qclasses.txt │ ├── qclassification_data.txt │ ├── qclassifier_trainer.csv │ ├── question_classifier.pkl │ ├── semi_feature_trainer.csv │ ├── stop_words.txt │ └── test_question.txt ├── doc_scorer.py ├── doc_search_rank.py ├── esstore │ ├── __init__.py │ ├── es_config.py │ ├── es_connect.py │ └── es_operate.py ├── feature_extractor.py ├── fetch_wiki.py ├── model │ ├── __init__.py │ ├── es_document.py │ └── query_container.py ├── qa_init.py ├── query_const.py ├── search_source.py ├── sqlitestore │ ├── __init__.py │ └── sqlt_connect.py ├── sys_info.py └── wiki │ ├── __init__.py │ ├── wiki_fetch.py │ ├── wiki_parse.py │ ├── wiki_query.py │ └── wiki_search.py ├── requirements-test.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── create_test_data.py ├── test_classify_question.py ├── test_construct_query.py ├── test_extract_features.py ├── test_wiki_scraper.py └── travis_install.sh └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | # .coveragerc to control coverage.py 2 | [run] 3 | branch = True 4 | source = qas 5 | # omit = bad_file.py 6 | 7 | [report] 8 | # Regexes for lines to exclude from consideration 9 | exclude_lines = 10 | # Have to re-enable the standard pragma 11 | pragma: no cover 12 | 13 | # Don't complain about missing debug-only code: 14 | def __repr__ 15 | if cls\.debug 16 | 17 | # Don't complain if tests don't hit defensive assertion code: 18 | raise AssertionError 19 | raise NotImplementedError 20 | 21 | # Don't complain if non-runnable code isn't run: 22 | if 0: 23 | if __name__ == .__main__.: 24 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .dockerignore 2 | __pycache__ 3 | *.pyc 4 | *.pyo 5 | *.pyd 6 | .Python 7 | env 8 | adam_env 9 | pip-log.txt 10 | .tox 11 | .coverage 12 | .coverage.* 13 | .cache 14 | coverage.xml 15 | *,cover 16 | *.log 17 | .git -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Temporary and binary files 2 | *~ 3 | *.py[cod] 4 | *.so 5 | *.cfg 6 | !setup.cfg 7 | *.orig 8 | *.log 9 | *.pot 10 | __pycache__/* 11 | .cache/* 12 | .*.swp 13 | */.ipynb_checkpoints/* 14 | 15 | # Project files 16 | .ropeproject 17 | .project 18 | .pydevproject 19 | .settings 20 | .idea 21 | 22 | # Package files 23 | *.egg 24 | *.eggs/ 25 | .installed.cfg 26 | *.egg-info 27 | 28 | # Unittest and coverage 29 | htmlcov/* 30 | .coverage 31 | .tox 32 | junit.xml 33 | coverage.xml 34 | 35 | # Build and docs folder/files 36 | build/* 37 | dist/* 38 | sdist/* 39 | docs/api/* 40 | docs/_build/* 41 | cover/* 42 | MANIFEST 43 | # Created by .ignore support plugin (hsz.mobi) 44 | ### Linux template 45 | *~ 46 | 47 | # temporary files which can be created if a process still has a handle open of a deleted file 48 | .fuse_hidden* 49 | 50 | # KDE directory preferences 51 | .directory 52 | 53 | # Linux trash folder which might appear on any partition or disk 54 | .Trash-* 55 | 56 | # .nfs files are created when an open file is removed but is still being accessed 57 | .nfs* 58 | ### Python template 59 | # Byte-compiled / optimized / DLL files 60 | __pycache__/ 61 | *.py[cod] 62 | *$py.class 63 | 64 | # C extensions 65 | *.so 66 | 67 | # Distribution / packaging 68 | .Python 69 | env/ 70 | adam_env/* 71 | build/ 72 | develop-eggs/ 73 | dist/ 74 | downloads/ 75 | eggs/ 76 | .eggs/ 77 | lib/ 78 | lib64/ 79 | parts/ 80 | sdist/ 81 | var/ 82 | wheels/ 83 | *.egg-info/ 84 | .installed.cfg 85 | *.egg 86 | 87 | # PyInstaller 88 | # Usually these files are written by a python script from a template 89 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 90 | *.manifest 91 | *.spec 92 | 93 | # Installer logs 94 | pip-log.txt 95 | pip-delete-this-directory.txt 96 | 97 | # Unit test / coverage reports 98 | htmlcov/ 99 | .tox/ 100 | .coverage 101 | .coverage.* 102 | .cache 103 | nosetests.xml 104 | coverage.xml 105 | *,cover 106 | .hypothesis/ 107 | 108 | # Translations 109 | *.mo 110 | *.pot 111 | 112 | # Django stuff: 113 | *.log 114 | local_settings.py 115 | 116 | # Flask stuff: 117 | instance/ 118 | .webassets-cache 119 | 120 | # Scrapy stuff: 121 | .scrapy 122 | 123 | # Sphinx documentation 124 | docs/_build/ 125 | 126 | # PyBuilder 127 | target/ 128 | 129 | # Jupyter Notebook 130 | .ipynb_checkpoints 131 | 132 | # pyenv 133 | .python-version 134 | 135 | # celery beat schedule file 136 | celerybeat-schedule 137 | 138 | # SageMath parsed files 139 | *.sage.py 140 | 141 | # dotenv 142 | .env 143 | 144 | # virtualenv 145 | .venv 146 | venv/ 147 | ENV/ 148 | 149 | # Spyder project settings 150 | .spyderproject 151 | 152 | # Rope project settings 153 | .ropeproject 154 | 155 | # MacOS .DS_Store 156 | .DS_Store 157 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: python 3 | 4 | python: 5 | - "3.5" 6 | - "3.6" 7 | 8 | os: 9 | - linux 10 | 11 | #virtualenv: 12 | # system_site_packages: true 13 | 14 | branches: 15 | only: 16 | - master 17 | - dev 18 | 19 | before_install: 20 | - pip install -r requirements-test.txt 21 | - wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.1.1-amd64.deb 22 | - sudo dpkg -i --force-confnew elasticsearch-7.1.1-amd64.deb 23 | - sudo chown -R elasticsearch:elasticsearch /etc/default/elasticsearch 24 | - sudo chown -R elasticsearch:elasticsearch /usr/share/elasticsearch 25 | - sudo service elasticsearch restart 26 | - until curl --silent -XGET --fail http://localhost:9200; do printf '.'; sleep 1; done 27 | 28 | install: 29 | - pip install -r requirements.txt 30 | 31 | #afterinstall: 32 | # - python -m spacy download en 33 | # - python -m spacy download en_core_web_md 34 | 35 | services: 36 | - elasticsearch 37 | 38 | script: 39 | - pytest --cov=codecov 40 | 41 | after_success: 42 | - codecov 43 | 44 | notifications: 45 | slack: 46 | secure: Az9G4l3zoYYTDLkEUJj/t0wqacM/ApCrr9RWWfP0PEinwBy7WlRxFUGrg3dhJ8rnfHBWmfndgQUvFqX7V3A9++85eqvj3Ik2y0bs/xcgundJRGpiEKKu2dvrfXP3uuvPrQI014Tbm3ZvA0aCTA1zz/iJTT8TUtm1pEAXRlbWUAzyfvqrNaMlfw0xFZ4nbIYwF8Fv+Q9TZ8cbAcgSOz9naMsYv/YOHSpviFOw6kMSNHoASP7vUrsxpCBqucJVXTlDdBz2IePUbbizZ5aEvRxQMKMCDFUb+j4K9prRvDJykCgYIkbGRwv3TNNjoingbtK2uC2awELUHwI+zg6Muyzc/xY1ngl3RPY7y71grLukzYSrY9T5onYtgU+4g42ioCebjlTbR5XsCqOLZS75cTqDPiU2lBca0nszAkQd+XzTz6nPPabnXY3ye9YNrutwsG6KFPppCFbuND8WzqmRIKH5yL7yviCW1jJrQIfk+ln3F6MyuFPt7Iqbse3U6tOsEr9usiGzrhbaRalc+QpJWZvF15DUgafbpVxAP31157Wxrz2bHPSJKbfPs4dGhY0VVd/IiCyhEe2IWWwQg04yLcLItZh80sthMkKu9WgLrPLlZ//0Zo5AgNduO50tyKKv+/Hk56bvcXSRFUK7jNxEnH4rKTGTBhjhJZ95N5uMlwOZDwE= 47 | email: false -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | Developers 3 | ========== 4 | 5 | * Shirish Kadam 6 | * Hobson Lane 7 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | Changelog 3 | ========= 4 | 5 | Version 0.1 6 | =========== 7 | 8 | - Added Travis CI Integration 9 | - Restructured project with PyScaffold 10 | - Migrated to spaCy 2.X 11 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at shirishkadam35@yahoo.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use an official Python runtime as a parent image 2 | FROM python:3.6-stretch 3 | 4 | LABEL maintainer="ziggerzz@gmail.com" 5 | 6 | # Set working directory 7 | WORKDIR /adam_qas 8 | 9 | # First copy and install the requirements so further cache can be used 10 | COPY ./requirements.txt ./requirements.txt 11 | 12 | # Install any needed packages specified in requirements.txt 13 | RUN pip install --default-timeout=3000 --trusted-host pypi.python.org -r requirements.txt 14 | 15 | # Copy the current directory contents into the container at /app 16 | COPY . /adam_qas 17 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | ## Your Environment 9 | 10 | 11 | ```bash 12 | $ python -m qas.sys_info 13 | ``` 14 | ``` 15 | # To get the system info, past the output of the above command here 16 | ``` 17 | * Question you were trying to ask: -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | Adam Qas, a question answering system 635 | Copyright (C) 2017 Shirish Kadam 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Adam Qas Copyright (C) 2017 Shirish Kadam 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NOTES.md: -------------------------------------------------------------------------------- 1 | ## SQUAD 2.0 2 | 3 | SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 new, unanswerable questions written adversarially 4 | by crowdworkers to look similar to answerable ones. 5 | 6 | Implementing: [U-Net: Machine Reading Comprehension with Unanswerable Questions, Fudan University & Liulishuo Lab]( 7 | https://arxiv.org/pdf/1810.06638.pdf) 8 | 9 | This paper decomposes the problem of Machine Reading Comprehension with unanswerable questions into three sub-tasks: 10 | answer pointer, no-answer pointer, and answer verifier. 11 | 12 | 1) an answer pointer to predict a canidate answer span for a question; 13 | 2) a no-answer pointer to avoid selecting any text span when a question has no answer; and 14 | 3) an answer verifier to determine the probability of the "unanswerability" of a question with candidate answer information. 15 | 16 | Introduce a universal node and process the question and its context passage as a single contiguous sequence of tokens, 17 | which greatly improves the conciseness of UNet. 18 | 19 | Represent the MRC problem as: given a set of tuples *(Q, P, A)*, 20 | where *Q = (q1, q2, · · · , qm)* is the question with *m* words, 21 | *P = (p1, p2, · · · , pn)* is the context passage with *n* words, 22 | and *A = prs:re* is the answer with *rs* and *re* indicating 23 | the start and end points, the task is to estimate the conditional probability *P(A|Q, P)*. 24 | 25 | #### 1) Unified Encoding 26 | 27 | **Embedding**: Embed both the question and the passage with Glove embedding and Elmo embedding. 28 | Use POS embedding, NER embedding, and a feature embedding that 29 | includes the exact match, lower-case match, lemma match, 30 | and a TF-IDF feature. Get the question representation *Q = qmi=1* and 31 | the passage representation *P = pni=1*, where each word is represented as a d-dim 32 | embedding by combining the features/embedding described above. 33 | 34 | **Universal Node**: We create a universal node *u*, to learn universal information from 35 | both passage and question. This universal node is added and 36 | connects the passage and question at the phase of embedding, 37 | and then goes along with the whole representation, so 38 | it is a key factor in information representation. 39 | 40 | We concatenated question representation, 41 | universal node representation, passage representation 42 | together as: 43 | 44 | *V = [Q, u, P] = [q1, q2 . . . qm, u, p1, p2, · · · , pn]* 45 | 46 | **Word-level Fusion**: Then we first use two-layer bidirectional 47 | LSTM (BiLSTM) to fuse the joint representation of question, universal 48 | node, and passage. 49 | 50 | *Hl = BiLSTM(V)* 51 | 52 | *Hh = BiLSTM(Hl)* 53 | 54 | *Hf = BiLSTM([Hl;Hh])* 55 | 56 | Thus, *H = [Hl; Hh; Hf]* represents the deep fusion information 57 | of the question and passage on word-level. When 58 | a BiLSTM is applied to encode representations, it learns 59 | the semantic information bi-directionally. Since the universal 60 | node *u* is between the question and passage, its hidden 61 | states hm+1 can learn both question and passage information. 62 | 63 | #### 2) Multi-Level Attention 64 | 65 | First divide *H* into two representations: attached passage 66 | *Hq* and attached question *Hp*, and let the universal node 67 | representation hm+1 attached to both the passage and question, 68 | 69 | *Hq = [h1, h2, · · · , hm+1]* 70 | 71 | *Hp = [hm+1, hm+2, · · · , hm+n+1]* 72 | 73 | Note *hm+1* is shared by *Hq* and *Hp*. Here the universal node 74 | works as a special information carrier, and both passage and 75 | question can focus attention information on this node so that 76 | the connection between them is closer than a traditional biattention 77 | interaction. 78 | 79 | We first compute the affine matrix of *Hlq* and *Hlp* by 80 | 81 | *S = (ReLU(W1Hlq))TReLU(W2Hlp)* 82 | 83 | Where, *W1* and *W2* are learnable parameters. 84 | Next, a bi-directional attention is used to compute the 85 | interacted representation *^Hlq* 86 | and *^Hlp*. 87 | 88 | *^Hlq = Hlp × softmax(ST)* 89 | 90 | *^Hlp = Hlq × softmax(S)* 91 | 92 | where *softmax(·)* is column-wise normalized function. We use the same attention layer to model the interactions 93 | for all the three levels, and get the final fused representation 94 | *^Hlq, ^Hhq, ^Hfq* for the question and passage respectively 95 | 96 | #### 3) Final Fusion 97 | 98 | We concatenate all the history information: we first concatenate the 99 | encoded representation *H* and the representation after attention *^H*. We pass the concatenated representation H through 100 | a BiLSTM to get HA. 101 | 102 | *HA = BiLSTM[Hl; Hh; Hf; ^Hl; ^Hh; ^Hf]* 103 | 104 | where the representation *HA* is a fusion of information from 105 | different levels. Then we concatenate the original embedded representation 106 | *V* and *HA* for better representation of the fused information 107 | of passage, universal node, and question. 108 | 109 | *A = [V;HA]* 110 | 111 | Finally, we use a self-attention layer to get the attention 112 | information within the fused information. The self-attention 113 | layer is constructed the same way as: 114 | 115 | *^A = A × softmax(ATA)* 116 | 117 | where *^A* is the representation after self-attention of the fused 118 | information *A*. Next we concatenated representation *HA* 119 | and *^A* and pass them through another BiLSTM layer: 120 | 121 | *O = BiLSTM[HA; ^A]* 122 | 123 | Now *O* is the final fused representation of all the information. 124 | At this point, we divide *O* into two parts: *OP* , *OQ*, 125 | representing the fused information of the question and passage 126 | respectively. 127 | 128 | *OP = [o1, o2, · · · , om]* 129 | 130 | *OQ = [om+1, om+2, · · · , om+n+1]* 131 | 132 | Note for the final representation, we attach the universal 133 | node only in the passage representation *OP* . This is because 134 | we need the universal node as a focus for the pointer when 135 | the question is unanswerable. 136 | 137 | #### 4) Prediction 138 | 139 | The prediction layer receives fused information of passage 140 | *OP* and question *OQ*, and tackles three prediction tasks: 141 | 1) answer pointer, 142 | 2) no-answer pointer and 143 | 3) answer verifier 144 | 145 | First, we summarize the 146 | question information *OQ* into a fixed-dim representation *cq*. 147 | 148 | 149 | where *Wq* is a learnable weight matrix and *oQi* 150 | represents the ith word in the question representation. Then we feed cq 151 | into the answer pointer to find boundaries of answers , and the classification layer to distinguish 152 | whether the question is answerable. 153 | 154 | ##### i) Answer Pointer 155 | We use two trainable matrices *Ws* and 156 | *We* to estimate the probability of the answer start and end 157 | boundaries of the ith word in the passage, αi and βi. 158 | 159 | *αi ∝ exp(cqWsoPi)* 160 | 161 | *βi ∝ exp(cqWeoPi)* 162 | 163 | Note here when the question is answerable, we do not 164 | consider the universal node in answer boundary detection, 165 | so we have *i > 0*. 166 | 167 | The loss function for the answerable question pairs is: 168 | 169 | *LA = −(log αa + log βb)* 170 | 171 | 172 | where *a* and *b* are the ground-truth of the start and end 173 | boundary of the answer 174 | 175 | ##### ii) No-Answer Pointer 176 | We use the same pointer for questions that are not answerable 177 | 178 | *LNA = −(log α0 + log β0) − (log α\`a\* + log β\`b\*)* 179 | 180 | 181 | Here *α0* and *β0* correspond to the position of the universal node, 182 | which is at the front of the passage representation *Op*. For 183 | this scenario, the loss is calculated for the universal node. 184 | 185 | Additionally, since there exits a plausible answer for each 186 | unanswerable question in SQuAD 2.0, we introduce an auxiliary 187 | plausible answer pointer to predict the boundaries of 188 | the plausible answer. where *α\`* and *β\`* 189 | are the output of the plausible answer pointer; *a* 190 | and *b* are the start and end boundary of the unanswerable answer. 191 | 192 | ##### iii) Answer Verifier 193 | Answer verifier applies a weighted summary layer to 194 | summarize the passage information into a fixed-dim representation *cq* 195 | And we use the weight matrix obtained from the answer 196 | pointer to get two representations of the passage. 197 | 198 | *F = [cq; om+1; cs; ce]* 199 | 200 | This fixed *F* includes the representation *cq* representing 201 | the question information, and *cs* and *ce* representing the 202 | passage information. Since these representations are highly 203 | summarized specially for classification, we believe that this 204 | passage-question pair contains information to distinguish 205 | whether this question is answerable. 206 | 207 | Finally, we pass this fixed vector *F* through a linear layer 208 | to obtain the prediction whether the question is answerable. 209 | 210 | *pc = σ(WTf F)* 211 | 212 | where *σ* is a sigmoid function, *Wf* is a learnable weight matrix. 213 | Here we use the cross-entropy loss in training. 214 | 215 | *LAV = − (δ · log pc + (1 − δ) · (log (1 − pc)))* 216 | 217 | where *δ ∈ {0, 1}* indicates whether the question has an answer 218 | in the passage. 219 | 220 | 221 | #### Training 222 | We jointly train the three tasks by combining the three loss 223 | functions. The final loss function is: 224 | 225 | *L = δLA + (1 − δ)LNA + LAV* 226 | 227 | where *δ ∈ {0, 1}* indicates whether the question has an answer 228 | in the passage, *LA, LNA and LAV* are the three loss 229 | functions of the answer pointer, no-answer pointer, and answer 230 | verifier. 231 | 232 | Refering: 233 | * [Attention and Memory in Deep Learning and NLP 234 | ](http://www.wildml.com/2016/01/attention-and-memory-in-deep-learning-and-nlp/) 235 | * Glove Vectors 236 | * Elmo 237 | * Loss function 238 | * BiLSTM 239 | * Softmax 240 | * Affine matrix -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 9 | 10 | ### Types of change 11 | 13 | 14 | ## Checklist 15 | 17 | 18 | - [ ] I ran the tests, and all new and existing tests passed. 19 | - [ ] My changes don't require a change to the documentation, or if they do, I've added all required information. 20 | - [ ] My changes requires the reindexing of the current indexes. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ADAM -- Question Answering System 2 | 3 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 4 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/2e669faacb12496f9d4e97f3a0cfc361)](https://www.codacy.com/app/5hirish/adam_qas?utm_source=github.com&utm_medium=referral&utm_content=5hirish/adam_qas&utm_campaign=badger) 5 | [![Codecov](https://codecov.io/gh/5hirish/adam_qas/branch/master/graph/badge.svg)](https://codecov.io/gh/5hirish/adam_qas) 6 | [![Build Status](https://travis-ci.org/5hirish/adam_qas.svg?branch=master)](https://travis-ci.org/5hirish/adam_qas) 7 | [![Gitter](https://badges.gitter.im/alleviatenlp/adam_qas.svg)](https://gitter.im/alleviatenlp/adam_qas?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 8 | [![Twitter](https://img.shields.io/twitter/follow/openebs.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=5hirish) 9 | 10 | A question answering system that extracts answers from Wikipedia to questions posed in natural language. 11 | Inspired by *IBM Watson* and *START*. 12 | We are currently focused on improving the accuracy of the extracted answers. 13 | Follow the creator's blog at [shirishkadam.com](https://www.shirishkadam.com/) for updates on progress. 14 | 15 | ## Getting Started 16 | 17 | Elasticsearch is being used to store and index the scrapped and parsed texts from Wikipedia. 18 | `Elasticsearch 7.X` installation guide can be found at [Elasticsearch Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html). 19 | You might have to start the elasticsearch search service. 20 | 21 | ```bash 22 | $ git clone https://github.com/5hirish/adam_qas.git 23 | $ cd adam_qas 24 | $ pip install -r requirements.txt 25 | $ python -m qas.adam -vv "When was linux kernel version 4.0 released ?" 26 | ``` 27 | 28 | _Note:_ The above installation downloads the best-matching default english language model for spaCy. But to improve the model's accuracy you can install other models too. Read more at [spaCy docs](https://spacy.io/usage/models). 29 | 30 | ```bash 31 | $ python -m spacy download en_core_web_md 32 | ``` 33 | 34 | ## Running with Docker 35 | 36 | ```bash 37 | $ git clone https://github.com/5hirish/adam_qas.git 38 | $ cd adam_qas 39 | $ docker-compose up 40 | ``` 41 | 42 | Now both conntainers are up and running. 43 | Next step is to enter in the python container and run Adam: 44 | 45 | ```bash 46 | $ docker exec -it $(docker ps -a -q --filter ancestor=adam_qas_adam) bash 47 | $ python -m qas.adam -vv "When was linux kernel version 4.0 released ?" 48 | ``` 49 | 50 | 51 | ## References 52 | 53 | Find more in depth documentation about the system with its research paper and system architecture [here](docs/ARCHI.md) 54 | 55 | ## Requirements 56 | 57 | * [Python 3.X](https://docs.python.org/3/) 58 | * [Elasticsearch 7.X](https://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html) 59 | 60 | Python Package dependencies listed in [requirements.txt](requirements.txt) 61 | Upgrading Elasticsearch 6.X: 62 | - Rolling Update 6.2 to 6.8 > [ref](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/rolling-upgrades.html) 63 | - Rolling Update 6.8 to 7.1 > [ref](https://www.elastic.co/guide/en/elasticsearch/reference/current/rolling-upgrades.html) 64 | ### Features 65 | 66 | * Extract information from Wikipedia 67 | * Classify questions with regular expression (default) 68 | * Classify questions with a SVM (optional) 69 | * Vector space model used for answer extraction 70 | * Rank candidate answers 71 | * Merge top 5 answers into one response 72 | 73 | #### Current Project State ? 74 | [GitHub Issue #36: Invalid Answers](https://github.com/5hirish/adam_qas/issues/36) 75 | 76 | ### TODO 77 | 78 | - [x] Replace Wikipedia APIs with custom scraper 79 | - [x] Storing extracted data in database (elasticsearch) 80 | - [x] SQLite test input data storage 81 | - [ ] Anaphora resolution in both questions and answers 82 | - [ ] Machine learning query constructor rather than rule-based 83 | - [ ] Improve vector space language model for answer extraction 84 | 85 | ### Contributions 86 | Please see our [contributing documentation](docs/CONTRIBUTING.md) for some tips on getting started. 87 | 88 | ### Maintainers 89 | * [@5hirish](https://github.com/5hirish) - Shirish Kadam 90 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | elasticsearch: 5 | image: docker.elastic.co/elasticsearch/elasticsearch:7.1.1 6 | #container_name: es01 7 | environment: 8 | - node.name=es01 9 | - cluster.initial_master_nodes=es01 10 | - cluster.name=docker-cluster 11 | - bootstrap.memory_lock=true 12 | - "ES_JAVA_OPTS=-Xms512m -Xmx512m" 13 | ulimits: 14 | memlock: 15 | soft: -1 16 | hard: -1 17 | ports: 18 | - "9200:9200" 19 | adam: 20 | build: . 21 | depends_on: 22 | - "elasticsearch" 23 | entrypoint: 24 | - bash 25 | tty: true -------------------------------------------------------------------------------- /docs/ARCHI.md: -------------------------------------------------------------------------------- 1 | 2 | ## Research Paper: 3 | ["A Cognitive approach in Question Answering System" - Shirish Kadam, Amit Gunjal, (2017)](adam_qa_research_paper.pdf) 4 | 5 | ## System Architecture : 6 | ![alt text](adam_arch.png "ADAM Architecture") 7 | > (c) 2016-17, Shirish Kadam; 8 | > (c) 2016-17, Amit Gunjal 9 | 10 | ## Work FLow 11 | ![alt text](adam_qa_pipeline.png "ADAM Architecture") 12 | > (c) 2016-17, Shirish Kadam; 13 | > (c) 2016-17, Amit Gunjal -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTING 2 | 3 | Adam QAS is a community-maintained project and we happily accept contributions. 4 | 5 | If you wish to add a new feature or fix a bug: 6 | 7 | 1. Check for [open issues](https://github.com/5hirish/adam_qas/issues) or open a fresh issue to start a discussion around a feature idea or a bug. 8 | 2. Fork the [Adam QAS](https://github.com/5hirish/adam_qas) repository on Github to start making your changes. 9 | 3. Write a test which shows that the bug was fixed or that the feature works as expected. 10 | 4. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to [AUTHORS.rst](/AUTHORS.rst). 11 | 12 | ```bash 13 | $ git checkout dev -b feature/my-new-feature 14 | $ git pull origin master 15 | ``` 16 | _Note:_ Follow [PEP8](http://docs.python-guide.org/en/latest/writing/style/) codding style. 17 | 18 | ## Running the tests 19 | 20 | We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. Our Makefile handles much of this for you as long as you’re running it inside of a virtualenv: 21 | ```bash 22 | $ pytest tests 23 | ``` 24 | Our test suite runs continuously on Travis CI with every pull request to `master`. 25 | 26 | ## HELP REQUIRED 27 | 28 | To find where you can help, search for the following tags: 29 | * `#TODO:` The tasks which are pending or yet not taken up 30 | * `#FIXME:` The tasks which require some attending to do 31 | * `#HELP:` The tasks which are require some help 32 | 33 | You can also help in making the Wikipedia parser more robust by adding more XPath filters that remove irrelevant information or extract and format relevant information. 34 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $?), 1) 12 | $(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/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/qas.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/qas.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $HOME/.local/share/devhelp/qas" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $HOME/.local/share/devhelp/qas" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/_static/.gitignore: -------------------------------------------------------------------------------- 1 | # Empty directory 2 | -------------------------------------------------------------------------------- /docs/adam_arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/docs/adam_arch.png -------------------------------------------------------------------------------- /docs/adam_qa_pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/docs/adam_qa_pipeline.png -------------------------------------------------------------------------------- /docs/adam_qa_research_paper.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/docs/adam_qa_research_paper.pdf -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. _authors: 2 | .. include:: ../AUTHORS.rst 3 | -------------------------------------------------------------------------------- /docs/changes.rst: -------------------------------------------------------------------------------- 1 | .. _changes: 2 | .. include:: ../CHANGES.rst 3 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is execfile()d with the current directory set to its containing dir. 4 | # 5 | # Note that not all possible configuration values are present in this 6 | # autogenerated file. 7 | # 8 | # All configuration values have a default; values that are commented out 9 | # serve to show the default. 10 | 11 | import sys 12 | 13 | # If extensions (or modules to document with autodoc) are in another directory, 14 | # add these directories to sys.path here. If the directory is relative to the 15 | # documentation root, use os.path.abspath to make it absolute, like shown here. 16 | # sys.path.insert(0, os.path.abspath('.')) 17 | 18 | # -- Hack for ReadTheDocs ------------------------------------------------------ 19 | # This hack is necessary since RTD does not issue `sphinx-apidoc` before running 20 | # `sphinx-build -b html . _build/html`. See Issue: 21 | # https://github.com/rtfd/readthedocs.org/issues/1139 22 | # DON'T FORGET: Check the box "Install your project inside a virtualenv using 23 | # setup.py install" in the RTD Advanced Settings. 24 | import os 25 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 26 | if on_rtd: 27 | import inspect 28 | from sphinx import apidoc 29 | 30 | __location__ = os.path.join(os.getcwd(), os.path.dirname( 31 | inspect.getfile(inspect.currentframe()))) 32 | 33 | output_dir = os.path.join(__location__, "../docs/api") 34 | module_dir = os.path.join(__location__, "../qas") 35 | cmd_line_template = "sphinx-apidoc -f -o {outputdir} {moduledir}" 36 | cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir) 37 | apidoc.main(cmd_line.split(" ")) 38 | 39 | # -- General configuration ----------------------------------------------------- 40 | 41 | # If your documentation needs a minimal Sphinx version, state it here. 42 | # needs_sphinx = '1.0' 43 | 44 | # Add any Sphinx extension module names here, as strings. They can be extensions 45 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 46 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 47 | 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', 'sphinx.ext.coverage', 48 | 'sphinx.ext.doctest', 'sphinx.ext.ifconfig', 'sphinx.ext.mathjax', 49 | 'sphinx.ext.napoleon'] 50 | 51 | # Add any paths that contain templates here, relative to this directory. 52 | templates_path = ['_templates'] 53 | 54 | # The suffix of source filenames. 55 | source_suffix = '.rst' 56 | 57 | # The encoding of source files. 58 | # source_encoding = 'utf-8-sig' 59 | 60 | # The master toctree document. 61 | master_doc = 'index' 62 | 63 | # General information about the project. 64 | project = u'Adam - Question Answering System' 65 | copyright = u'2017, Shirish Kadam' 66 | 67 | # The version info for the project you're documenting, acts as replacement for 68 | # |version| and |release|, also used in various other places throughout the 69 | # built documents. 70 | # 71 | # The short X.Y version. 72 | version = '' # Is set by calling `setup.py docs` 73 | # The full version, including alpha/beta/rc tags. 74 | release = '' # Is set by calling `setup.py docs` 75 | 76 | # The language for content autogenerated by Sphinx. Refer to documentation 77 | # for a list of supported languages. 78 | # language = None 79 | 80 | # There are two options for replacing |today|: either, you set today to some 81 | # non-false value, then it is used: 82 | # today = '' 83 | # Else, today_fmt is used as the format for a strftime call. 84 | # today_fmt = '%B %d, %Y' 85 | 86 | # List of patterns, relative to source directory, that match files and 87 | # directories to ignore when looking for source files. 88 | exclude_patterns = ['_build'] 89 | 90 | # The reST default role (used for this markup: `text`) to use for all documents. 91 | # default_role = None 92 | 93 | # If true, '()' will be appended to :func: etc. cross-reference text. 94 | # add_function_parentheses = True 95 | 96 | # If true, the current module name will be prepended to all description 97 | # unit titles (such as .. function::). 98 | # add_module_names = True 99 | 100 | # If true, sectionauthor and moduleauthor directives will be shown in the 101 | # output. They are ignored by default. 102 | # show_authors = False 103 | 104 | # The name of the Pygments (syntax highlighting) style to use. 105 | pygments_style = 'sphinx' 106 | 107 | # A list of ignored prefixes for module index sorting. 108 | # modindex_common_prefix = [] 109 | 110 | # If true, keep warnings as "system message" paragraphs in the built documents. 111 | # keep_warnings = False 112 | 113 | 114 | # -- Options for HTML output --------------------------------------------------- 115 | 116 | # The theme to use for HTML and HTML Help pages. See the documentation for 117 | # a list of builtin themes. 118 | html_theme = 'alabaster' 119 | 120 | # Theme options are theme-specific and customize the look and feel of a theme 121 | # further. For a list of options available for each theme, see the 122 | # documentation. 123 | # html_theme_options = {} 124 | 125 | # Add any paths that contain custom themes here, relative to this directory. 126 | # html_theme_path = [] 127 | 128 | # The name for this set of Sphinx documents. If None, it defaults to 129 | # " v documentation". 130 | try: 131 | from qas import __version__ as version 132 | except ImportError: 133 | pass 134 | else: 135 | release = version 136 | 137 | # A shorter title for the navigation bar. Default is the same as html_title. 138 | # html_short_title = None 139 | 140 | # The name of an image file (relative to this directory) to place at the top 141 | # of the sidebar. 142 | # html_logo = "" 143 | 144 | # The name of an image file (within the static path) to use as favicon of the 145 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 146 | # pixels large. 147 | # html_favicon = None 148 | 149 | # Add any paths that contain custom static files (such as style sheets) here, 150 | # relative to this directory. They are copied after the builtin static files, 151 | # so a file named "default.css" will overwrite the builtin "default.css". 152 | html_static_path = ['_static'] 153 | 154 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 155 | # using the given strftime format. 156 | # html_last_updated_fmt = '%b %d, %Y' 157 | 158 | # If true, SmartyPants will be used to convert quotes and dashes to 159 | # typographically correct entities. 160 | # html_use_smartypants = True 161 | 162 | # Custom sidebar templates, maps document names to template names. 163 | # html_sidebars = {} 164 | 165 | # Additional templates that should be rendered to pages, maps page names to 166 | # template names. 167 | # html_additional_pages = {} 168 | 169 | # If false, no module index is generated. 170 | # html_domain_indices = True 171 | 172 | # If false, no index is generated. 173 | # html_use_index = True 174 | 175 | # If true, the index is split into individual pages for each letter. 176 | # html_split_index = False 177 | 178 | # If true, links to the reST sources are added to the pages. 179 | # html_show_sourcelink = True 180 | 181 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 182 | # html_show_sphinx = True 183 | 184 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 185 | # html_show_copyright = True 186 | 187 | # If true, an OpenSearch description file will be output, and all pages will 188 | # contain a tag referring to it. The value of this option must be the 189 | # base URL from which the finished HTML is served. 190 | # html_use_opensearch = '' 191 | 192 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 193 | # html_file_suffix = None 194 | 195 | # Output file base name for HTML help builder. 196 | htmlhelp_basename = 'qas-doc' 197 | 198 | 199 | # -- Options for LaTeX output -------------------------------------------------- 200 | 201 | latex_elements = { 202 | # The paper size ('letterpaper' or 'a4paper'). 203 | # 'papersize': 'letterpaper', 204 | 205 | # The font size ('10pt', '11pt' or '12pt'). 206 | # 'pointsize': '10pt', 207 | 208 | # Additional stuff for the LaTeX preamble. 209 | # 'preamble': '', 210 | } 211 | 212 | # Grouping the document tree into LaTeX files. List of tuples 213 | # (source start file, target name, title, author, documentclass [howto/manual]). 214 | latex_documents = [ 215 | ('index', 'user_guide.tex', u'qas Documentation', 216 | u'Shirish Kadam', 'manual'), 217 | ] 218 | 219 | # The name of an image file (relative to this directory) to place at the top of 220 | # the title page. 221 | # latex_logo = "" 222 | 223 | # For "manual" documents, if this is true, then toplevel headings are parts, 224 | # not chapters. 225 | # latex_use_parts = False 226 | 227 | # If true, show page references after internal links. 228 | # latex_show_pagerefs = False 229 | 230 | # If true, show URL addresses after external links. 231 | # latex_show_urls = False 232 | 233 | # Documents to append as an appendix to all manuals. 234 | # latex_appendices = [] 235 | 236 | # If false, no module index is generated. 237 | # latex_domain_indices = True 238 | 239 | # -- External mapping ------------------------------------------------------------ 240 | python_version = '.'.join(map(str, sys.version_info[0:2])) 241 | intersphinx_mapping = { 242 | 'sphinx': ('http://sphinx.pocoo.org', None), 243 | 'python': ('http://docs.python.org/' + python_version, None), 244 | 'matplotlib': ('http://matplotlib.sourceforge.net', None), 245 | 'numpy': ('http://docs.scipy.org/doc/numpy', None), 246 | 'sklearn': ('http://scikit-learn.org/stable', None), 247 | 'pandas': ('http://pandas.pydata.org/pandas-docs/stable', None), 248 | 'scipy': ('http://docs.scipy.org/doc/scipy/reference/', None), 249 | } 250 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | === 2 | qas 3 | === 4 | 5 | This is the documentation of **qas**. 6 | 7 | .. note:: 8 | 9 | This is the main page of your project's `Sphinx `_ 10 | documentation. It is formatted in `reStructuredText 11 | `__. Add additional pages by creating 12 | rst-files in ``docs`` and adding them to the `toctree 13 | `_ below. Use then 14 | `references `__ in order to link 15 | them from this page, e.g. :ref:`authors ` and :ref:`changes`. 16 | 17 | It is also possible to refer to the documentation of other Python packages 18 | with the `Python domain syntax 19 | `__. By default you 20 | can reference the documentation of `Sphinx `__, 21 | `Python `__, `NumPy 22 | `__, `SciPy 23 | `__, `matplotlib 24 | `__, `Pandas 25 | `__, `Scikit-Learn 26 | `__. You can add more by 27 | extending the ``intersphinx_mapping`` in your Sphinx's ``conf.py``. 28 | 29 | The pretty useful extension `autodoc 30 | `__ is activated by 31 | default and lets you include documentation from docstrings. Docstrings can 32 | be written in `Google 33 | `__ 34 | (recommended!), `NumPy 35 | `__ 36 | and `classical 37 | `__ 38 | style. 39 | 40 | 41 | Contents 42 | ======== 43 | 44 | .. toctree:: 45 | :maxdepth: 2 46 | 47 | License 48 | Authors 49 | Changelog 50 | Module Reference 51 | 52 | 53 | Indices and tables 54 | ================== 55 | 56 | * :ref:`genindex` 57 | * :ref:`modindex` 58 | * :ref:`search` 59 | -------------------------------------------------------------------------------- /docs/license.rst: -------------------------------------------------------------------------------- 1 | .. _license: 2 | 3 | ======= 4 | License 5 | ======= 6 | 7 | .. literalinclude:: ../LICENSE.txt 8 | -------------------------------------------------------------------------------- /docs/resources.rst: -------------------------------------------------------------------------------- 1 | https://github.com/dapurv5/awesome-question-answering 2 | 3 | Datasets: 4 | 5 | https://research.fb.com/downloads/babi/ : The SimpleQuestions dataset 6 | 7 | https://nlp.stanford.edu/software/sempre/ : SEMPRE: Semantic Parsing with Execution 8 | 9 | https://rajpurkar.github.io/SQuAD-explorer/ : The Stanford Question Answering Dataset 10 | 11 | https://github.com/shuzi/insuranceQA : A question answering corpus in insurance domain -------------------------------------------------------------------------------- /qas/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import pkg_resources 3 | 4 | try: 5 | __version__ = pkg_resources.get_distribution(__name__).version 6 | except: 7 | __version__ = '0.1' 8 | -------------------------------------------------------------------------------- /qas/about.py: -------------------------------------------------------------------------------- 1 | 2 | __title__ = 'qas' 3 | __version__ = '0.1' 4 | __summary__ = 'A Question Answering System' 5 | __uri__ = 'https://shirishkadam.com' 6 | __author__ = 'Shirish Kadam' 7 | __email__ = 'shirishkadam35@gmail.com' 8 | __license__ = 'GPLv3' 9 | __release__ = False 10 | -------------------------------------------------------------------------------- /qas/adam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import argparse 5 | import logging 6 | import sys 7 | 8 | import spacy 9 | 10 | from qas import __version__ 11 | from qas.candidate_ans import get_candidate_answers 12 | from qas.classifier.question_classifier import classify_question 13 | from qas.constants import EN_MODEL_MD, EN_MODEL_DEFAULT, EN_MODEL_SM 14 | from qas.doc_search_rank import search_rank 15 | from qas.feature_extractor import extract_features 16 | from qas.query_const import construct_query 17 | from qas.wiki.wiki_search import search_wikipedia 18 | 19 | __author__ = "Shirish Kadam" 20 | __copyright__ = "Copyright (C) 2017 Shirish Kadam" 21 | __license__ = "GNU General Public License v3 (GPLv3)" 22 | 23 | _logger = logging.getLogger(__name__) 24 | 25 | 26 | def get_default_model(model_name): 27 | err_msg = "Language model {0} not found. Please, refer https://spacy.io/usage/models" 28 | nlp = None 29 | if model_name is not None: 30 | try: 31 | nlp = spacy.load(model_name) 32 | except (ImportError, OSError): 33 | print(err_msg.format(model_name)) 34 | print('Using default language model') 35 | nlp = get_default_model(EN_MODEL_SM) 36 | return nlp 37 | 38 | 39 | def get_nlp(language, lite, lang_model=""): 40 | err_msg = "Language model {0} not found. Please, refer https://spacy.io/usage/models" 41 | nlp = None 42 | 43 | if not lang_model == "" and not lang_model == "en": 44 | 45 | try: 46 | nlp = spacy.load(lang_model) 47 | except ImportError: 48 | print(err_msg.format(lang_model)) 49 | raise 50 | 51 | elif language == 'en': 52 | 53 | if lite: 54 | nlp = spacy.load(EN_MODEL_DEFAULT) 55 | else: 56 | 57 | try: 58 | nlp = spacy.load(EN_MODEL_MD) 59 | except (ImportError, OSError): 60 | print(err_msg.format(EN_MODEL_MD)) 61 | print('Using default language model') 62 | nlp = get_default_model(EN_MODEL_DEFAULT) 63 | 64 | elif not language == 'en': 65 | print('Currently only English language is supported. ' 66 | 'Please contribute to https://github.com/5hirish/adam_qas to add your language.') 67 | sys.exit(0) 68 | 69 | return nlp 70 | 71 | 72 | class QasInit: 73 | 74 | nlp = None 75 | language = "en" 76 | lang_model = None 77 | search_depth = 3 78 | lite = False 79 | 80 | question_doc = None 81 | 82 | question_class = "" 83 | question_keywords = None 84 | query = None 85 | 86 | candidate_answers = None 87 | 88 | def __init__(self, language, search_depth, lite, lang_model=""): 89 | self.language = language 90 | self.search_depth = search_depth 91 | self.lite = lite 92 | self.lang_model = lang_model 93 | self.nlp = get_nlp(self.language, self.lite, self.lang_model) 94 | 95 | def get_question_doc(self, question): 96 | 97 | self.question_doc = self.nlp(u'' + question) 98 | 99 | return self.question_doc 100 | 101 | def process_question(self): 102 | 103 | self.question_class = classify_question(self.question_doc) 104 | _logger.info("Question Class: {}".format(self.question_class)) 105 | 106 | self.question_keywords = extract_features(self.question_class, self.question_doc) 107 | _logger.info("Question Features: {}".format(self.question_keywords)) 108 | 109 | self.query = construct_query(self.question_keywords, self.question_doc) 110 | _logger.info("Query: {}".format(self.query)) 111 | 112 | def process_answer(self): 113 | 114 | _logger.info("Retrieving {} Wikipedia pages...".format(self.search_depth)) 115 | search_wikipedia(self.question_keywords, self.search_depth) 116 | 117 | # Anaphora Resolution 118 | wiki_pages = search_rank(self.query) 119 | _logger.info("Pages retrieved: {}".format(len(wiki_pages))) 120 | 121 | self.candidate_answers, keywords = get_candidate_answers(self.query, wiki_pages, self.nlp) 122 | _logger.info("Candidate answers ({}):\n{}".format(len(self.candidate_answers), '\n'.join(self.candidate_answers))) 123 | 124 | return " ".join(self.candidate_answers) 125 | 126 | 127 | def parse_args(args): 128 | 129 | parser = argparse.ArgumentParser( 130 | description="Adam a question answering system") 131 | 132 | parser.add_argument( 133 | '--version', 134 | action='version', 135 | help="show version", 136 | version='qas {ver}'.format(ver=__version__)) 137 | 138 | parser.add_argument( 139 | dest="question", 140 | help="Question for the Know It All Adam to answer", 141 | type=str, 142 | default='', 143 | metavar='"QUESTION"') 144 | 145 | parser.add_argument( 146 | '-l', 147 | '--lang', 148 | dest="language", 149 | help="set language according to ISO codes", 150 | default='en', 151 | type=str, 152 | metavar="XX" 153 | ) 154 | 155 | parser.add_argument( 156 | '-n', 157 | dest="search_limit", 158 | help="set limit for pages fetched from Wikipedia. Default is 3 and max is 10", 159 | default=3, 160 | type=int, 161 | metavar="Y" 162 | ) 163 | 164 | parser.add_argument( 165 | '--lite', 166 | action='store_const', 167 | dest="lite", 168 | default=False, 169 | const=True, 170 | help="set qas to use lighter version of language model" 171 | ) 172 | 173 | parser.add_argument( 174 | '--model', 175 | dest="lang_model", 176 | default="en", 177 | type=str, 178 | help="set spaCy language model", 179 | metavar="XXX_XX" 180 | ) 181 | 182 | parser.add_argument( 183 | '-v', 184 | '--verbose', 185 | dest="loglevel", 186 | help="set loglevel to INFO", 187 | action='store_const', 188 | const=logging.INFO) 189 | 190 | parser.add_argument( 191 | '-vv', 192 | '--very-verbose', 193 | dest="loglevel", 194 | help="set loglevel to DEBUG", 195 | action='store_const', 196 | const=logging.DEBUG) 197 | 198 | # parser.print_help() 199 | 200 | return parser.parse_args(args) 201 | 202 | 203 | def setup_logging(loglevel): 204 | 205 | logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" 206 | logging.basicConfig(level=loglevel, stream=sys.stdout, 207 | format=logformat, datefmt="%Y-%m-%d %H:%M:%S") 208 | 209 | logging.getLogger('urllib3').setLevel(logging.CRITICAL) 210 | logging.getLogger('elasticsearch').setLevel(logging.CRITICAL) 211 | logging.getLogger('gensim').setLevel(logging.CRITICAL) 212 | 213 | 214 | def main(args): 215 | 216 | args = parse_args(args) 217 | setup_logging(args.loglevel) 218 | _logger.debug("Thinking...") 219 | if args.question is None: 220 | args.question = input("Ask your question:>") 221 | 222 | print("I think what you want to know is: {}".format(args.question)) 223 | 224 | # print(args) 225 | 226 | qas = QasInit(language=args.language, search_depth=args.search_limit, lite=args.lite, lang_model=args.lang_model) 227 | qas.get_question_doc(args.question) 228 | qas.process_question() 229 | answer = qas.process_answer() 230 | # 231 | print("\n\n** Your answer:\n {}".format(answer)) 232 | 233 | 234 | def run(): 235 | 236 | main(sys.argv[1:]) 237 | 238 | 239 | if __name__ == "__main__": 240 | run() 241 | -------------------------------------------------------------------------------- /qas/anaphora_res.py: -------------------------------------------------------------------------------- 1 | from pprint import pprint 2 | 3 | import requests 4 | 5 | 6 | def get_named_entities(en_doc): 7 | prop_noun_entities = {} 8 | prop_noun_entities_pos = {} 9 | payload = {} 10 | i = 0 11 | for ent in en_doc.ents: 12 | prop_noun_entities_pos[ent.text] = ent.start 13 | if i < 10: 14 | payload["name["+str(i)+"]"] = ent.text 15 | print(ent.label_, ent.text) 16 | if i == 9: 17 | prop_noun_entities = get_gender(payload, prop_noun_entities) 18 | i = 0 19 | i += 1 20 | pprint(payload) 21 | if i < 10: 22 | prop_noun_entities = get_gender(payload, prop_noun_entities) 23 | return prop_noun_entities, prop_noun_entities_pos 24 | 25 | 26 | def get_noun_chunks(en_doc, prop_noun_entities): 27 | payload = {} 28 | i = 0 29 | for noun in en_doc.noun_chunks: 30 | if i < 10: 31 | payload["name[" + str(i) + "]"] = noun.text 32 | print(noun.label_, noun.text) 33 | if i == 9: 34 | prop_noun_entities = get_gender(payload, prop_noun_entities) 35 | i = 0 36 | i += 1 37 | pprint(payload) 38 | if i < 10: 39 | prop_noun_entities = get_gender(payload, prop_noun_entities) 40 | return prop_noun_entities 41 | 42 | 43 | def get_gender(payload, prop_noun_entities): 44 | gender_req = requests.get("https://api.genderize.io/", params=payload) 45 | json_gen = gender_req.json() 46 | 47 | for ji in json_gen: 48 | prop_noun_entities[json_gen[ji]['name']] = json_gen[ji]['gender'] 49 | 50 | return prop_noun_entities 51 | 52 | 53 | def map_entity_pronoun(prop_noun_entities, entity, anaphora_mappings): 54 | pronouns = ["i", "you", "he", "she", "it", "we", "they", "me", "him", "her", "us", "them"] 55 | 56 | first_person_pron = ["i", "me", "my", "mine"] 57 | second_person_pron = ["you", "your"] 58 | third_person_pron = [["he", "him", "his"], ["she", "her", "hers"], ["it"]] # M - F - N 59 | 60 | first_person_plu_pron = ["we", "us", "our", "ours"] 61 | second_person_plu_pron = ["you", "yours"] 62 | third_person_plu_pron = ["they", "them", "their", "theirs"] 63 | 64 | gender = prop_noun_entities[entity] 65 | 66 | if gender == 'male': 67 | anaphora_mappings[entity] = first_person_pron + second_person_pron + third_person_pron[0] 68 | elif gender == 'female': 69 | anaphora_mappings[entity] = first_person_pron + second_person_pron + third_person_pron[1] 70 | else: 71 | anaphora_mappings[entity] = third_person_pron[2] 72 | return anaphora_mappings 73 | 74 | 75 | def propogate_anaphora(en_doc, anaphora_mappings, prop_noun_entities_pos): 76 | first_person_pron = ["i", "me", "my", "mine"] 77 | 78 | anaphora_pronouns = list(anaphora_mappings.values()) 79 | anaphora_pnouns = list(anaphora_mappings.keys()) 80 | doc_list = [str(tok) for tok in en_doc] 81 | 82 | for sent in en_doc.sents: 83 | prev_noun = "" 84 | for token in sent: 85 | print(token.text) 86 | if token.tag_ == "NNP" or token.tag_ == "NNPS": 87 | prev_noun = token.text 88 | if token.tag_ == "PRP" or token.tag_ == "PRP$": 89 | for pos in anaphora_pronouns: 90 | if str(token.text).lower() in anaphora_pronouns[pos]: 91 | resolve_noun = anaphora_pnouns[pos] 92 | print(resolve_noun, prev_noun, token.text) 93 | res_pos = prop_noun_entities_pos[resolve_noun] 94 | if res_pos < token.i and str(token.text).lower in first_person_pron: 95 | doc_list[token.i] = prev_noun 96 | break 97 | elif res_pos < token.i and resolve_noun != prev_noun: 98 | doc_list[token.i] = resolve_noun 99 | prev_noun = resolve_noun 100 | break 101 | 102 | return doc_list 103 | 104 | 105 | sentence = "Louie is a quite fellow." \ 106 | " But that doesn't mean he will endure anything." \ 107 | " Samantha loves this about him." \ 108 | " Why wouldn't she?" \ 109 | " Her whole childhood was under his shadow." \ 110 | " John admired him, but he didn't know him, like she knew him." \ 111 | " Louie used to say 'I know life'." \ 112 | " He did." 113 | 114 | 115 | 116 | """en_nlp = spacy.load('en_core_web_md') 117 | # sentence = sentence.lower() 118 | print(sentence) 119 | en_doc = en_nlp(u'' + sentence) 120 | prop_noun = "" 121 | anaphora_mappings = {} 122 | 123 | prop_noun_entities, prop_noun_entities_pos = get_named_entities(en_doc) 124 | # prop_noun_entities = get_noun_chunks(en_doc, prop_noun_entities) 125 | 126 | for entity in prop_noun_entities.keys(): 127 | anaphora_mappings = map_entity_pronoun(prop_noun_entities, entity, anaphora_mappings) 128 | # pprint(prop_noun_entities) 129 | pprint(anaphora_mappings) 130 | 131 | 132 | for sent in en_doc.sents: 133 | for token in sent: 134 | if token.tag_ == "PRP" or token.tag_ == "PRP$": 135 | print(token.text, token.tag_, token.dep_, "---") # PRON / PRP Propagation 136 | 137 | elif token.pos_ == "PROPN": 138 | 139 | if token.tag_ == "NNP": 140 | prop_noun = token.text 141 | payload = {"name[0]": token.text} 142 | prop_noun_entities = get_gender(payload, prop_noun_entities) 143 | prop_noun_entities_pos[token.text] = token.i 144 | prop_noun_gender = prop_noun_entities[token.text] 145 | anaphora_mappings = map_entity_pronoun(prop_noun_entities, prop_noun, anaphora_mappings) 146 | print(token.text, token.tag_, token.dep_, token.ent_type_, prop_noun, prop_noun_gender) # NNP / NNPS 147 | 148 | elif token.tag_ == "NNPS": 149 | print(token.text, token.tag_, token.dep_, token.ent_type_) # NNP / NNPS 150 | else: 151 | print(token.text, token.tag_, token.dep_, token.ent_type_) 152 | 153 | pprint(anaphora_mappings) 154 | 155 | resolved_sent = propogate_anaphora(en_doc, anaphora_mappings, prop_noun_entities_pos) 156 | print(' '.join(resolved_sent))""" 157 | 158 | # John admired Louie, but John didn't know Louie, like Samantha knew Louie -------------------------------------------------------------------------------- /qas/candidate_ans.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from collections import Counter 4 | 5 | import gensim 6 | 7 | from qas.constants import CORPUS_DIR 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | def query2vec(query, dictionary): 13 | 14 | logging.info("Searching: {0}".format(query)) 15 | corpus = dictionary.doc2bow(query) 16 | 17 | return corpus 18 | 19 | 20 | def doc2vec(documents): 21 | with open(os.path.join(CORPUS_DIR, 'stop_words.txt'), 'r', newline='') as stp_fp: 22 | stop_list = (stp_fp.read()).lower().split("\n") 23 | texts = [[word for word in doc.lemma_.split() if word not in stop_list]for doc in documents] 24 | 25 | frequency = Counter() 26 | for sent in texts: 27 | for token in sent: 28 | frequency[token] += 1 29 | 30 | texts = [[token for token in snipp if frequency[token] > 1]for snipp in texts] 31 | 32 | dictionary = gensim.corpora.Dictionary(texts) 33 | corpus = [dictionary.doc2bow(snipp) for snipp in texts] 34 | 35 | return corpus, dictionary 36 | 37 | 38 | def transform_vec(corpus, query_corpus): 39 | lsidf = gensim.models.LsiModel(corpus) 40 | 41 | corpus_lsidf = lsidf[corpus] 42 | query_lsidf = lsidf[query_corpus] 43 | 44 | return corpus_lsidf, query_lsidf 45 | 46 | 47 | def similariy(corpus_lsidf, query_lsidf): 48 | index = gensim.similarities.SparseMatrixSimilarity(corpus_lsidf, num_features=100000) 49 | 50 | simi = index[query_lsidf] 51 | 52 | simi_sorted = sorted(enumerate(simi), key=lambda item: -item[1]) 53 | return simi_sorted 54 | 55 | 56 | def combine(sub_keys, keywords_splits, lb, mb, ub): 57 | whitespace = ' ' 58 | while mb != ub: 59 | keywords_splits.append(whitespace.join(sub_keys[lb: mb])) 60 | keywords_splits.append(whitespace.join(sub_keys[mb: ub])) 61 | mb += 1 62 | del sub_keys[0] 63 | if len(sub_keys) > 2: 64 | combine(sub_keys, keywords_splits, 0, 1, len(sub_keys)) 65 | 66 | 67 | def keywords_splitter(keywords, keywords_splits): 68 | 69 | for key in keywords: 70 | sub_keys = key.split() 71 | 72 | if len(sub_keys) > 2: 73 | combine(sub_keys, keywords_splits, 0, 1, len(sub_keys)) 74 | 75 | 76 | def pre_query(question_query): 77 | 78 | keywords = question_query.get_features() 79 | 80 | keywords = [feat.lower() for feat in keywords] 81 | whitespace = ' ' 82 | keywords_splits = whitespace.join(keywords).split() 83 | 84 | keywords_splitter(keywords, keywords_splits) 85 | keywords_splits = list(set(keywords_splits + keywords)) 86 | 87 | return keywords_splits 88 | 89 | 90 | def get_processed_document(ranked_wiki_docs): 91 | 92 | with open(os.path.join(CORPUS_DIR, 'know_corp.txt'), 'r') as fp: 93 | documents = fp.read().split("\n") 94 | del documents[len(documents) - 1] 95 | 96 | processed_documents = "" 97 | 98 | for rank_tuple in ranked_wiki_docs: 99 | processed_documents += documents[rank_tuple[0]] 100 | 101 | return processed_documents 102 | 103 | 104 | def get_candidate_answers(question_query, ranked_wiki_docs, en_nlp): 105 | 106 | # NOTE: Currently this project doesn't support multiple questions. 107 | keywords_query = pre_query(question_query[0]) 108 | 109 | combined_document = [] 110 | for wiki_doc in ranked_wiki_docs: 111 | combined_document.append(wiki_doc.get_wiki_content()) 112 | 113 | combined_document_str = ' '.join(combined_document) 114 | en_doc = en_nlp(u'' + combined_document_str) 115 | 116 | sentences = list(en_doc.sents) 117 | 118 | corpus, dictionary = doc2vec(sentences) 119 | 120 | query_corpus = query2vec(keywords_query, dictionary) 121 | 122 | corpus_lsidf, query_lsidf = transform_vec(corpus, query_corpus) 123 | 124 | simi_sorted = similariy(corpus_lsidf, query_lsidf) 125 | 126 | if len(simi_sorted) > 5: 127 | simi_sorted = simi_sorted[0:5] 128 | 129 | candidate_ans = [] 130 | for sent in simi_sorted: 131 | sent_id = sent[0] 132 | candidate_ans.append(str(sentences[sent_id])) 133 | 134 | return candidate_ans, keywords_query 135 | 136 | 137 | if __name__ == "__main__": 138 | 139 | import spacy 140 | from qas.constants import EN_MODEL_MD 141 | from qas.model.query_container import QueryContainer 142 | from qas.wiki.wiki_search import search_wikipedia 143 | from qas.doc_search_rank import search_rank 144 | 145 | logging.basicConfig(level=logging.DEBUG) 146 | 147 | lquestion_keywords = ['Albert Einstein', 'birth'] 148 | lquery_raw = list([[['Albert Einstein', 'birth'], [], [], []]]) 149 | lquery = [] 150 | for qr in lquery_raw: 151 | lquery.append(QueryContainer(qr)) 152 | search_wikipedia(lquestion_keywords, 3) 153 | lwiki_pages = search_rank(lquery_raw) 154 | 155 | len_nlp = spacy.load(EN_MODEL_MD) 156 | 157 | candidate_answers, keywords = get_candidate_answers(lquery, lwiki_pages, len_nlp) 158 | print(' '.join(candidate_answers)) -------------------------------------------------------------------------------- /qas/classifier/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/classifier/__init__.py -------------------------------------------------------------------------------- /qas/classifier/question_classifier.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | import pandas 5 | import joblib 6 | 7 | from scipy.sparse import csr_matrix 8 | from sklearn.naive_bayes import GaussianNB 9 | from sklearn.svm import LinearSVC 10 | 11 | from qas.constants import CORPUS_DIR, EN_MODEL_MD 12 | from qas.corpus.data import QUESTION_CLASSIFICATION_TRAINING_DATA, QUESTION_CLASSIFICATION_MODEL 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | def pre_process(dta): 18 | return pandas.get_dummies(dta) 19 | 20 | 21 | def remove_irrelevant_features(df_question): 22 | df_question_class = df_question.pop('Class') 23 | 24 | df_question.pop('Question') 25 | df_question.pop('WH-Bigram') 26 | 27 | return df_question_class 28 | 29 | 30 | def transform_data_matrix(df_question_train, df_question_predict): 31 | 32 | df_question_train_columns = list(df_question_train.columns) 33 | df_question_predict_columns = list(df_question_predict.columns) 34 | 35 | df_question_trans_columns = list(set(df_question_train_columns + df_question_predict_columns)) 36 | 37 | logger.debug("Union Columns: {0}".format(len(df_question_trans_columns))) 38 | 39 | trans_data_train = {} 40 | 41 | for feature in df_question_trans_columns: 42 | if feature not in df_question_train: 43 | trans_data_train[feature] = [0 for i in range(len(df_question_train.index))] 44 | else: 45 | trans_data_train[feature] = list(df_question_train[feature]) 46 | 47 | df_question_train = pandas.DataFrame(trans_data_train) 48 | logger.debug("Training data: {0}".format(df_question_train.shape)) 49 | df_question_train = csr_matrix(df_question_train) 50 | 51 | trans_data_predict = {} 52 | 53 | for feature in trans_data_train: 54 | if feature not in df_question_predict: 55 | trans_data_predict[feature] = 0 56 | else: 57 | trans_data_predict[feature] = list(df_question_predict[feature]) # KeyError 58 | 59 | df_question_predict = pandas.DataFrame(trans_data_predict) 60 | logger.debug("Target data: {0}".format(df_question_predict.shape)) 61 | df_question_predict = csr_matrix(df_question_predict) 62 | 63 | return df_question_train, df_question_predict 64 | 65 | 66 | def naive_bayes_classifier(x_train, y, x_predict): 67 | gnb = GaussianNB() 68 | gnb.fit(x_train, y) 69 | prediction = gnb.predict(x_predict) 70 | return prediction 71 | 72 | 73 | def support_vector_machine(df_question_train, df_question_class, df_question_predict): 74 | lin_clf = LinearSVC() 75 | lin_clf.fit(df_question_train, df_question_class) 76 | prediction = lin_clf.predict(df_question_predict) 77 | return prediction, lin_clf 78 | 79 | 80 | def predict_question_class(question_clf, df_question_predict): 81 | return question_clf.predict(df_question_predict), question_clf 82 | 83 | 84 | def load_classifier_model(model_type="linearSVC"): 85 | 86 | # HELP: Not using the persistent classifier. SVC fails when it encounters previously unseen features at training. 87 | # Refer the comment in query_container 88 | 89 | training_model_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_MODEL) 90 | 91 | if model_type == "linearSVC": 92 | return joblib.load(training_model_path) 93 | 94 | 95 | def get_question_predict_data(en_doc=None, df_question_test=None): 96 | 97 | if df_question_test is None: 98 | # currently only supports single sentence classification 99 | sentence_list = list(en_doc.sents)[0:1] 100 | 101 | else: 102 | sentence_list = df_question_test["Question"].tolist() 103 | 104 | import spacy 105 | en_nlp = spacy.load(EN_MODEL_MD) 106 | 107 | question_data_frame = [] 108 | 109 | for sentence in sentence_list: 110 | 111 | wh_bi_gram = [] 112 | root_token, wh_pos, wh_nbor_pos, wh_word = [""] * 4 113 | 114 | if df_question_test is not None: 115 | en_doc = en_nlp(u'' + sentence) 116 | sentence = list(en_doc.sents)[0] 117 | 118 | for token in sentence: 119 | 120 | if token.tag_ == "WDT" or token.tag_ == "WP" or token.tag_ == "WP$" or token.tag_ == "WRB": 121 | wh_pos = token.tag_ 122 | wh_word = token.text 123 | wh_bi_gram.append(token.text) 124 | wh_bi_gram.append(str(en_doc[token.i + 1])) 125 | wh_nbor_pos = en_doc[token.i + 1].tag_ 126 | 127 | if token.dep_ == "ROOT": 128 | root_token = token.tag_ 129 | 130 | question_data_frame_obj = {'WH': wh_word, 'WH-POS': wh_pos, 'WH-NBOR-POS': wh_nbor_pos, 'Root-POS': root_token} 131 | question_data_frame.append(question_data_frame_obj) 132 | logger.debug("WH : {0} | WH-POS : {1} | WH-NBOR-POS : {2} | Root-POS : {3}" 133 | .format(wh_word, wh_pos, wh_nbor_pos, root_token)) 134 | 135 | df_question = pandas.DataFrame(question_data_frame) 136 | 137 | return df_question 138 | 139 | 140 | def classify_question(en_doc=None, df_question_train=None, df_question_test=None): 141 | """ Determine whether this is a who, what, when, where or why question """ 142 | 143 | if df_question_train is None: 144 | training_data_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_TRAINING_DATA) 145 | df_question_train = pandas.read_csv(training_data_path, sep='|', header=0) 146 | 147 | df_question_class = remove_irrelevant_features(df_question_train) 148 | 149 | if df_question_test is None: 150 | df_question_predict = get_question_predict_data(en_doc=en_doc) 151 | else: 152 | df_question_predict = get_question_predict_data(df_question_test=df_question_test) 153 | 154 | df_question_train = pre_process(df_question_train) 155 | df_question_predict = pre_process(df_question_predict) 156 | 157 | df_question_train, df_question_predict = transform_data_matrix(df_question_train, df_question_predict) 158 | 159 | question_clf = load_classifier_model() 160 | 161 | logger.debug("Classifier: {0}".format(question_clf)) 162 | 163 | predicted_class, svc_clf = support_vector_machine(df_question_train, df_question_class, df_question_predict) 164 | 165 | if df_question_test is not None: 166 | return predicted_class, svc_clf, df_question_class, df_question_train 167 | else: 168 | return predicted_class 169 | 170 | 171 | if __name__ == "__main__": 172 | 173 | import spacy 174 | from time import time 175 | 176 | logging.basicConfig(level=logging.DEBUG) 177 | start_time = time() 178 | en_nlp_l = spacy.load(EN_MODEL_MD) 179 | 180 | question = 'Who is Linus Torvalds ?' 181 | en_doc_l = en_nlp_l(u'' + question) 182 | 183 | question_class = classify_question(en_doc_l) 184 | 185 | logger.info("Class: {0}".format(question_class)) 186 | 187 | end_time = time() 188 | logger.info("Total prediction time : {0}".format(end_time - start_time)) 189 | -------------------------------------------------------------------------------- /qas/classifier/question_classifier_trainer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import logging 4 | import pandas 5 | import csv 6 | import spacy 7 | 8 | 9 | from sklearn.naive_bayes import GaussianNB 10 | from sklearn.svm import LinearSVC 11 | from sklearn.externals import joblib 12 | from scipy.sparse import csr_matrix 13 | 14 | from qas.constants import CORPUS_DIR, EN_MODEL_MD 15 | from qas.corpus.data import QUESTION_CLASSIFICATION_TRAINING_DATA, \ 16 | QUESTION_CLASSIFICATION_RAW_DATA, QUESTION_CLASSIFICATION_MODEL 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | def get_data_info(question_df): 22 | logger.debug("\n{0}".format(question_df.head())) 23 | logger.debug("\n{0}".format(question_df.info())) 24 | logger.debug("\n{0}".format(question_df.describe())) 25 | logger.debug("\n{0}".format(question_df.columns)) 26 | 27 | 28 | def pre_process(question_df): 29 | return pandas.get_dummies(question_df) 30 | 31 | 32 | def transform_data_matrix(df_question_train): 33 | 34 | # Generate Compressed Sparse Row matrix: 35 | # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html 36 | logger.debug("Training data: {0}".format(df_question_train.shape)) 37 | df_question_train = csr_matrix(df_question_train) 38 | 39 | return df_question_train 40 | 41 | 42 | def naive_bayes_classifier(df_question_train, df_question_class): 43 | gnb = GaussianNB() 44 | gnb.fit(df_question_train, df_question_class) 45 | logger.info("Gaussian Naive Bayes: {0}".format(gnb)) 46 | 47 | return gnb 48 | 49 | 50 | def support_vector_machine(df_question_train, df_question_class): 51 | lin_clf = LinearSVC() 52 | lin_clf.fit(df_question_train, df_question_class) 53 | logger.info("Linear SVC: {0}".format(lin_clf)) 54 | 55 | return lin_clf 56 | 57 | 58 | def save_classifier_model(df_question_train, df_question_class, model_type="linearSVC"): 59 | 60 | """ 61 | FIXME: Although the classifier is being saved in Pickle file. It is not being used to predict. 62 | Since, Support Vector Classifier, fails when it encounters new features it failed to see while training. 63 | """ 64 | 65 | classifier_model = None 66 | training_model_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_MODEL) 67 | 68 | if model_type == "linearSVC": 69 | classifier_model = support_vector_machine(df_question_train, df_question_class) 70 | else: 71 | logger.error("Undefined Classifier") 72 | 73 | if classifier_model is not None: 74 | joblib.dump(classifier_model, training_model_path) 75 | logger.info("Model saved at {0}".format(training_model_path)) 76 | else: 77 | logger.error("Model empty") 78 | 79 | 80 | def remove_irrelevant_features(df_question): 81 | df_question_class = df_question.pop('Class') 82 | 83 | df_question.pop('Question') 84 | df_question.pop('WH-Bigram') 85 | 86 | return df_question_class 87 | 88 | 89 | def train_question_classifier(training_data_path): 90 | """ 91 | Question Classifier based on its feature. 92 | CSV: Training Data `qclassifier_trainer.csv` 93 | #Question|WH|WH-Bigram|WH-POS|WH-NBOR-POS|Root-POS|Class 94 | Using: Linear Support Vector Machine 95 | Model: Saved as Pickle `question_classifier.pkl` 96 | """ 97 | 98 | df_question = pandas.read_csv(training_data_path, sep='|', header=0) 99 | 100 | get_data_info(df_question) 101 | 102 | df_question_class = remove_irrelevant_features(df_question) 103 | 104 | df_question_train = pre_process(df_question) 105 | 106 | df_question_train = transform_data_matrix(df_question_train) 107 | 108 | save_classifier_model(df_question_train, df_question_class) 109 | 110 | 111 | def read_input_file(raw_data_file, training_data_path, en_nlp): 112 | 113 | with open(training_data_path, 'a', newline='') as csv_fp: 114 | csv_fp_writer = csv.writer(csv_fp, delimiter='|') 115 | for row in raw_data_file: 116 | list_row = row.split(" ") 117 | question_class_list = list_row[0].split(":") 118 | question = " ".join(list_row[1:len(list_row)]) 119 | question = question.strip("\n") 120 | question_class = question_class_list[0] 121 | 122 | process_question(question, question_class, en_nlp, training_data_path, csv_fp_writer) 123 | 124 | csv_fp.close() 125 | 126 | 127 | def process_question(question, question_class, en_nlp, training_data_path, csv_fp_writer): 128 | en_doc = en_nlp(u'' + question) 129 | sentence_list = list(en_doc.sents) 130 | 131 | # Currently question classifier classifies only the 1st sentence of the question 132 | sentence = sentence_list[0] 133 | 134 | wh_bi_gram = [] 135 | root_token, wh_pos, wh_nbor_pos, wh_word = [""] * 4 136 | 137 | for token in sentence: 138 | 139 | # if token is of WH question type 140 | if token.tag_ == "WDT" or token.tag_ == "WP" or token.tag_ == "WP$" or token.tag_ == "WRB": 141 | wh_pos = token.tag_ 142 | wh_word = token.text 143 | wh_bi_gram.append(token.text) 144 | wh_bi_gram.append(str(en_doc[token.i + 1])) 145 | wh_nbor_pos = en_doc[token.i + 1].tag_ 146 | 147 | # if token is the root of sentence 148 | if token.dep_ == "ROOT": 149 | root_token = token.tag_ 150 | 151 | if wh_word != "" and " ".join(wh_bi_gram) != "" and wh_pos != "" and wh_nbor_pos != "": 152 | csv_fp_writer.writerow([question, wh_word, " ".join(wh_bi_gram), wh_pos, wh_nbor_pos, root_token, question_class]) 153 | else: 154 | logger.error("Extraction failed: {0}:{1}".format(question, question_class)) 155 | 156 | 157 | def clean_old_data(training_data_path): 158 | 159 | question_features = ['Question', 'WH', 'WH-Bigram', 'WH-POS', 'WH-NBOR-POS', 'Root-POS', 'Class'] 160 | 161 | with open(training_data_path, 'w', newline='') as csv_fp: 162 | csv_fp_writer = csv.writer(csv_fp, delimiter='|') 163 | csv_fp_writer.writerow(question_features) 164 | csv_fp.close() 165 | 166 | 167 | def extract_training_features(raw_data_path, training_data_path, en_nlp): 168 | with open(raw_data_path, 'r') as fp: 169 | read_input_file(fp, training_data_path, en_nlp) 170 | fp.close() 171 | logger.info("Extracted features from raw data.") 172 | logger.info("Excluded data where features failed to extract.") 173 | 174 | 175 | if __name__ == "__main__": 176 | 177 | from time import time 178 | 179 | logging.basicConfig(level=logging.DEBUG) 180 | if len(sys.argv) > 1: 181 | start_time = time() 182 | 183 | should_extract = sys.argv[1] 184 | 185 | training_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_TRAINING_DATA) 186 | raw_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_RAW_DATA) 187 | 188 | if should_extract: 189 | logger.info("Cleaning enabled.") 190 | clean_old_data(training_path) 191 | en_nlp_l = spacy.load(EN_MODEL_MD) 192 | 193 | extract_training_features(raw_path, training_path, en_nlp_l) 194 | 195 | train_question_classifier(training_path) 196 | 197 | end_time = time() 198 | logger.info("Total training time : {0}".format(end_time - start_time)) 199 | else: 200 | raise ValueError('Missing option to enable to disable feature extraction') 201 | -------------------------------------------------------------------------------- /qas/constants.py: -------------------------------------------------------------------------------- 1 | """ Package Global Constants """ 2 | import os 3 | 4 | 5 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 6 | CORPUS_DIR = os.path.join(os.path.dirname(__file__), 'corpus') 7 | OUTPUT_DIR = os.path.join(os.path.dirname(__file__), 'output') 8 | SAVE_OUTPUTS = True 9 | EXAMPLE_QUESTIONS = [ 10 | "When was linux kernel version 4.0 released ?", 11 | "How to compile linux kernel ?", 12 | "Who is Linus Torvalds ?", 13 | "What's the only color Johnny Cash wears on stage ?", 14 | "What are the four applications bundled with Windows Vista ?", 15 | "How do you use a seismograph ?", 16 | "What is Facebook Spaces ?"] 17 | 18 | EN_MODEL_DEFAULT = "en" 19 | EN_MODEL_SM = "en_core_web_sm" 20 | EN_MODEL_MD = "en_core_web_md" 21 | EN_MODEL_LG = "en_core_web_lg" 22 | 23 | 24 | -------------------------------------------------------------------------------- /qas/corpus/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/corpus/__init__.py -------------------------------------------------------------------------------- /qas/corpus/data.py: -------------------------------------------------------------------------------- 1 | 2 | QUESTION_CLASSIFICATION_TRAINING_DATA = "qclassifier_trainer.csv" 3 | QUESTION_CLASSIFICATION_RAW_DATA = "qclassification_data.txt" 4 | QUESTION_CLASSIFICATION_MODEL = "question_classifier.pkl" 5 | 6 | WIKI_QA_TSV = "WikiQA.tsv" 7 | QA_TEST_DATA = "qa_test.db" 8 | 9 | -------------------------------------------------------------------------------- /qas/corpus/feature_trainer.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/corpus/feature_trainer.csv -------------------------------------------------------------------------------- /qas/corpus/qa_test.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/corpus/qa_test.db -------------------------------------------------------------------------------- /qas/corpus/qclasses.txt: -------------------------------------------------------------------------------- 1 | ABBREVIATION abbreviation 2 | abb abbreviation 3 | exp expression abbreviated 4 | ENTITY entities 5 | animal animals 6 | body organs of body 7 | color colors 8 | creative inventions, books and other creative pieces 9 | currency currency names 10 | dis.med. diseases and medicine 11 | event events 12 | food food 13 | instrument musical instrument 14 | lang languages 15 | letter letters like a-z 16 | other other entities 17 | plant plants 18 | product products 19 | religion religions 20 | sport sports 21 | substance elements and substances 22 | symbol symbols and signs 23 | technique techniques and methods 24 | term equivalent terms 25 | vehicle vehicles 26 | word words with a special property 27 | DESCRIPTION description and abstract concepts 28 | definition definition of sth. 29 | description description of sth. 30 | manner manner of an action 31 | reason reasons 32 | HUMAN human beings 33 | group a group or organization of persons 34 | ind an individual 35 | title title of a person 36 | description description of a person 37 | LOCATION locations 38 | city cities 39 | country countries 40 | mountain mountains 41 | other other locations 42 | state states 43 | NUMERIC numeric values 44 | code postcodes or other codes 45 | count number of sth. 46 | date dates 47 | distance linear measures 48 | money prices 49 | order ranks 50 | other other numbers 51 | period the lasting time of sth. 52 | percent fractions 53 | speed speed 54 | temp temperature 55 | size size, area and volume 56 | weight weight -------------------------------------------------------------------------------- /qas/corpus/question_classifier.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/corpus/question_classifier.pkl -------------------------------------------------------------------------------- /qas/corpus/stop_words.txt: -------------------------------------------------------------------------------- 1 | a 2 | about 3 | above 4 | after 5 | again 6 | against 7 | all 8 | am 9 | an 10 | and 11 | any 12 | are 13 | aren't 14 | as 15 | at 16 | be 17 | because 18 | been 19 | before 20 | being 21 | below 22 | between 23 | both 24 | but 25 | by 26 | can't 27 | cannot 28 | could 29 | couldn't 30 | did 31 | didn't 32 | do 33 | does 34 | doesn't 35 | doing 36 | don't 37 | down 38 | during 39 | each 40 | few 41 | for 42 | from 43 | further 44 | had 45 | hadn't 46 | has 47 | hasn't 48 | have 49 | haven't 50 | having 51 | he 52 | he'd 53 | he'll 54 | he's 55 | her 56 | here 57 | here's 58 | hers 59 | herself 60 | him 61 | himself 62 | his 63 | how 64 | how's 65 | i 66 | i'd 67 | i'll 68 | i'm 69 | i've 70 | if 71 | in 72 | into 73 | is 74 | isn't 75 | it 76 | it's 77 | its 78 | itself 79 | let's 80 | me 81 | more 82 | most 83 | mustn't 84 | my 85 | myself 86 | no 87 | nor 88 | not 89 | of 90 | off 91 | on 92 | once 93 | only 94 | or 95 | other 96 | ought 97 | our 98 | ours 99 | ourselves 100 | out 101 | over 102 | own 103 | same 104 | shan't 105 | she 106 | she'd 107 | she'll 108 | she's 109 | should 110 | shouldn't 111 | so 112 | some 113 | such 114 | than 115 | that 116 | that's 117 | the 118 | their 119 | theirs 120 | them 121 | themselves 122 | then 123 | there 124 | there's 125 | these 126 | they 127 | they'd 128 | they'll 129 | they're 130 | they've 131 | this 132 | those 133 | through 134 | to 135 | too 136 | under 137 | until 138 | up 139 | very 140 | was 141 | wasn't 142 | we 143 | we'd 144 | we'll 145 | we're 146 | we've 147 | were 148 | weren't 149 | what 150 | what's 151 | when 152 | when's 153 | where 154 | where's 155 | which 156 | while 157 | who 158 | who's 159 | whom 160 | why 161 | why's 162 | with 163 | won't 164 | would 165 | wouldn't 166 | you 167 | you'd 168 | you'll 169 | you're 170 | you've 171 | your 172 | yours 173 | yourself 174 | yourselves -------------------------------------------------------------------------------- /qas/corpus/test_question.txt: -------------------------------------------------------------------------------- 1 | What are Cushman or Wakefield known for ? 2 | Why would the NRA not favour gun control ? 3 | What is the difference between Quality Assurance and Quality Control? 4 | What are the toxicities of amiodarone? 5 | What is the most common cause of right heart failure? 6 | Which instrument is used to measure altitudes in aircraft's ? -------------------------------------------------------------------------------- /qas/doc_scorer.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import re 4 | from collections import Counter 5 | 6 | import gensim 7 | from esstore.es_config import __wiki_content__ 8 | from esstore.es_operate import ElasticSearchOperate 9 | 10 | from qas.constants import CORPUS_DIR 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | # Document scoring should be done on elasticsearch and not with this 15 | # search terms [....] where document id is [...or...] 16 | 17 | 18 | def query2vec(query, dictionary): 19 | corpus = dictionary.doc2bow(query) 20 | return corpus 21 | 22 | 23 | def doc2vec(documents): 24 | with open(os.path.join(CORPUS_DIR, 'stop_words.txt'), 'r', newline='') as stp_fp: 25 | stop_list = (stp_fp.read()).lower().split("\n") 26 | texts = [[word for word in doc.lower().split() if word not in stop_list]for doc in documents.values()] 27 | frequency = Counter() 28 | for sent in texts: 29 | for token in sent: 30 | frequency[token] += 1 31 | 32 | texts = [[token for token in snipp if frequency[token] > 1]for snipp in texts] 33 | 34 | dictionary = gensim.corpora.Dictionary(texts) 35 | 36 | corpus = [dictionary.doc2bow(snipp) for snipp in texts] 37 | 38 | return corpus, dictionary 39 | 40 | 41 | def transform_vec(corpus, query_corpus): 42 | tfidf = gensim.models.TfidfModel(corpus) 43 | 44 | corpus_tfidf = tfidf[corpus] 45 | query_tfidf = tfidf[query_corpus] 46 | return corpus_tfidf, query_tfidf 47 | 48 | 49 | def similariy(corpus_tfidf, query_tfidf): 50 | index = gensim.similarities.SparseMatrixSimilarity(corpus_tfidf, num_features=100000) 51 | 52 | simi = index[query_tfidf] 53 | 54 | simi_sorted = sorted(enumerate(simi), key=lambda item: -item[1]) 55 | return simi_sorted 56 | 57 | 58 | def pre_process_doc(list_docs): 59 | 60 | regex_newline = re.compile(r'(\\n)+') 61 | regex_references = re.compile(r'== References(.)+') 62 | regex_apostrophe = re.compile(r"(\\')") 63 | regex_or = re.compile(r'(?<=[A-Za-z.]\s)+/(?=\s+[A-Za-z])') 64 | regex_sections = re.compile(r'(=+[a-zA-Z0-9\s]+=+([a-zA-Z0-9\s]+=+)*)') 65 | regex_whitespace = re.compile(r"(\s)+") 66 | 67 | for doc in list_docs: 68 | snip = list_docs[doc] 69 | snip = regex_newline.sub(" ", snip) 70 | snip = regex_references.sub("", snip) 71 | snip = regex_apostrophe.sub("'", snip) 72 | snip = regex_or.sub("or", snip) 73 | snip = regex_sections.sub("", snip) 74 | snip = regex_whitespace.sub(" ", snip) 75 | 76 | list_docs[doc] = snip 77 | 78 | with open(os.path.join(CORPUS_DIR, 'know_corp.txt'), 'w') as fp: 79 | for op_doc in list_docs: 80 | fp.write(str(op_doc) + "\n") 81 | 82 | 83 | def combine(sub_keys, keywords_splits, lb, mb, ub): 84 | whitespace = ' ' 85 | while mb != ub: 86 | keywords_splits.append(whitespace.join(sub_keys[lb: mb])) 87 | keywords_splits.append(whitespace.join(sub_keys[mb: ub])) 88 | mb += 1 89 | del sub_keys[0] 90 | if len(sub_keys) > 2: 91 | combine(sub_keys, keywords_splits, 0, 1, len(sub_keys)) 92 | 93 | 94 | def keywords_splitter(keywords, keywords_splits): 95 | 96 | for key in keywords: 97 | sub_keys = key.split() 98 | 99 | if len(sub_keys) > 2: 100 | combine(sub_keys, keywords_splits, 0, 1, len(sub_keys)) 101 | 102 | 103 | def score_docs(documents, keywords): 104 | 105 | keywords = [keywords[feat].lower() for feat in range(0, len(keywords) - 1)] 106 | whitespace = ' ' 107 | keywords_splits = whitespace.join(keywords).split() 108 | 109 | keywords_splitter(keywords, keywords_splits) 110 | keywords_splits = list(set(keywords_splits + keywords)) 111 | # print(keywords_splits) 112 | 113 | # pre_process_doc(documents) 114 | 115 | corpus, dictionary = doc2vec(documents) 116 | query_corpus = query2vec(keywords_splits, dictionary) 117 | 118 | corpus_tfidf, query_tfidf = transform_vec(corpus, query_corpus) 119 | 120 | simi_sorted = similariy(corpus_tfidf, query_tfidf) 121 | 122 | if len(simi_sorted) > 3: 123 | return simi_sorted[0:3] 124 | return simi_sorted 125 | 126 | 127 | def rank_docs(keywords, page_ids): 128 | 129 | doc_dictionary = {} 130 | 131 | es_conn = ElasticSearchOperate() 132 | for page in page_ids: 133 | doc_data = es_conn.get_wiki_article(page) 134 | if __wiki_content__ in doc_data: 135 | doc_dictionary[page] = doc_data[__wiki_content__] 136 | ranked_docs = score_docs(doc_dictionary, keywords) 137 | return ranked_docs 138 | 139 | 140 | if __name__ == "__main__": 141 | logging.basicConfig(level=logging.DEBUG) 142 | keywords_ip = ['albert einstein', 'birth'] 143 | page_ids = [736, 18742711, 12738235, 83443, 18978770, 79449] 144 | rank_docs = rank_docs(keywords_ip, page_ids) 145 | print(rank_docs) 146 | -------------------------------------------------------------------------------- /qas/doc_search_rank.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from qas.esstore.es_operate import ElasticSearchOperate 4 | 5 | """ 6 | Created by felix on 25/3/18 at 5:19 PM 7 | """ 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | def search_rank(query): 13 | es = ElasticSearchOperate() 14 | result_all = es.search_wiki_article(query) 15 | logging.debug("Ranked Wiki Pages Title: {0}".format([result.get_wiki_title() for result in result_all])) 16 | return result_all 17 | 18 | 19 | if __name__ == "__main__": 20 | 21 | logging.basicConfig(level=logging.DEBUG) 22 | 23 | mquery = list([[['Albert', 'Einstein', 'birth'], [], [], []]]) 24 | 25 | les = ElasticSearchOperate() 26 | res_all = les.search_wiki_article(mquery) 27 | for res in res_all: 28 | print(res.get_wiki_title()) 29 | -------------------------------------------------------------------------------- /qas/esstore/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/esstore/__init__.py -------------------------------------------------------------------------------- /qas/esstore/es_config.py: -------------------------------------------------------------------------------- 1 | 2 | __index_name__ = "adam_qas" 3 | __num_shards__ = 1 4 | __num_replicas__ = 0 5 | # __doc_type__ = "article" # Elasticsearch 7.X: specifying types in requests is now deprecated 6 | __index_version__ = 2 7 | 8 | __wiki_title__ = "title" 9 | __wiki_updated_date__ = "updated" 10 | __wiki_raw__ = "raw" 11 | __wiki_content__ = "content" 12 | __wiki_content_info__ = "content_info" 13 | __wiki_content_table__ = "content_table" 14 | __wiki_revision__ = "revision" 15 | __wiki_pageid__ = "article_id" 16 | 17 | 18 | __analyzer_std__ = "standard" 19 | __analyzer_en__ = "english" 20 | __analyzer_adam__ = "adam_analyzer" 21 | -------------------------------------------------------------------------------- /qas/esstore/es_connect.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | from os.path import isfile 4 | 5 | from elasticsearch import Elasticsearch 6 | from elasticsearch.exceptions import ConnectionError as ESConnectionError 7 | from urllib3.exceptions import NewConnectionError 8 | 9 | from qas.esstore.es_config import __index_name__, __wiki_title__, __wiki_updated_date__, __wiki_content__, \ 10 | __wiki_content_info__, __wiki_content_table__, __wiki_revision__, __wiki_raw__, __num_shards__, \ 11 | __num_replicas__, __analyzer_en__, __analyzer_adam__, __index_version__ 12 | 13 | """ 14 | Meta Class for managing elasticsearch db connection. It also serves as an singleton 15 | """ 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | class ElasticSearchMeta(type): 21 | _instances = {} 22 | 23 | def __call__(cls, *args, **kwargs): 24 | if cls not in cls._instances: 25 | cls._instances[cls] = super(ElasticSearchMeta, cls).__call__(*args, **kwargs) 26 | return cls._instances[cls] 27 | 28 | 29 | class ElasticSearchConn(metaclass=ElasticSearchMeta): 30 | if isfile('../.dockerenv'): 31 | __hostname__ = 'elasticsearch' 32 | else: 33 | __hostname__ = 'localhost' 34 | __port__ = 9200 35 | __es_conn__ = None 36 | es_index_config = None 37 | 38 | def __init__(self): 39 | es_host = {'host': self.__hostname__, 'port': self.__port__} 40 | self.__es_conn__ = Elasticsearch(hosts=[es_host]) 41 | self.set_up_index() 42 | 43 | @staticmethod 44 | def get_index_mapping(): 45 | return { 46 | "settings": { 47 | "number_of_shards": __num_shards__, 48 | "number_of_replicas": __num_replicas__, 49 | "analysis": { 50 | "filter": { 51 | "english_stop": { 52 | "type": "stop", 53 | "stopwords": "_english_" 54 | }, 55 | "english_porter2": { 56 | "type": "stemmer", 57 | "language": "porter2" 58 | } 59 | }, 60 | "analyzer": { 61 | __analyzer_adam__: { 62 | "type": "custom", 63 | "tokenizer": "standard", 64 | "filter": [ 65 | "lowercase", 66 | "english_stop", 67 | "english_porter2" 68 | ] 69 | } 70 | } 71 | }, 72 | }, 73 | "mappings": { 74 | "_meta": { 75 | "version": 2 76 | }, 77 | "properties": { 78 | __wiki_title__: { 79 | "type": "text", 80 | "analyzer": __analyzer_adam__ 81 | }, 82 | __wiki_updated_date__: { 83 | "type": "date" 84 | }, 85 | __wiki_raw__: { 86 | "type": "object", 87 | "enabled": "false" 88 | }, 89 | __wiki_content__: { 90 | "type": "text", 91 | "analyzer": __analyzer_adam__ 92 | }, 93 | __wiki_content_info__: { 94 | "type": "text", 95 | "analyzer": __analyzer_adam__ 96 | }, 97 | __wiki_content_table__: { 98 | "type": "text", 99 | "analyzer": __analyzer_adam__ 100 | }, 101 | __wiki_revision__: { 102 | "type": "long" 103 | } 104 | } 105 | } 106 | } 107 | 108 | def create_index(self): 109 | # ignore 400 cause by IndexAlreadyExistsException when creating an index 110 | self.es_index_config = ElasticSearchConn.get_index_mapping() 111 | res = self.__es_conn__.indices.create(index=__index_name__, body=self.es_index_config, ignore=400) 112 | if 'error' in res and res['status'] == 400: 113 | # NOTE: Illegal argument errors are also being masked here, so test the index creation 114 | error_type = res['error']['root_cause'][0]['type'] 115 | if error_type == 'resource_already_exists_exception': 116 | logger.debug("Index already exists") 117 | else: 118 | logger.error("Error Occurred in Index creation:{0}".format(res)) 119 | print("\n -- Unable to create Index:"+error_type+"--\n") 120 | sys.exit(1) 121 | elif res['acknowledged'] and res['index'] == __index_name__: 122 | logger.debug("Index Created") 123 | else: 124 | logger.error("Index creation failed:{0}".format(res)) 125 | print("\n -- Unable to create Index--\n") 126 | sys.exit(1) 127 | 128 | def update_index(self, current_version): 129 | 130 | """ 131 | Existing type and field mappings cannot be updated. Changing the mapping would mean invalidating already indexed documents. 132 | Instead, you should create a new index with the correct mappings and reindex your data into that index. 133 | """ 134 | 135 | updated_mapping = None 136 | 137 | # Migrating from version 1 to version 2 138 | if current_version == 1 and __index_version__ == 2: 139 | updated_mapping = { 140 | "_meta": { 141 | "version": __index_version__ 142 | }, 143 | "properties": { 144 | __wiki_content_info__: { 145 | "type": "text", 146 | "analyzer": __analyzer_en__ 147 | }, 148 | __wiki_content_table__: { 149 | "type": "text", 150 | "analyzer": __analyzer_en__ 151 | } 152 | } 153 | } 154 | 155 | if updated_mapping is not None: 156 | self.__es_conn__.indices.close(index=__index_name__) 157 | res = self.__es_conn__.indices.put_mapping(index=__index_name__, body=updated_mapping) 158 | self.__es_conn__.indices.open(index=__index_name__) 159 | 160 | def set_up_index(self): 161 | try: 162 | try: 163 | try: 164 | index_exists = self.__es_conn__.indices.exists(index=__index_name__) 165 | if not index_exists: 166 | self.create_index() 167 | else: 168 | res = self.__es_conn__.indices.get_mapping(index=__index_name__) 169 | try: 170 | current_version = res[__index_name__]['mappings']['_meta']['version'] 171 | if current_version < __index_version__: 172 | self.update_index(current_version) 173 | elif current_version is None: 174 | logger.error("Old Index Mapping. Manually reindex the index to persist your data.") 175 | print("\n -- Old Index Mapping. Manually reindex the index to persist your data.--\n") 176 | sys.exit(1) 177 | except KeyError: 178 | logger.error("Old Index Mapping. Manually reindex the index to persist your data.") 179 | print("\n -- Old Index Mapping. Manually reindex the index to persist your data.--\n") 180 | sys.exit(1) 181 | 182 | except ESConnectionError as e: 183 | logger.error("Elasticsearch is not installed or its service is not running. {0}".format(e)) 184 | print("\n -- Elasticsearch is not installed or its service is not running.--\n", e) 185 | sys.exit(1) 186 | except NewConnectionError: 187 | pass 188 | except ConnectionRefusedError: 189 | pass 190 | 191 | def get_db_connection(self): 192 | return self.__es_conn__ 193 | 194 | 195 | if __name__ == "__main__": 196 | es = ElasticSearchConn() 197 | es_conn = es.get_db_connection() -------------------------------------------------------------------------------- /qas/esstore/es_operate.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import warnings 3 | from datetime import datetime 4 | 5 | from qas.esstore.es_config import __index_name__, __wiki_revision__, __wiki_title__, \ 6 | __wiki_content__, __wiki_content_info__, __wiki_content_table__, __wiki_updated_date__, __wiki_raw__ 7 | from qas.esstore.es_connect import ElasticSearchConn 8 | from qas.model.es_document import ElasticSearchDocument 9 | from qas.model.query_container import QueryContainer 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def resolve_operator(conj_op): 15 | if conj_op == "and": 16 | return "and" 17 | elif conj_op == "or": 18 | return "or" 19 | 20 | 21 | class ElasticSearchOperate: 22 | es_conn = None 23 | 24 | def __init__(self): 25 | es = ElasticSearchConn() 26 | self.es_conn = es.get_db_connection() 27 | 28 | def insert_wiki_article(self, pageid, revid, title, raw): 29 | warnings.warn("Deprecated: This will insert the document without any checks.", DeprecationWarning) 30 | wiki_body = { 31 | __wiki_revision__: revid, 32 | __wiki_title__: title, 33 | __wiki_raw__: raw, 34 | __wiki_updated_date__: datetime.now() 35 | } 36 | res = self.es_conn.index(index=__index_name__, body=wiki_body, id=pageid) 37 | logger.debug("Article Inserted:{0}".format(res['result'])) 38 | return res['result'] == 'created' or res['result'] == 'updated' 39 | 40 | def upsert_wiki_article(self, pageid, revid, title, raw): 41 | warnings.warn("Deprecated: This will upsert the complete document in any case, instead of upserting only if" 42 | "revision id changes.", DeprecationWarning) 43 | 44 | wiki_body = { 45 | "doc": { 46 | __wiki_revision__: revid, 47 | __wiki_title__: title, 48 | __wiki_raw__: raw, 49 | __wiki_updated_date__: datetime.now() 50 | }, 51 | "doc_as_upsert": True 52 | } 53 | res = self.es_conn.update(index=__index_name__, body=wiki_body, id=pageid) 54 | logger.debug("Article Upserted:{0}".format(res['result'])) 55 | return res['result'] == 'created' or res['result'] == 'updated' 56 | 57 | def upsert_wiki_article_if_updated(self, pageid, revid, title, raw): 58 | 59 | """ 60 | Refer: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html 61 | If the document does not already exist, the contents of the upsert element will be inserted as a new document. 62 | If the document does exist, then the script will be executed instead 63 | """ 64 | 65 | wiki_body = { 66 | "script": { 67 | "source": "if (ctx._source."+__wiki_revision__+" < params.new_revision) " 68 | "{ctx._source = params.new_article } " 69 | "else {ctx.op = 'none' }", 70 | "lang": "painless", 71 | "params": { 72 | "new_revision": revid, 73 | "new_article": { 74 | __wiki_revision__: revid, 75 | __wiki_title__: title, 76 | __wiki_raw__: raw, 77 | __wiki_updated_date__: datetime.now() 78 | } 79 | } 80 | }, 81 | "upsert": { 82 | __wiki_revision__: revid, 83 | __wiki_title__: title, 84 | __wiki_raw__: raw, 85 | __wiki_updated_date__: datetime.now() 86 | } 87 | } 88 | res = self.es_conn.update(index=__index_name__, body=wiki_body, id=pageid) 89 | logger.debug("Article Upserted:{0}".format(res['result'])) 90 | return res['result'] == 'created' or res['result'] == 'updated' or res['result'] == 'noop' 91 | 92 | def update_wiki_article(self, pagid, content=None, content_info=None, content_table=None): 93 | wiki_body = None 94 | 95 | if content is not None: 96 | wiki_body = { 97 | "script": { 98 | "source": "ctx._source." + __wiki_content__ + " = params." + __wiki_content__, 99 | "lang": "painless", 100 | "params": { 101 | __wiki_content__: content 102 | } 103 | } 104 | } 105 | 106 | elif content_info is not None: 107 | wiki_body = { 108 | "script": { 109 | "source": "ctx._source." + __wiki_content_info__ + " = params." + __wiki_content_info__, 110 | "lang": "painless", 111 | "params": { 112 | __wiki_content_info__: content_info 113 | } 114 | } 115 | } 116 | 117 | elif content_table is not None: 118 | wiki_body = { 119 | "script": { 120 | "source": "ctx._source." + __wiki_content_table__ + " = params." + __wiki_content_table__, 121 | "lang": "painless", 122 | "params": { 123 | __wiki_content_table__: content_table 124 | } 125 | } 126 | } 127 | 128 | if wiki_body is not None: 129 | res = self.es_conn.update(index=__index_name__, id=pagid, body=wiki_body) 130 | logger.debug("Article Updated:{0}".format(res['result'])) 131 | return res['result'] == 'updated' 132 | else: 133 | return None 134 | 135 | def get_wiki_article(self, pageid): 136 | res = self.es_conn.get(index=__index_name__, id=pageid) 137 | logger.debug("Article Fetched:{0}".format(res['found'])) 138 | if res['found']: 139 | return res['_source'] 140 | else: 141 | return None 142 | 143 | def delete_wiki_article(self, pageid): 144 | res = self.es_conn.delete(index=__index_name__, id=pageid) 145 | logger.debug("Article Deleted:{0}".format(res['result'])) 146 | return res['result'] == 'deleted' 147 | 148 | def extract_info_from_article(self, features, conjunct, conj, index): 149 | if isinstance(conj, list): 150 | features = [feat for feat in features if feat not in conj] 151 | if index < len(conjunct) - 1: 152 | conj_op = conjunct[index + 1] 153 | return conj_op 154 | 155 | # def extract_info_here(self, negations, features, conj_op, es_operator, must_nut_match): 156 | # if (negations is not None and len(negations) > 0: 157 | # for index, negate in enumerate(negations): 158 | # if isinstance(negate, list): 159 | # features = [feat for feat in features if feat not in negate] 160 | # if index < len(negations - 1) 161 | # conj_op = negations[index + 1] 162 | # es_operator = resolve_operator(conj_op) 163 | # return negations 164 | 165 | def search_wiki_article(self, search_query): 166 | 167 | """ 168 | Refer: https://www.elastic.co/guide/en/elasticsearch/reference/current/full-text-queries.html [6.X] 169 | https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html [2.X] 170 | """ 171 | 172 | """ 173 | The match query is of type boolean. 174 | The operator flag can be set to `or` or `and` to control the boolean clauses (defaults to or). 175 | Bool Query: [must, filter, should] 176 | The term query looks for the exact term in the field’s inverted index — it doesn’t know anything about the field’s analyzer. 177 | 178 | The match query supports multi-terms synonym expansion with the synonym_graph token filter. 179 | When this filter is used, the parser creates a phrase query for each multi-terms synonyms. 180 | 181 | The multi_match query builds on the match query to allow multi-field queries. We can sepcify the fields to be queried. 182 | The way the multi_match query is executed internally depends on the type parameter. 183 | The most_fields finds documents which match any field and combines the _score from each field. 184 | """ 185 | 186 | search_res = [] 187 | 188 | for query in search_query: 189 | if not isinstance(query, QueryContainer): 190 | query_cont = QueryContainer(query) 191 | else: 192 | query_cont = query 193 | if isinstance(query_cont, QueryContainer): 194 | features = query_cont.get_features() 195 | conjunct = query_cont.get_conjunctions() 196 | negations = query_cont.get_negations() 197 | # markers = query_cont.get_markers() 198 | 199 | must_match = [] 200 | should_match = [] 201 | must_not_match = [] 202 | 203 | if conjunct is not None and len(conjunct) > 0: 204 | for index, conj in enumerate(conjunct): 205 | conj_op = self.extract_info_from_article(features, conjunct, conj, index) 206 | es_operator = resolve_operator(conj_op) 207 | must_match_query = { 208 | "multi_match": { 209 | "query": " ".join(conj), 210 | "operator": es_operator, 211 | "type": "most_fields", 212 | "fields": [__wiki_content__, __wiki_content_info__, __wiki_content_table__] 213 | } 214 | } 215 | must_match.append(must_match_query) 216 | # FIXME: No support for negations with conjunctions 217 | 218 | if negations is not None and len(negations) > 0: 219 | for index, negate in enumerate(negations): 220 | conj_op = self.extract_info_from_article(features, negations, negate, index) 221 | es_operator = resolve_operator(conj_op) 222 | must_not_match_term = { 223 | "multi_match": { 224 | "query": " ".join(negations[index]), 225 | "operator": es_operator, 226 | "type": "most_fields", 227 | "fields": [__wiki_content__, __wiki_content_info__, __wiki_content_table__] 228 | } 229 | } 230 | must_not_match.append(must_not_match_term) 231 | 232 | if features is not None and len(features) > 0: 233 | must_match_query = { 234 | "multi_match": { 235 | "query": " ".join(features), 236 | "type": "most_fields", 237 | "fields": [__wiki_content__, __wiki_content_info__, __wiki_content_table__] 238 | } 239 | } 240 | must_match.append(must_match_query) 241 | 242 | search_body = self.build_body(must_match, must_not_match, should_match) 243 | 244 | logger.debug(search_body) 245 | 246 | es_result = self.es_conn.search(index=__index_name__, body=search_body) 247 | if es_result['hits']['hits'] is not None: 248 | es_result_hits = es_result['hits']['hits'] 249 | for result in es_result_hits: 250 | article_id = result['_id'] 251 | article_score = result['_score'] 252 | article_source = result['_source'] 253 | es_document = ElasticSearchDocument(article_id, article_source, article_score) 254 | search_res.append(es_document) 255 | 256 | else: 257 | raise ValueError("Incorrect Query Type") 258 | 259 | return search_res 260 | 261 | def build_body(self, must_match, must_not_match, should_match): 262 | search_body = { 263 | "query": { 264 | "bool": { 265 | "must": must_match, 266 | "should": should_match, 267 | "must_not": must_not_match, 268 | } 269 | } 270 | } 271 | return search_body 272 | 273 | 274 | if __name__ == "__main__": 275 | 276 | logging.basicConfig(level=logging.DEBUG) 277 | 278 | mquery = list([[['Albert', 'Einstein', 'birth'], [], [], []]]) 279 | 280 | es = ElasticSearchOperate() 281 | res_all = es.search_wiki_article(mquery) 282 | for lres in res_all: 283 | print(lres.get_wiki_title()) 284 | -------------------------------------------------------------------------------- /qas/feature_extractor.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logger = logging.getLogger(__name__) 4 | 5 | """ 6 | Penn Tree-bank : https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html 7 | """ 8 | 9 | 10 | def get_detail(sentence): 11 | for token in sentence: 12 | logger.debug("{0} -- Lemma:{1}, Tag:{2}, EntType:{3}, Dep:{4}, Head:{5}" 13 | .format(token.text, token.lemma_, token.tag_, token.ent_type_, token.dep_, token.head)) 14 | 15 | 16 | def get_compound_nouns(en_doc, token, token_text): 17 | 18 | """ 19 | Recursively find the left and right compound nouns 20 | """ 21 | 22 | parent_token = token 23 | 24 | logger.debug("Compound Noun:{0} DEP {1}".format(token.text, token.dep_)) 25 | 26 | # If previous token is a compound noun 27 | while token.i > 0 and en_doc[token.i - 1].dep_ == "compound": 28 | token_text = en_doc[token.i - 1].text + " " + token_text 29 | token = en_doc[token.i - 1] 30 | # if the compound noun has any adjective modifier 31 | token_text = get_adj_phrase(token, token_text) 32 | 33 | token = parent_token 34 | 35 | # If next token is a compound noun 36 | while token.i < len(en_doc) - 1 and en_doc[token.i + 1].dep_ == "compound": 37 | token_text = token_text + " " + en_doc[token.i + 1].text 38 | token = en_doc[token.i + 1] 39 | # if the compound noun has any adjective modifier 40 | token_text = get_adj_phrase(token, token_text) 41 | 42 | # NOTE: Can token.shape_ == Xxxx... or XXXX... token.ent_iob_ help us here ...? 43 | 44 | return token_text 45 | 46 | def this_is_adjective(dep_): 47 | return dep_ == "amod" or dep_ == "acomp" or dep_ == "ccomp" 48 | 49 | def get_adj_phrase(token, token_text): 50 | 51 | """ 52 | To fetch all the adjectives describing the noun 53 | """ 54 | 55 | # amod: An adjectival modifier of a noun is any adjectival phrase that serves to modify the meaning of the noun. 56 | # ccomp: A clausal complement of a verb or adjective is a dependent clause which is a core argument. 57 | # That is, it functions like an object of the verb, or adjective. 58 | # acomp: An adjectival complement of a verb is an adjectival phrase which functions as the complement 59 | 60 | for child in token.children: 61 | if(this_is_adjective(child.dep_)) and child.text != "much" and child.text != "many": 62 | # if child.dep_ == "amod" or child.dep_ == "acomp" or child.dep_ == "ccomp": # not for how many 63 | # if child.text != "much" and child.text != "many": 64 | token_text = child.lemma_ + " " + token_text 65 | return token_text 66 | 67 | 68 | def get_root_phrase(token, keywords): 69 | 70 | # xcomp: An open clausal complement (xcomp) of a verb or an adjective is a predicative or clausal complement 71 | # without its own subject. 72 | 73 | for child in token.children: 74 | if child.dep_ == "acomp" or child.dep_ == "xcomp" or child.dep_ == "ccomp": 75 | keywords.append(child.lemma_) 76 | return keywords 77 | 78 | 79 | def this_is_noun(tag_): 80 | # If is Noun/Proper Noun, be it Singular or Plural 81 | return tag_ == "NN" or tag_ == "NNP" or tag_ == "NNPS" or tag_ == "NNS" 82 | 83 | 84 | def get_noun_chunk(sentence, en_doc, keywords): 85 | 86 | root_word = "" 87 | 88 | for token in sentence: 89 | 90 | # If the Noun itself is not a compound Noun then we can find its compound Nouns 91 | if(this_is_noun(token.tag_)) and token.dep_ != "compound": 92 | token_text = get_compound_nouns(en_doc, token, token.text) 93 | keywords.append(token_text) 94 | 95 | if token.tag_ == "JJ" and token.dep_ == "attr": 96 | token_text = get_compound_nouns(en_doc, token, token.text) 97 | token_text = get_adj_phrase(token, token_text) 98 | keywords.append(token_text) 99 | 100 | # If is a Cardinal Number & dependency is numeric modifier 101 | # nummod : A numeric modifier of a noun is any number phrase that 102 | # serves to modify the meaning of the noun with a quantity. 103 | if token.dep_ == "nummod" or token.tag_ == "CD": 104 | token_text = token.text 105 | 106 | if token.i > 0 and en_doc[token.i - 1].tag_ == "JJ": 107 | # If previous token is Adjective, the adjective is liked with the cardinal number 108 | token_text = en_doc[token.i - 1].text + " " + token.text 109 | 110 | if token.i < len(en_doc) - 1 and en_doc[token.i + 1].tag_ == "JJ": 111 | # If next token is Adjective 112 | token_text = token.text + " " + en_doc[token.i + 1].text 113 | 114 | keywords.append(token_text) 115 | 116 | # Extracts the root word of sentence 117 | if token.dep_ == "ROOT": 118 | root_word = token.lemma_ 119 | keywords = get_root_phrase(token, keywords) 120 | 121 | return root_word, keywords 122 | 123 | 124 | def extract_features(question_type, en_doc, show_debug=False): 125 | 126 | # NOTE: In the whole pipeline question_type is not used anywhere currently... 127 | 128 | keywords = [] 129 | 130 | for sentence in en_doc.sents: 131 | if show_debug: 132 | get_detail(sentence) 133 | root, keywords = get_noun_chunk(sentence, en_doc, keywords) 134 | keywords.append(root) 135 | 136 | return keywords 137 | 138 | 139 | if __name__ == "__main__": 140 | 141 | import spacy 142 | from constants import EN_MODEL_MD 143 | 144 | logging.basicConfig(level=logging.DEBUG) 145 | 146 | question = "What's the American dollar equivalent for 8 pounds in the U.K. ?" 147 | 148 | en_nlp_l = spacy.load(EN_MODEL_MD) 149 | en_doc_l = en_nlp_l(u'' + question) 150 | 151 | logger.info("Extracted: {0}".format(extract_features("", en_doc_l, True))) 152 | -------------------------------------------------------------------------------- /qas/fetch_wiki.py: -------------------------------------------------------------------------------- 1 | import os 2 | from collections import OrderedDict 3 | 4 | import wikipedia 5 | 6 | from qas.constants import CORPUS_DIR 7 | 8 | 9 | def search_wiki(keywords, number_of_search, wiki_pages): 10 | suggestion = False 11 | 12 | for word in range(0, len(keywords) - 1): 13 | # print(keywords[word], ">>") 14 | result_set = wikipedia.search(keywords[word], number_of_search, suggestion) 15 | for term in result_set: 16 | 17 | try: 18 | page = wikipedia.page(term, preload=False) 19 | page_title = page.title 20 | # page_summary = page.summary 21 | page_content = page.content 22 | wiki_pages[page_title] = page_content 23 | 24 | except wikipedia.exceptions.DisambiguationError as error: 25 | pass 26 | except wikipedia.exceptions.PageError as error: 27 | pass 28 | # print(error.options) 29 | 30 | # print(page_title, len(page_content), type(page_content)) 31 | 32 | return wiki_pages 33 | 34 | 35 | def fetch_wiki(keywords, number_of_search): 36 | 37 | wiki_pages = OrderedDict() 38 | 39 | search_wiki(keywords, number_of_search, wiki_pages) 40 | 41 | # print(wiki_pages) 42 | 43 | with open(os.path.join(CORPUS_DIR, 'know_corp_raw.txt'), 'w') as fp: 44 | for src_doc in wiki_pages.values(): 45 | split_wiki_docs = [src_doc] 46 | fp.write(str(split_wiki_docs) + "\n") 47 | 48 | return wiki_pages 49 | -------------------------------------------------------------------------------- /qas/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/model/__init__.py -------------------------------------------------------------------------------- /qas/model/es_document.py: -------------------------------------------------------------------------------- 1 | 2 | from qas.esstore.es_config import __wiki_content__, __wiki_content_info__, __wiki_content_table__, \ 3 | __wiki_raw__, __wiki_title__, __wiki_pageid__, __wiki_revision__, __wiki_updated_date__ 4 | 5 | """ 6 | Created by felix on 24/3/18 at 10:26 PM 7 | """ 8 | 9 | 10 | class ElasticSearchDocument: 11 | 12 | _source = None 13 | 14 | def __init__(self, article_id, source, score=0): 15 | self._source = dict() 16 | self._source[__wiki_pageid__] = article_id 17 | self._source['score'] = score 18 | self._source[__wiki_revision__] = source[__wiki_revision__] 19 | self._source[__wiki_updated_date__] = source[__wiki_updated_date__] 20 | self._source[__wiki_raw__] = source[__wiki_raw__] 21 | self._source[__wiki_title__] = source[__wiki_title__] 22 | self._source[__wiki_content__] = source[__wiki_content__] 23 | self._source[__wiki_content_info__] = source[__wiki_content_info__] 24 | self._source[__wiki_content_table__] = source[__wiki_content_table__] 25 | 26 | def get_wiki_revision(self): 27 | return self._source[__wiki_revision__] 28 | 29 | def get_wiki_article_id(self): 30 | return self._source[__wiki_pageid__] 31 | 32 | def get_wiki_updated_date(self): 33 | return self._source[__wiki_updated_date__] 34 | 35 | def get_wiki_raw_text(self): 36 | return self._source[__wiki_raw__] 37 | 38 | def get_wiki_title(self): 39 | return self._source[__wiki_title__] 40 | 41 | def get_wiki_content(self): 42 | return self._source[__wiki_content__] 43 | 44 | def get_wiki_content_info(self): 45 | return self._source[__wiki_content_info__] 46 | 47 | def get_wiki_content_table(self): 48 | return self._source[__wiki_content_table__] -------------------------------------------------------------------------------- /qas/model/query_container.py: -------------------------------------------------------------------------------- 1 | 2 | class QueryContainer: 3 | 4 | """ 5 | This is class is created to help map the query to elasticsearch _search API 6 | [0] - Features 7 | [1] - Conjunctions (nested list with the conjunct and coordinating conjunction) 8 | [2] - Negations 9 | [3] - Markers 10 | """ 11 | 12 | __constructed_query__ = [None] * 4 13 | coordinating_conjuncts = [] 14 | 15 | def __init__(self, ip_query=None): 16 | if ip_query is not None and len(ip_query) == 4: 17 | self.__constructed_query__ = ip_query 18 | 19 | def add_features(self, feature_list): 20 | self.__constructed_query__[0] = feature_list 21 | 22 | def add_conjunctions(self, conjunction_list): 23 | self.__constructed_query__[1] = conjunction_list 24 | 25 | def add_coordinating_conjunct(self, c_conjunct): 26 | self.coordinating_conjuncts.append(c_conjunct) 27 | 28 | def add_negations(self, negation_list): 29 | self.__constructed_query__[2] = negation_list 30 | 31 | def add_markers(self, marker_list): 32 | self.__constructed_query__[3] = marker_list 33 | 34 | def get_constructed_qery(self): 35 | return self.__constructed_query__ 36 | 37 | def get_features(self): 38 | return self.__constructed_query__[0] 39 | 40 | def get_conjunctions(self): 41 | return self.__constructed_query__[1] 42 | 43 | def get_negations(self): 44 | return self.__constructed_query__[2] 45 | 46 | def get_markers(self): 47 | return self.__constructed_query__[3] 48 | 49 | def __repr__(self): 50 | return "{Features: "+str(self.__constructed_query__[0]) + " ," \ 51 | "Conjunction: "+str(self.__constructed_query__[1]) + " ," \ 52 | "Negations: "+str(self.__constructed_query__[2]) + " ,"\ 53 | "Marker: "+str(self.__constructed_query__[3]) + "}" 54 | -------------------------------------------------------------------------------- /qas/qa_init.py: -------------------------------------------------------------------------------- 1 | import re 2 | import warnings 3 | from time import time 4 | 5 | import enchant 6 | import numpy as np 7 | import spacy 8 | from autocorrect import spell 9 | from classifier.question_classifier import classify_question 10 | 11 | from qas.candidate_ans import get_candidate_answers 12 | from qas.constants import EXAMPLE_QUESTIONS 13 | from qas.doc_scorer import rank_docs 14 | from qas.feature_extractor import extract_features 15 | from qas.fetch_wiki import fetch_wiki 16 | from qas.query_const import construct_query 17 | 18 | """ 19 | This script is Deprecated 20 | """ 21 | 22 | 23 | def answer_question(input_question): 24 | warnings.warn("This method is now deprecated.", DeprecationWarning) 25 | 26 | en_nlp = spacy.load('en_core_web_md') 27 | 28 | en_doc = en_nlp(u'' + input_question) 29 | 30 | question_class = classify_question(en_doc) 31 | print("Class:", question_class) 32 | 33 | question_keywords = extract_features(question_class, en_doc) 34 | print("Question Features:", question_keywords) 35 | 36 | question_query = construct_query(question_keywords, en_doc) 37 | print("Question Query:", question_query) 38 | 39 | print("Fetching Knowledge source...") 40 | wiki_pages = fetch_wiki(question_keywords, number_of_search=3) 41 | print("Pages Fetched:", len(wiki_pages)) 42 | 43 | # Anaphora Resolution 44 | 45 | ranked_wiki_docs = rank_docs(question_keywords) 46 | print("Ranked Pages:", ranked_wiki_docs) 47 | 48 | candidate_answers, split_keywords = get_candidate_answers(question_query, ranked_wiki_docs, en_nlp) 49 | print("Candidate Answer:", "(" + str(len(candidate_answers)) + ")", candidate_answers) 50 | 51 | print("Answer:", " ".join(candidate_answers)) 52 | 53 | answer = " ".join(candidate_answers) 54 | 55 | return answer 56 | 57 | 58 | def spell_check(input_question): 59 | 60 | pattern = "\w" 61 | prog = re.compile(pattern) 62 | 63 | input_question_word_list = input_question.split() 64 | en_dict = enchant.Dict("en_US") 65 | for word_index in input_question_word_list: 66 | if (not en_dict.check(input_question_word_list[word_index]) and 67 | prog.match(input_question_word_list[word_index]) is None): 68 | correct_word = spell(input_question_word_list[word_index]) 69 | input_question_word_list[word_index] = correct_word 70 | return " ".join(input_question_word_list) 71 | 72 | 73 | if __name__ == '__main__': 74 | 75 | q = EXAMPLE_QUESTIONS[np.random.randint(len(EXAMPLE_QUESTIONS))] 76 | q = spell_check(q) 77 | print("Question:", q) 78 | 79 | start_time = time() 80 | 81 | answer_output = answer_question(q) 82 | 83 | end_time = time() 84 | print("Total time :", end_time - start_time) 85 | -------------------------------------------------------------------------------- /qas/query_const.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from qas.model.query_container import QueryContainer 4 | ''' 5 | The Query is constructed just to show relationship amongst different features in the feature set. 6 | A conjunction is a part of speech that is used to connect words, phrases, clauses, or sentences. 7 | ''' 8 | 9 | """ 10 | Refer http://universaldependencies.org/u/dep/ for dependency labels. 11 | More in-depth at https://nlp.stanford.edu/software/dependencies_manual.pdf 12 | """ 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | def get_detail(sentence): 18 | logger.debug("Word\tLemma\tTag\tEntity\tDependency\tHead") 19 | for token in sentence: 20 | logger.debug("{0}\t{1}\t{2}\t{3}\t{4}\t{5}".format( 21 | token.text, token.lemma_, token.tag_, token.ent_type_, token.dep_, token.head)) 22 | 23 | 24 | def get_conjuncts(token): 25 | 26 | """ 27 | A conjunct is the relation between two elements connected by a coordinating conjunction, such as and, or, etc. 28 | We treat conjunctions asymmetrically: The head of the relation is the first conjunct and all the other conjuncts 29 | depend on it via the conj relation. 30 | 31 | Coordinating Conjunction: and, or, but, yet, so, nor, for. 32 | Correlative Conjunctions: either...or, whether...or, not only...but also 33 | """ 34 | 35 | parent = token.head 36 | conj = [parent.text] 37 | 38 | for child in parent.children: 39 | if child.dep_ == "conj": 40 | conj.append(child.text) 41 | 42 | logger.debug("Conjuncting: {0}".format(conj)) 43 | return conj 44 | 45 | 46 | def get_query(sentence, feature_list): 47 | 48 | """ 49 | This function sequentially adds the query components to the structured query. 50 | """ 51 | 52 | query_container = QueryContainer() 53 | query_container.add_features(feature_list) 54 | 55 | conjunct_list = [] 56 | neg_list = [] 57 | mark_list = [] 58 | 59 | for token in sentence: 60 | 61 | # cc: A cc is the relation between a conjunct and a preceding coordinating conjunction. 62 | if token.dep_ == "cc": 63 | logger.debug("Conjunction: `{0}` at {1}".format(token.text, token.i)) 64 | conjunct_list.append(get_conjuncts(token)) 65 | conjunct_list.append(token.text) 66 | query_container.add_coordinating_conjunct(token.text) 67 | 68 | # neg: The negation modifier is the relation between a negation word and the word it modifies. 69 | if token.dep_ == "neg": 70 | if token.i > token.head.i: 71 | neg_list.append([token.text, token.head.text]) 72 | logger.debug("Negation: `{0}` at `{1}`".format(token.text, token.head.text)) 73 | else: 74 | neg_list.append([token.head.text, token.text]) 75 | logger.debug("Negation: `{0}` at `{1}`".format(token.text, token.head.text)) 76 | 77 | # mark: A marker is the word introducing a finite clause subordinate to another clause. 78 | if token.dep_ == "mark": 79 | if token.i > token.head.i: 80 | mark_list.append([token.text, token.head.text]) 81 | logger.debug("Mark: `{0}` at `{1}`".format(token.text, token.head.text)) 82 | else: 83 | mark_list.append([token.head.text, token.text]) 84 | logger.debug("Mark: `{0}` at `{1}`".format(token.text, token.head.text)) 85 | 86 | query_container.add_conjunctions(conjunct_list) 87 | query_container.add_negations(neg_list) 88 | query_container.add_markers(mark_list) 89 | 90 | return query_container 91 | 92 | 93 | def construct_query(features_list, en_doc): 94 | query_constructed_obj = [] 95 | 96 | for sentence in en_doc.sents: 97 | query_constructed_obj.append(get_query(sentence, features_list)) 98 | 99 | return query_constructed_obj 100 | 101 | 102 | if __name__ == "__main__": 103 | 104 | import spacy 105 | from constants import EN_MODEL_MD 106 | 107 | logging.basicConfig(level=logging.DEBUG) 108 | question = "What are Cushman or Wakefield known for ?" 109 | features = ['Cushman', 'known', 'Wakefield', 'are'] 110 | 111 | en_nlp = spacy.load(EN_MODEL_MD) 112 | en_doc = en_nlp(u'' + question) 113 | 114 | query = [] 115 | 116 | for sent in en_doc.sents: 117 | get_detail(sent) 118 | query.append(get_query(sent, features)) 119 | logger.info("Query: {0}".format(repr(query))) 120 | -------------------------------------------------------------------------------- /qas/search_source.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from wiki.wiki_fetch import WikiFetch 4 | from wiki.wiki_parse import XPathExtractor 5 | from wiki.wiki_query import WikiQuery 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | class SearchSources: 11 | 12 | source_type = "wiki" 13 | search_keywords = [] 14 | max_page_per_search = 10 15 | 16 | def __init__(self, search_keywords, source_type, max_page_per_search): 17 | self.search_keywords = search_keywords 18 | self.source_type = source_type 19 | self.max_page_per_search = max_page_per_search 20 | 21 | def query_source(self): 22 | if self.source_type == "wiki": 23 | for keyword in self.search_keywords: 24 | logger.info("Searching:{0}".format(keyword)) 25 | wikiq = WikiQuery(keyword, self.max_page_per_search) 26 | wiki_page_ids = wikiq.fetch_wiki_pages() 27 | wikif = WikiFetch(wiki_page_ids) 28 | wikif.parse_wiki_page() 29 | for page in wiki_page_ids: 30 | xpe = XPathExtractor(page) 31 | xpe.strip_tag() 32 | xpe.strip_headings() 33 | # extracted_img = xpe.img_extract() 34 | # extracted_info = xpe.extract_info() 35 | # extracted_table = xpe.extract_tables() 36 | # extracted_text = xpe.extract_text() 37 | else: 38 | print("Source not supported") 39 | 40 | 41 | if __name__ == "__main__": 42 | logging.basicConfig(level=logging.INFO) 43 | search = ['albert einstein', 'birth'] 44 | sr = SearchSources(search, "wiki", 3) 45 | sr.query_source() -------------------------------------------------------------------------------- /qas/sqlitestore/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import logging 4 | 5 | """ 6 | Created by felix on 8/3/18 at 1:39 AM 7 | """ 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | if __name__ == "__main__": 12 | 13 | logging.basicConfig(level=logging.DEBUG) 14 | 15 | if len(sys.argv) > 1: 16 | arguments = sys.argv 17 | 18 | else: 19 | raise ValueError('Missing Arguments') -------------------------------------------------------------------------------- /qas/sqlitestore/sqlt_connect.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | import sqlite3 4 | 5 | from qas.corpus.data import QA_TEST_DATA 6 | from qas.constants import CORPUS_DIR 7 | 8 | """ 9 | Created by felix on 8/3/18 at 1:40 AM 10 | """ 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | class SqLiteMeta(type): 16 | _instances = {} 17 | 18 | def __call__(cls, *args, **kwargs): 19 | if cls not in cls._instances: 20 | cls._instances[cls] = super(SqLiteMeta, cls).__call__(*args, **kwargs) 21 | return cls._instances[cls] 22 | 23 | 24 | class SqLiteManager(metaclass=SqLiteMeta): 25 | 26 | __test_db__ = CORPUS_DIR + "/" + QA_TEST_DATA 27 | __sqlt_conn__ = None 28 | sqlt_cursor = None 29 | table_name = "wikiqa" 30 | 31 | def __init__(self, db_name=__test_db__): 32 | self.__sqlt_conn__ = sqlite3.connect(db_name) 33 | self.create_table() 34 | 35 | def get_db_cursor(self): 36 | if self.sqlt_cursor is None: 37 | self.sqlt_cursor = self.__sqlt_conn__.cursor() 38 | return self.sqlt_cursor 39 | 40 | def commit_db(self): 41 | self.__sqlt_conn__.commit() 42 | 43 | def close_db(self): 44 | # Since here the connection is a singleton, closing the db will close the db but will not delete the object. 45 | self.__sqlt_conn__.close() 46 | 47 | def create_table(self): 48 | create_query = """CREATE TABLE IF NOT EXISTS """+self.table_name+""" ( 49 | Qid integer PRIMARY KEY, 50 | Question text, 51 | Class text, 52 | Features text, 53 | Query text, 54 | Pages text, 55 | Ranks text, 56 | Answer text) 57 | """ 58 | self.get_db_cursor().execute(create_query) 59 | self.commit_db() 60 | 61 | def insert_many_question(self, question_set): 62 | insert_many_query = """INSERT INTO """+self.table_name+""" 63 | (Question) VALUES (?)""" 64 | self.get_db_cursor().executemany(insert_many_query, question_set) 65 | self.commit_db() 66 | 67 | def get_question_count(self): 68 | count_questions_query = """SELECT COUNT(*) FROM """+self.table_name 69 | self.get_db_cursor().execute(count_questions_query) 70 | result = self.get_db_cursor().fetchone() 71 | return result[0] 72 | 73 | def get_all_questions(self, limit=0): 74 | if limit > 0: 75 | fetch_all_question = """SELECT * FROM """+self.table_name+""" LIMIT """+str(limit) 76 | else: 77 | fetch_all_question = """SELECT * FROM """+self.table_name 78 | self.get_db_cursor().execute(fetch_all_question) 79 | return self.get_db_cursor().fetchall() 80 | 81 | def get_random_questions(self, limit=0): 82 | if limit > 0: 83 | fetch_all_question = """SELECT * FROM """+self.table_name+""" ORDER BY RANDOM() LIMIT """+str(limit) 84 | else: 85 | fetch_all_question = """SELECT * FROM """+self.table_name+""" ORDER BY RANDOM()""" 86 | self.get_db_cursor().execute(fetch_all_question) 87 | return self.get_db_cursor().fetchall() 88 | 89 | def get_questions_between(self, start, end): 90 | fetch_range_question = """SELECT * FROM """+self.table_name+""" WHERE Qid BETWEEN """+str(start)+""" AND """+str(end) 91 | self.get_db_cursor().execute(fetch_range_question) 92 | return self.get_db_cursor().fetchall() 93 | 94 | def update_feature(self, qid, features): 95 | update_feature = """UPDATE """+self.table_name+""" SET Features = ? WHERE Qid = """+str(qid) 96 | self.get_db_cursor().execute(update_feature, (features,)) 97 | self.commit_db() 98 | 99 | def update_search_query(self, qid, query): 100 | update_feature = """UPDATE """+self.table_name+""" SET Query = ? WHERE Qid = """+str(qid) 101 | self.get_db_cursor().execute(update_feature, (query,)) 102 | self.commit_db() 103 | 104 | def remove_all_data(self): 105 | delete_all = """DELETE FROM """+self.table_name 106 | self.get_db_cursor().execute(delete_all) 107 | self.commit_db() 108 | 109 | def remove_old_results(self): 110 | update_many_query = """UPDATE """+self.table_name+""" 111 | SET Class = ?, Features = ?, Query = ?, Pages = ?, Ranks = ?, Answer = ? 112 | WHERE (Class IS NOT NULL OR Features IS NOT NULL OR Query IS NOT NULL OR Pages IS NOT NULL 113 | OR Ranks IS NOT NULL OR Answer IS NOT NULL)""" 114 | self.get_db_cursor().execute(update_many_query, (None, None, None, None, None, None)) 115 | self.commit_db() 116 | 117 | 118 | if __name__ == "__main__": 119 | 120 | logging.basicConfig(level=logging.DEBUG) 121 | 122 | if len(sys.argv) > 1: 123 | arguments = sys.argv 124 | 125 | else: 126 | raise ValueError('Missing Arguments') -------------------------------------------------------------------------------- /qas/sys_info.py: -------------------------------------------------------------------------------- 1 | import platform 2 | import elasticsearch 3 | 4 | from qas.esstore.es_connect import ElasticSearchConn 5 | 6 | 7 | def get_system_info(): 8 | print("System:", platform.system()) 9 | print("Platform:", platform.version()) 10 | print("Python:", platform.python_version()) 11 | print("Elasticsearch:", str(elasticsearch.__version__)) 12 | print("Elasticsearch Mapping: ", ElasticSearchConn().get_index_mapping()) 13 | 14 | 15 | if __name__ == "__main__": 16 | get_system_info() -------------------------------------------------------------------------------- /qas/wiki/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/qas/wiki/__init__.py -------------------------------------------------------------------------------- /qas/wiki/wiki_fetch.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import sys 3 | import logging 4 | from lxml import etree 5 | 6 | from qas.constants import OUTPUT_DIR, SAVE_OUTPUTS 7 | from qas.esstore.es_operate import ElasticSearchOperate 8 | """ 9 | https://en.wikipedia.org/w/api.php [EndPoint] [User-Agent header] 10 | > format:json 11 | > action:parse 12 | 13 | pageid: Parse the content of this page. Overrides page. 14 | 15 | prop:text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties|parsewarnings 16 | 17 | eg: https://en.wikipedia.org/w/api.php?action=parse&pageid=16283969 18 | doc: https://en.wikipedia.org/w/api.php?action=help&modules=parse 19 | 20 | """ 21 | 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | class WikiFetch: 26 | 27 | base_url = 'https://en.wikipedia.org/w/api.php' 28 | # noinspection PyDictCreation 29 | wiki_query_payload = {'action': 'parse', 'format': 'json'} 30 | wiki_query_payload['prop'] = 'text|links|images|externallinks|sections|revid|displaytitle|iwlinks' 31 | es_ops = None 32 | page_list = [] 33 | wiki_text = [] 34 | 35 | def __init__(self, page_list): 36 | self.page_list = page_list 37 | self.es_ops = ElasticSearchOperate() 38 | 39 | def parse_wiki_page(self): 40 | 41 | for page in self.page_list: 42 | 43 | self.wiki_query_payload['pageid'] = page 44 | 45 | wiki_query_req = requests.get(self.base_url, params=self.wiki_query_payload) 46 | wiki_query_response = wiki_query_req.json() 47 | wiki_revid = wiki_query_response.get('parse').get('revid') 48 | wiki_title = wiki_query_response.get('parse').get('title') 49 | wiki_html_text = wiki_query_response.get('parse').get('text').get('*') 50 | 51 | res = self.es_ops.upsert_wiki_article_if_updated(page, wiki_revid, wiki_title, wiki_html_text) 52 | if res: 53 | logger.info("Wiki article {0} inserted.".format(page)) 54 | else: 55 | logger.error("Wiki article insertion failed") 56 | 57 | self.wiki_text.append(wiki_html_text) 58 | return self.wiki_text 59 | 60 | @staticmethod 61 | def save_html(content, page): 62 | parser = etree.XMLParser(ns_clean=True, remove_comments=True) 63 | html_tree = etree.fromstring(content, parser) 64 | html_str = etree.tostring(html_tree, pretty_print=True) 65 | with open(OUTPUT_DIR + '/wiki_content_'+str(page)+'.html', 'wb') as fp: 66 | fp.write(html_str) 67 | 68 | 69 | if __name__ == "__main__": 70 | logging.basicConfig(level=logging.DEBUG) 71 | if len(sys.argv) > 1: 72 | parse_pageId = sys.argv[1:] 73 | wikif = WikiFetch(parse_pageId) 74 | html_text = wikif.parse_wiki_page() 75 | 76 | if SAVE_OUTPUTS: 77 | for pageId, text in zip(parse_pageId, html_text): 78 | WikiFetch.save_html(text, pageId) 79 | 80 | else: 81 | raise ValueError('No page id provided for Wiki parse') 82 | -------------------------------------------------------------------------------- /qas/wiki/wiki_parse.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import re 4 | import sys 5 | from pprint import pprint 6 | 7 | from lxml import etree 8 | 9 | from qas.constants import OUTPUT_DIR, SAVE_OUTPUTS 10 | from qas.esstore.es_config import __wiki_raw__ 11 | from qas.esstore.es_operate import ElasticSearchOperate 12 | 13 | """ 14 | Parsing with XPath 1.0 query 15 | XPath Documentation : https://developer.mozilla.org/en-US/docs/Web/XPath 16 | 17 | The '.' at the beginning means, that the current processing starts at the current node. 18 | Your xpath starts with a slash '/' and is therefore absolute. 19 | The '*' selects all element nodes descending from this current node with the @id-attribute-value or @class value'. 20 | The '//' identifies any descendant designation element of element 21 | """ 22 | 23 | logger = logging.getLogger(__name__) 24 | 25 | 26 | class XPathExtractor: 27 | 28 | regex_expressions = "http://exslt.org/regular-expressions" 29 | non_break_space = u'\xa0' 30 | new_line_non_break_regex = r'(\n+)|(\xa0)' 31 | 32 | toc_pattern = '''//*[@id="toc"]''' 33 | non_searchable_pattern = '''/html/body/div/div[starts-with(@class, "hatnote")]''' 34 | description_list_pattern = '''/html/body/div/dl''' 35 | references_pattern = '''/html/body/div/div[starts-with(@class, "refbegin")]''' 36 | references_list_pattern = '''/html/body/div/div[starts-with(@class, "reflist")]''' 37 | meta_data_box_pattern = '''/html/body/div/div[starts-with(@class, "metadata")]''' 38 | nav_boxes_pattern = '''/html/body/div/div[@class="navbox"]''' 39 | vertical_nav_boxes_pattern = '''/html/body/div/table[starts-with(@class, "vertical-navbox")]''' 40 | no_print_metadata_pattern = '''/html/body/div/div[starts-with(@class, "noprint")]''' 41 | subscript_pattern = '''//sup[@class="reference"]''' 42 | edit_pattern = '''//span[@class="mw-editsection"]''' 43 | meta_data_table = '''/html/body/div/table[contains(@class, "metadata")]''' 44 | 45 | see_also_pattern = '''//*[@id="See_also"]''' 46 | external_links_pattern = '''//*[@id="External_links"]''' 47 | 48 | img_pattern = '''/html/body/div//div[starts-with(@class, "thumb ")]''' 49 | img_href = '''./div//a/@href''' 50 | img_caption = '''.//div[@class="thumbcaption"]/text()''' 51 | 52 | info_box_pattern = '''/html/body/div/table[starts-with(@class, "infobox")]''' 53 | info_box_item = '''./tr''' 54 | info_key_pattern = '''./th//text()''' 55 | info_value_pattern = '''./td//text()''' 56 | 57 | table_pattern = '''/html/body/div/table[@class="wikitable"]''' 58 | table_row_pattern = '''./tr''' 59 | table_key_pattern = '''./th''' 60 | table_value_pattern = '''./td''' 61 | all_text_pattern = '''.//text()''' 62 | 63 | irrelevant_headlines = ['''//*[@id="See_also"]''', '''//*[@id="Notes_and_references"]''', 64 | '''//*[@id="Explanatory_notes"]''', '''//*[@id="Citations"]''', 65 | '''//*[@id="Further_reading"]''', '''//*[@id="External_links"]''', 66 | '''//*[@id="References"]'''] 67 | 68 | html_data = '' 69 | extracted_img = {} 70 | html_tree = None 71 | is_file = False 72 | page_id = None 73 | es_ops = None 74 | new_line_non_break_pattern = None 75 | 76 | def __init__(self, html_data, is_file): 77 | self.es_ops = ElasticSearchOperate() 78 | self.html_data = html_data 79 | self.new_line_non_break_pattern = re.compile(self.new_line_non_break_regex) 80 | parser = etree.HTMLParser(remove_blank_text=True, remove_comments=True) 81 | if is_file: 82 | self.html_tree = etree.parse(self.html_data, parser) 83 | else: 84 | self.html_tree = etree.fromstring(self.html_data, parser) 85 | 86 | def __init__(self, pageid): 87 | self.page_id = pageid 88 | self.new_line_non_break_pattern = re.compile(self.new_line_non_break_regex) 89 | self.es_ops = ElasticSearchOperate() 90 | wiki_data = self.es_ops.get_wiki_article(pageid) 91 | if wiki_data is not None and __wiki_raw__ in wiki_data: 92 | self.html_data = wiki_data[__wiki_raw__] 93 | parser = etree.HTMLParser(remove_blank_text=True, remove_comments=True) 94 | self.html_tree = etree.fromstring(self.html_data, parser) 95 | 96 | def strip_tag(self): 97 | 98 | toc_list = self.html_tree.xpath(self.toc_pattern) 99 | for toc in toc_list: 100 | toc.getparent().remove(toc) 101 | 102 | non_searchable_list = self.html_tree.xpath(self.non_searchable_pattern) 103 | for non_searchable in non_searchable_list: 104 | non_searchable.getparent().remove(non_searchable) 105 | 106 | dl_list = self.html_tree.xpath(self.description_list_pattern) 107 | for dl in dl_list: 108 | dl.getparent().remove(dl) 109 | 110 | ref_begin_list = self.html_tree.xpath(self.references_pattern) 111 | for ref_begin in ref_begin_list: 112 | ref_begin.getparent().remove(ref_begin) 113 | 114 | ref_list = self.html_tree.xpath(self.references_list_pattern) 115 | for ref in ref_list: 116 | ref.getparent().remove(ref) 117 | 118 | meta_data_list = self.html_tree.xpath(self.meta_data_box_pattern) 119 | for meta_data in meta_data_list: 120 | meta_data.getparent().remove(meta_data) 121 | 122 | meta_data_table = self.html_tree.xpath(self.meta_data_table) 123 | for meta_data in meta_data_table: 124 | meta_data.getparent().remove(meta_data) 125 | 126 | nav_box_list = self.html_tree.xpath(self.nav_boxes_pattern) 127 | for nav_box in nav_box_list: 128 | nav_box.getparent().remove(nav_box) 129 | 130 | vnav_box_list = self.html_tree.xpath(self.vertical_nav_boxes_pattern) 131 | for vnav_box in vnav_box_list: 132 | vnav_box.getparent().remove(vnav_box) 133 | 134 | no_print_list = self.html_tree.xpath(self.no_print_metadata_pattern) 135 | for no_print in no_print_list: 136 | no_print.getparent().remove(no_print) 137 | 138 | sub_ref_list = self.html_tree.xpath(self.subscript_pattern) 139 | for sub_ref in sub_ref_list: 140 | sub_ref.getparent().remove(sub_ref) 141 | 142 | edit_list = self.html_tree.xpath(self.edit_pattern) 143 | for edit in edit_list: 144 | edit.getparent().remove(edit) 145 | 146 | see_also_list = self.html_tree.xpath(self.see_also_pattern) 147 | for see_also in see_also_list: 148 | see_also_data = see_also.getparent().getnext() 149 | see_also_data.getparent().remove(see_also_data) 150 | 151 | external_link_list = self.html_tree.xpath(self.external_links_pattern) 152 | for external_link in external_link_list: 153 | external_link_data = external_link.getparent().getnext() 154 | external_link_data.getparent().remove(external_link_data) 155 | 156 | def strip_headings(self): 157 | for heading in self.irrelevant_headlines: 158 | heading_parent_list = self.html_tree.xpath(heading) 159 | if len(heading_parent_list) > 0: 160 | heading_parent = heading_parent_list[0].getparent() 161 | heading_parent.getparent().remove(heading_parent) 162 | 163 | def img_extract(self): 164 | img_list = self.html_tree.xpath(self.img_pattern) 165 | for img in img_list: 166 | img_url, img_caption = "", "" 167 | img_url_list = img.xpath(self.img_href) 168 | if len(img_url_list) > 0: 169 | img_url = str(img_url_list[0]) 170 | img_caption_list = img.xpath(self.img_caption) 171 | if len(img_caption_list) > 0: 172 | img_caption = ''.join(img_caption_list).strip() 173 | img.getparent().remove(img) 174 | if img_url != "": 175 | self.extracted_img[img_url] = img_caption 176 | logger.debug("Extracted Images: %d", len(self.extracted_img)) 177 | return self.extracted_img 178 | 179 | def extract_info(self): 180 | info_box = self.html_tree.xpath(self.info_box_pattern) 181 | wiki_info = WikiInfo() 182 | for info in info_box: 183 | info_key = info.xpath(self.info_box_item) 184 | info_list = [] 185 | info_title = "" 186 | for ikey in info_key: 187 | info_key = ''.join(ikey.xpath(self.info_key_pattern)).strip() # issues with   // https://stackoverflow.com/a/33829869/8646414 188 | info_value = ''.join(ikey.xpath(self.info_value_pattern)).strip() 189 | info_value = info_value.split('\n') 190 | info_value = [item.strip() for item in info_value] 191 | if info_key != "" and len(info_value) >= 1: 192 | if info_title == "": 193 | info_title = info_key 194 | if info_value[0] != '': 195 | info_pair = {info_key: info_value} 196 | info_list.append(info_pair) 197 | wiki_info.add_info(info_title, info_list) 198 | info.getparent().remove(info) 199 | res = self.es_ops.update_wiki_article(self.page_id, content_info=json.dumps(wiki_info.info_data)) 200 | if res: 201 | logger.info("Inserted parsed content info for: %d", self.page_id) 202 | else: 203 | logger.error("Inserted of parsed content info failed") 204 | logger.debug("Extracted Bios: %d", len(wiki_info.info_data)) 205 | return wiki_info.info_data 206 | 207 | def extract_tables(self): 208 | table_list = self.html_tree.xpath(self.table_pattern) 209 | wikit = WikiTable() 210 | for table in table_list: 211 | table_row_list = table.xpath(self.table_row_pattern) 212 | for table_row in table_row_list: 213 | table_head_list = table_row.xpath(self.table_key_pattern) 214 | for table_head in table_head_list: 215 | wikit.add_header(''.join(table_head.xpath(self.all_text_pattern))) 216 | tab_data = [] 217 | table_data_list = table_row.xpath(self.table_value_pattern) 218 | for table_data in table_data_list: 219 | tab_data.append(''.join(table_data.xpath(self.all_text_pattern))) 220 | wikit.set_values(tab_data) 221 | table.getparent().remove(table) 222 | res = self.es_ops.update_wiki_article(self.page_id, content_table=json.dumps(wikit.tab_data)) 223 | if res: 224 | logger.info("Inserted parsed content table for: %d", self.page_id) 225 | else: 226 | logger.error("Inserted of parsed content table failed") 227 | logger.debug("Extracted Tables: %d", len(wikit.tab_data)) 228 | return wikit.tab_data 229 | 230 | def extract_text(self): 231 | text_data = ''.join(self.html_tree.xpath(self.all_text_pattern)).strip() 232 | text_data = re.sub(self.new_line_non_break_pattern, ' ', text_data) 233 | res = self.es_ops.update_wiki_article(self.page_id, content=text_data) 234 | logger.debug("Parsed content length: %d", len(text_data)) 235 | if res: 236 | logger.info("Inserted parsed content for: %d", self.page_id) 237 | else: 238 | logger.error("Inserted of parsed content failed") 239 | return text_data 240 | 241 | def save_html(self, page=0): 242 | html_str = etree.tostring(self.html_tree, pretty_print=True) 243 | with open(OUTPUT_DIR+'/wiki_content_cleaned_'+str(page)+'.html', 'wb') as fp: 244 | fp.write(html_str) 245 | 246 | 247 | class WikiInfo: 248 | info_data = [] 249 | 250 | def add_info(self, key, value): 251 | info_tuple = (key, value) 252 | self.info_data.append(info_tuple) 253 | 254 | 255 | class WikiTable: 256 | description = "" 257 | tab_header = [] 258 | tab_data = [] 259 | 260 | def add_header(self, tab_header): 261 | self.tab_header.append(tab_header) 262 | 263 | def set_values(self, tab_values): 264 | zipped_list = list(zip(self.tab_header, tab_values)) 265 | if len(zipped_list) > 0: 266 | self.tab_data.append(zipped_list) 267 | 268 | 269 | def extract_wiki_pages(wiki_page_ids): 270 | for page in wiki_page_ids: 271 | xpe = XPathExtractor(page) 272 | xpe.strip_tag() 273 | xpe.strip_headings() 274 | # xpe.img_extract() # TODO: Save with Elasticsearch 275 | xpe.extract_info() # TODO: Save with Elasticsearch 276 | xpe.extract_tables() # TODO: Save with Elasticsearch 277 | xpe.extract_text() 278 | 279 | 280 | if __name__ == "__main__": 281 | logging.basicConfig(level=logging.DEBUG) 282 | if len(sys.argv) > 1: 283 | parse_pageId = sys.argv[1:] 284 | for lpage in parse_pageId: 285 | lxpe = XPathExtractor(lpage) 286 | lxpe.strip_tag() 287 | lxpe.strip_headings() 288 | print("Extracted Images:", lxpe.img_extract()) 289 | pprint([str(item) for item in lxpe.extract_info()]) 290 | pprint(lxpe.extract_tables()) 291 | print(lxpe.extract_text()) 292 | if SAVE_OUTPUTS: 293 | lxpe.save_html(lpage) 294 | else: 295 | raise ValueError('No page id provided for Wiki parse') -------------------------------------------------------------------------------- /qas/wiki/wiki_query.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import urllib.parse 3 | import sys 4 | import logging 5 | 6 | """ 7 | https://en.wikipedia.org/w/api.php [EndPoint] [User-Agent header] 8 | > format:json 9 | > action:query 10 | 11 | list:search 12 | 13 | srsearch: Search for all page titles (or content) that have this value. 14 | srwhat: Search inside the text or titles. 15 | srlimit: How many total pages to return. No more than 50 (500 for bots) allowed. (Default: 10) 16 | 17 | prop: 18 | 19 | eg: https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Albert%20Einstein 20 | eg: https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=wikipedia&srwhat=text 21 | doc: https://en.wikipedia.org/w/api.php?action=help&modules=query 22 | """ 23 | 24 | logger = logging.getLogger(__name__) 25 | 26 | 27 | class WikiQuery: 28 | 29 | base_url = 'https://en.wikipedia.org/w/api.php' 30 | wiki_max_results = 10 31 | 32 | # noinspection PyDictCreation 33 | wiki_query_payload = {'action': 'query', 'format': 'json', 'list': 'search'} 34 | wiki_query_payload['srwhat'] = 'text' 35 | search_term = "" 36 | 37 | def __init__(self, search_term, wiki_max_results=10): 38 | self.search_term = search_term 39 | self.wiki_max_results = wiki_max_results 40 | 41 | def fetch_wiki_pages(self): 42 | 43 | search_term = urllib.parse.quote(self.search_term) 44 | logger.debug("Querying: %s", search_term) 45 | 46 | self.wiki_query_payload['srlimit'] = str(self.wiki_max_results) 47 | self.wiki_query_payload['srsearch'] = search_term 48 | 49 | wiki_query_req = requests.get(self.base_url, params=self.wiki_query_payload) 50 | wiki_query_response = wiki_query_req.json() 51 | 52 | if 'errors' not in wiki_query_response: 53 | wiki_page_list = wiki_query_response.get('query').get('search') 54 | pages_list = [pages.get('pageid') for pages in wiki_page_list] 55 | logger.info("Fetched %d : %s", len(pages_list), str(pages_list)) 56 | return pages_list 57 | 58 | else: 59 | logger.error(wiki_query_req.text) 60 | return None 61 | 62 | 63 | if __name__ == "__main__": 64 | logging.basicConfig(level=logging.DEBUG) 65 | if len(sys.argv) > 1: 66 | search_term_cmd = " ".join(sys.argv[1:]) 67 | wikiq = WikiQuery(search_term_cmd) 68 | print(wikiq.fetch_wiki_pages()) 69 | 70 | else: 71 | raise ValueError('No search term provided for Wiki query') 72 | -------------------------------------------------------------------------------- /qas/wiki/wiki_search.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | 4 | from qas.wiki.wiki_query import WikiQuery 5 | from qas.wiki.wiki_fetch import WikiFetch 6 | from qas.wiki.wiki_parse import extract_wiki_pages 7 | 8 | """ 9 | Created by felix on 24/3/18 at 10:55 PM 10 | """ 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def search_wikipedia(search_term_list, max_results): 16 | 17 | for search_term in search_term_list: 18 | wikiq = WikiQuery(search_term, max_results) 19 | wiki_page_ids = wikiq.fetch_wiki_pages() 20 | 21 | wikif = WikiFetch(wiki_page_ids) 22 | wikif.parse_wiki_page() 23 | 24 | extract_wiki_pages(wiki_page_ids) 25 | 26 | 27 | if __name__ == "__main__": 28 | 29 | logging.basicConfig(level=logging.DEBUG) 30 | 31 | if len(sys.argv) > 1: 32 | arguments = sys.argv 33 | search_wikipedia(arguments, 3) 34 | 35 | else: 36 | raise ValueError('Missing Arguments') -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | # Add requirements only needed for your unittests and during development here. 2 | # They will be installed automatically when running `python setup.py test`. 3 | # ATTENTION: Don't remove pytest-cov and pytest as they are needed. 4 | pytest-cov==2.5.0 5 | pytest==4.6.3 6 | codecov==2.0.15 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | elasticsearch==7.0.2 2 | gensim==3.7.3 3 | lxml==4.3.4 4 | pandas==0.24.2 5 | requests==2.22.0 6 | spaCy==2.1.4 7 | scikit-learn==0.21.2 8 | dill==0.2.9 9 | joblib==0.13.2 10 | 11 | ############## spaCy language models ################ 12 | 13 | https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.1.0/en_core_web_sm-2.1.0.tar.gz 14 | https://github.com/explosion/spacy-models/releases/download/en_core_web_md-2.1.0/en_core_web_md-2.1.0.tar.gz -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = qas 3 | version = 0.1.dev 4 | summary = Adam - A question answering system 5 | author = Shirish Kadam 6 | author-email = shirishkadam35@gmail.com 7 | license = GNU General Public License v3 (GPLv3) 8 | home-page = https://shirishkadam.com 9 | description-file = README.rst 10 | doc_files = docs/ 11 | examples/ 12 | # Add here all kinds of additional classifiers as defined under 13 | # https://pypi.python.org/pypi?%3Aaction=list_classifiers 14 | classifier = 15 | Development Status :: 3 - Alpha 16 | Programming Language :: Python 17 | Topic :: Scientific/Engineering :: Natural Language Processing 18 | 19 | [entry_points] 20 | # Add here console scripts like: 21 | # console_scripts = 22 | # script_name = qas.module:function 23 | # For example: 24 | # console_scripts = 25 | # fibonacci = qas.skeleton:run 26 | # as well as other entry_points. 27 | 28 | 29 | [files] 30 | # Add here 'data_files', 'packages' or 'namespace_packages'. 31 | # Additional data files are defined as key value pairs of target directory 32 | # and source location from the root of the repository: 33 | packages = 34 | qas 35 | # data_files = 36 | # share/qas_docs = docs/* 37 | 38 | [extras] 39 | # Add here additional requirements for extra features, like: 40 | # PDF = 41 | # ReportLab>=1.2 42 | # RXP 43 | 44 | [test] 45 | # py.test options when running `python setup.py test` 46 | addopts = tests 47 | 48 | [tool:pytest] 49 | # Options for py.test: 50 | # Specify command line options as you would do when invoking py.test directly. 51 | # e.g. --cov-report html (or xml) for html/xml output or --junitxml junit.xml 52 | # in order to write a coverage file that can be read by Jenkins. 53 | addopts = 54 | --cov qas --cov-report term-missing 55 | --verbose 56 | 57 | [devpi:upload] 58 | # Options for the devpi: PyPI server and packaging tool 59 | # VCS export must be deactivated since we are using setuptools-scm 60 | no-vcs = 1 61 | formats = bdist_wheel 62 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Setup file for qas. 5 | """ 6 | 7 | import contextlib 8 | import io 9 | import os 10 | import sys 11 | 12 | from setuptools import setup, find_packages 13 | 14 | 15 | @contextlib.contextmanager 16 | def chdir(new_dir): 17 | old_dir = os.getcwd() 18 | try: 19 | os.chdir(new_dir) 20 | sys.path.insert(0, new_dir) 21 | yield 22 | finally: 23 | del sys.path[0] 24 | os.chdir(old_dir) 25 | 26 | 27 | def setup_package(): 28 | 29 | base_dir = os.path.abspath(os.path.dirname(__file__)) 30 | 31 | with chdir(base_dir): 32 | with io.open(os.path.join(base_dir, 'qas', 'about.py'), encoding='utf8') as fp: 33 | about = {} 34 | exec(fp.read(), about) 35 | 36 | with io.open(os.path.join(base_dir, 'README.rst'), encoding='utf8') as f: 37 | readme = f.read() 38 | 39 | setup(name=about['__title__'], 40 | packages=find_packages(), 41 | description=about['__summary__'], 42 | long_description=readme, 43 | version=about['__version__'], 44 | author=about['__author__'], 45 | author_email=about['__email__'], 46 | url=about['__uri__'], 47 | license=about['__license__'], 48 | # TODO change the signs from '>=' to '==' like we did on adam_qas/requirements.txt 49 | install_requires=[ 50 | "autocorrect>=0.3.0", 51 | "gensim>=3.0.1", 52 | "lxml>=4.1.0", 53 | "pandas>=0.21", 54 | "pyenchant>=2.0.0", 55 | "requests>=2.18.0", 56 | "spaCy>=2.0.3", 57 | "scikit-learn>=v0.19.1", 58 | "wikipedia>=1.4.0"] 59 | ) 60 | 61 | 62 | if __name__ == "__main__": 63 | setup_package() 64 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/adam_qas/c5d4f472836ef8caf84756182c2a398d583ed5b8/tests/__init__.py -------------------------------------------------------------------------------- /tests/create_test_data.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import csv 3 | 4 | from qas.constants import CORPUS_DIR 5 | from qas.corpus.data import WIKI_QA_TSV 6 | from qas.sqlitestore.sqlt_connect import SqLiteManager 7 | 8 | """ 9 | Created by felix on 11/3/18 at 5:50 PM 10 | """ 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | # Dataset from WikiQA.tsv. Beware this file is of type TSV 16 | # Warning: This will remove old results and give you a fresh start. 17 | 18 | def insert_question_to_sqlt(): 19 | question_set = [] 20 | last_question = "" 21 | with open(CORPUS_DIR+"/"+WIKI_QA_TSV) as file: 22 | wiki_file = csv.DictReader(file, dialect='excel-tab') 23 | if wiki_file is not None: 24 | for row in wiki_file: 25 | if row['Question'] != last_question: 26 | question = (row['Question'], ) 27 | question_set.append(question) 28 | last_question = row['Question'] 29 | 30 | if question_set is not None: 31 | sqlt_man = SqLiteManager() 32 | # sqlt_man.remove_old_results() 33 | sqlt_man.remove_all_data() 34 | logger.info("Removed Old test results") 35 | sqlt_man.insert_many_question(question_set) 36 | logger.info("Inserted {0} questions".format(sqlt_man.get_question_count())) 37 | 38 | 39 | if __name__ == "__main__": 40 | 41 | logging.basicConfig(level=logging.DEBUG) 42 | 43 | insert_question_to_sqlt() -------------------------------------------------------------------------------- /tests/test_classify_question.py: -------------------------------------------------------------------------------- 1 | import os 2 | from unittest import TestCase 3 | 4 | import pandas 5 | from sklearn.model_selection import cross_val_score 6 | from sklearn.model_selection import train_test_split 7 | 8 | from qas.classifier.question_classifier import classify_question 9 | from qas.constants import CORPUS_DIR 10 | from qas.corpus.data import QUESTION_CLASSIFICATION_TRAINING_DATA 11 | 12 | 13 | class TestClassifyQuestion(TestCase): 14 | 15 | classification_score = 0.60 16 | 17 | def test_classify_question(self): 18 | training_data_path = os.path.join(CORPUS_DIR, QUESTION_CLASSIFICATION_TRAINING_DATA) 19 | df_question = pandas.read_csv(training_data_path, sep='|', header=0) 20 | df_question_train, df_question_test = train_test_split(df_question, test_size=0.2, random_state=42) 21 | 22 | predicted_class, clf, df_question_train_label, df_question_train = \ 23 | classify_question(df_question_train=df_question_train, df_question_test=df_question_test) 24 | 25 | scores = cross_val_score(clf, df_question_train, df_question_train_label) 26 | 27 | print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) 28 | print("SD:", scores.std()) 29 | 30 | assert scores.mean() > self.classification_score 31 | -------------------------------------------------------------------------------- /tests/test_construct_query.py: -------------------------------------------------------------------------------- 1 | import json 2 | from unittest import TestCase 3 | 4 | import spacy 5 | 6 | from qas.constants import EN_MODEL_MD 7 | from qas.query_const import construct_query 8 | from qas.sqlitestore.sqlt_connect import SqLiteManager 9 | 10 | """ 11 | Created by felix on 11/3/18 at 10:57 PM 12 | """ 13 | 14 | 15 | class TestConstructQuery(TestCase): 16 | 17 | def test_construct_query(self): 18 | sql_man = SqLiteManager() 19 | en_nlp_l = spacy.load(EN_MODEL_MD) 20 | 21 | result = sql_man.get_questions_between(5, 7) 22 | 23 | for row in result: 24 | qid = row[0] 25 | with self.subTest(qid): 26 | question = row[1] 27 | question_type = row[2] 28 | question_feat = json.loads(row[3]) 29 | 30 | if question_feat is not None: 31 | 32 | en_doc = en_nlp_l(u'' + question) 33 | 34 | query = construct_query(question_feat, en_doc) 35 | print("{0}){1} :\nQuery: {2}".format(qid, question, repr(query))) 36 | js_query = json.dumps(repr(query)) 37 | sql_man.update_search_query(qid, js_query) 38 | assert query is not None 39 | # sql_man.close_db() 40 | -------------------------------------------------------------------------------- /tests/test_extract_features.py: -------------------------------------------------------------------------------- 1 | import json 2 | from unittest import TestCase 3 | 4 | import spacy 5 | 6 | from qas.constants import EN_MODEL_MD 7 | from qas.feature_extractor import extract_features 8 | from qas.sqlitestore.sqlt_connect import SqLiteManager 9 | 10 | """ 11 | Created by felix on 11/3/18 at 7:21 PM 12 | """ 13 | 14 | 15 | class TestExtractFeatures(TestCase): 16 | 17 | def test_extract_features(self): 18 | sql_man = SqLiteManager() 19 | en_nlp_l = spacy.load(EN_MODEL_MD) 20 | 21 | result = sql_man.get_questions_between(5, 7) 22 | 23 | for row in result: 24 | qid = row[0] 25 | with self.subTest(qid): 26 | question = row[1] 27 | question_type = row[2] 28 | 29 | en_doc = en_nlp_l(u'' + question) 30 | 31 | features = extract_features(question_type, en_doc, True) 32 | print("{0}){1} :\nExtracted: {2}".format(qid, question, features)) 33 | js_feat = json.dumps(features) 34 | sql_man.update_feature(qid, js_feat) 35 | assert features is not None 36 | # sql_man.close_db() 37 | -------------------------------------------------------------------------------- /tests/test_wiki_scraper.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | from qas.wiki.wiki_query import WikiQuery 3 | from qas.wiki.wiki_fetch import WikiFetch 4 | from qas.wiki.wiki_parse import XPathExtractor 5 | 6 | from qas.esstore.es_operate import ElasticSearchOperate 7 | from qas.esstore.es_config import __wiki_title__, __wiki_raw__, __wiki_revision__ 8 | 9 | 10 | class TestWikiScraper(TestCase): 11 | 12 | es_ops = None 13 | page_list = [] 14 | 15 | def __init__(self, *args, **kwargs): 16 | super(TestWikiScraper, self).__init__(*args, **kwargs) 17 | self.es_ops = ElasticSearchOperate() 18 | 19 | def test_query_wiki_pages(self): 20 | html_tag_expr = '<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)' 21 | 22 | query_set = ["Alan Turing", "Harry Potter and the Deathly Hallows", "Tiger", "Melbourne"] 23 | 24 | for query in query_set: 25 | wikiq = WikiQuery(query) 26 | self.page_list = wikiq.fetch_wiki_pages() 27 | assert len(self.page_list) == wikiq.wiki_max_results 28 | 29 | with self.subTest(query): 30 | wikif = WikiFetch(self.page_list) 31 | wikif.parse_wiki_page() 32 | 33 | for pageid in self.page_list: 34 | with self.subTest(pageid): 35 | wiki_data = self.es_ops.get_wiki_article(pageid) 36 | assert wiki_data is not None 37 | assert wiki_data[__wiki_title__] 38 | assert wiki_data[__wiki_raw__] 39 | assert wiki_data[__wiki_revision__] 40 | 41 | for page in self.page_list: 42 | with self.subTest(page): 43 | xpe = XPathExtractor(page) 44 | xpe.strip_tag() 45 | xpe.strip_headings() 46 | img = xpe.img_extract() 47 | info = xpe.extract_info() 48 | table = xpe.extract_tables() 49 | text = xpe.extract_text() 50 | self.assertNotRegex(text, html_tag_expr) 51 | 52 | -------------------------------------------------------------------------------- /tests/travis_install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This script is meant to be called by the "install" step defined in 3 | # .travis.yml. See http://docs.travis-ci.com/ for more details. 4 | # The behavior of the script is controlled by environment variabled defined 5 | # in the .travis.yml in the top level folder of the project. 6 | # 7 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # Tox configuration file 2 | # Read more under https://tox.readthedocs.org/ 3 | 4 | [tox] 5 | minversion = 1.8 6 | envlist = py35 7 | skip_missing_interpreters = True 8 | 9 | [testenv] 10 | changedir = tests 11 | commands = 12 | py.test {posargs} 13 | deps = 14 | pytest 15 | -r{toxinidir}/requirements.txt 16 | 17 | 18 | --------------------------------------------------------------------------------