├── .gitignore ├── LICENSE ├── README.md ├── blacklist.txt ├── configuration.cfg ├── data └── .gitkeep ├── interface ├── server.py └── templates │ └── index.html ├── lib ├── setup.py └── wikifil.pl ├── model.png ├── model1.png ├── models └── .gitkeep ├── reports ├── report-review-1.pdf └── report-review-2.pdf ├── requirements.txt └── src ├── __init__.py ├── data ├── cornell │ ├── __init__.py │ ├── filter.py │ ├── make_pairs.py │ └── pull.py └── opus11 │ ├── filter.py │ ├── make_pairs.py │ └── pull.py ├── model ├── experiments.py ├── models.py ├── sample.py ├── sampling.py ├── sequence_blocks.py └── train.py └── utils ├── __init__.py ├── batch_utils.py ├── config_utils.py └── data_utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | models/*.h5 3 | models/*/*.h5 4 | data/processed/* 5 | data/raw/* 6 | data/*/*.txt 7 | venv -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Neural-Chatbot 2 | 3 | A Neural Network based Chatbot 4 | 5 | 6 | Inspired by "A Neural Conversational Model". 7 | 8 | ## Documentation 9 | 10 | 1. [Report 1](./reports/report-review-1.pdf) 11 | 2. [Report 2](./reports/report-review-2.pdf) 12 | 3. [Presentation](https://github.com/saurabhmathur96/presentations/blob/master/Mini-Project/review-1.pdf) 13 | 14 | 15 | ## Getting Started 16 | 17 | 1. Create virtualenv `virtualenv venv` 18 | 2. Install Dependencies `pip install -r requirements.txt` 19 | 3. Setup nltk and directories `python lib/setup.py` 20 | 21 | ## Data Preprocessing 22 | 23 | 0. Verify configurations in `configuration.cfg` 24 | 1. Fetch data `python src/data/opus11/pull.py` 25 | 2. Clean data `python src/data/opus11/make_pairs.py` 26 | 3. Prepare for training `python src/data/opus11/filter.py` 27 | 28 | ## Training 29 | 30 | Train model `python src/model/train.py` 31 | 32 | ## Sampling & interface 33 | 34 | Still working on this. 35 | 36 | 37 | ## Model Architecture 38 | 39 | ![](./model.png) 40 | -------------------------------------------------------------------------------- /blacklist.txt: -------------------------------------------------------------------------------- 1 | 2g1c 2 | 2 girls 1 cup 3 | acrotomophilia 4 | alabama hot pocket 5 | alaskan pipeline 6 | anal 7 | anilingus 8 | anus 9 | apeshit 10 | arsehole 11 | ass 12 | asshole 13 | assmunch 14 | auto erotic 15 | autoerotic 16 | babeland 17 | baby batter 18 | baby juice 19 | ball gag 20 | ball gravy 21 | ball kicking 22 | ball licking 23 | ball sack 24 | ball sucking 25 | bangbros 26 | bareback 27 | barely legal 28 | barenaked 29 | bastard 30 | bastardo 31 | bastinado 32 | bbw 33 | bdsm 34 | beaner 35 | beaners 36 | beaver cleaver 37 | beaver lips 38 | bestiality 39 | big black 40 | big breasts 41 | big knockers 42 | big tits 43 | bimbos 44 | birdlock 45 | bitch 46 | bitches 47 | black cock 48 | blonde action 49 | blonde on blonde action 50 | blowjob 51 | blow job 52 | blow your load 53 | blue waffle 54 | blumpkin 55 | bollocks 56 | bondage 57 | boner 58 | boob 59 | boobs 60 | booty call 61 | brown showers 62 | brunette action 63 | bukkake 64 | bulldyke 65 | bullet vibe 66 | bullshit 67 | bung hole 68 | bunghole 69 | busty 70 | butt 71 | buttcheeks 72 | butthole 73 | camel toe 74 | camgirl 75 | camslut 76 | camwhore 77 | carpet muncher 78 | carpetmuncher 79 | chocolate rosebuds 80 | circlejerk 81 | cleveland steamer 82 | clit 83 | clitoris 84 | clover clamps 85 | clusterfuck 86 | cock 87 | cocks 88 | coprolagnia 89 | coprophilia 90 | cornhole 91 | coon 92 | coons 93 | creampie 94 | cum 95 | cumming 96 | cunnilingus 97 | cunt 98 | darkie 99 | date rape 100 | daterape 101 | deep throat 102 | deepthroat 103 | dendrophilia 104 | dick 105 | dildo 106 | dingleberry 107 | dingleberries 108 | dirty pillows 109 | dirty sanchez 110 | doggie style 111 | doggiestyle 112 | doggy style 113 | doggystyle 114 | dog style 115 | dolcett 116 | domination 117 | dominatrix 118 | dommes 119 | donkey punch 120 | double dong 121 | double penetration 122 | dp action 123 | dry hump 124 | dvda 125 | eat my ass 126 | ecchi 127 | ejaculation 128 | erotic 129 | erotism 130 | escort 131 | eunuch 132 | faggot 133 | fecal 134 | felch 135 | fellatio 136 | feltch 137 | female squirting 138 | femdom 139 | figging 140 | fingerbang 141 | fingering 142 | fisting 143 | foot fetish 144 | footjob 145 | frotting 146 | fuck 147 | fuck buttons 148 | fuckin 149 | fucking 150 | fucktards 151 | fudge packer 152 | fudgepacker 153 | futanari 154 | gang bang 155 | gay sex 156 | genitals 157 | giant cock 158 | girl on 159 | girl on top 160 | girls gone wild 161 | goatcx 162 | goatse 163 | god damn 164 | gokkun 165 | golden shower 166 | goodpoop 167 | goo girl 168 | goregasm 169 | grope 170 | group sex 171 | g-spot 172 | guro 173 | hand job 174 | handjob 175 | hard core 176 | hardcore 177 | hentai 178 | homoerotic 179 | honkey 180 | hooker 181 | hot carl 182 | hot chick 183 | how to kill 184 | how to murder 185 | huge fat 186 | humping 187 | incest 188 | intercourse 189 | jack off 190 | jail bait 191 | jailbait 192 | jelly donut 193 | jerk off 194 | jigaboo 195 | jiggaboo 196 | jiggerboo 197 | jizz 198 | juggs 199 | kike 200 | kinbaku 201 | kinkster 202 | kinky 203 | knobbing 204 | leather restraint 205 | leather straight jacket 206 | lemon party 207 | lolita 208 | lovemaking 209 | make me come 210 | male squirting 211 | masturbate 212 | menage a trois 213 | milf 214 | missionary position 215 | motherfucker 216 | mound of venus 217 | mr hands 218 | muff diver 219 | muffdiving 220 | nambla 221 | nawashi 222 | negro 223 | neonazi 224 | nigga 225 | nigger 226 | nig nog 227 | nimphomania 228 | nipple 229 | nipples 230 | nsfw images 231 | nude 232 | nudity 233 | nympho 234 | nymphomania 235 | octopussy 236 | omorashi 237 | one cup two girls 238 | one guy one jar 239 | orgasm 240 | orgy 241 | paedophile 242 | paki 243 | panties 244 | panty 245 | pedobear 246 | pedophile 247 | pegging 248 | penis 249 | phone sex 250 | piece of shit 251 | pissing 252 | piss pig 253 | pisspig 254 | playboy 255 | pleasure chest 256 | pole smoker 257 | ponyplay 258 | poof 259 | poon 260 | poontang 261 | punany 262 | poop chute 263 | poopchute 264 | porn 265 | porno 266 | pornography 267 | prince albert piercing 268 | pthc 269 | pubes 270 | pussy 271 | queaf 272 | queef 273 | quim 274 | raghead 275 | raging boner 276 | rape 277 | raping 278 | rapist 279 | rectum 280 | reverse cowgirl 281 | rimjob 282 | rimming 283 | rosy palm 284 | rosy palm and her 5 sisters 285 | rusty trombone 286 | sadism 287 | santorum 288 | scat 289 | schlong 290 | scissoring 291 | semen 292 | sex 293 | sexo 294 | sexy 295 | shaved beaver 296 | shaved pussy 297 | shemale 298 | shibari 299 | shit 300 | shitblimp 301 | shitty 302 | shota 303 | shrimping 304 | skeet 305 | slanteye 306 | slut 307 | s&m 308 | smut 309 | snatch 310 | snowballing 311 | sodomize 312 | sodomy 313 | spic 314 | splooge 315 | splooge moose 316 | spooge 317 | spread legs 318 | spunk 319 | strap on 320 | strapon 321 | strappado 322 | strip club 323 | style doggy 324 | suck 325 | sucks 326 | suicide girls 327 | sultry women 328 | swastika 329 | swinger 330 | tainted love 331 | taste my 332 | tea bagging 333 | threesome 334 | throating 335 | tied up 336 | tight white 337 | tit 338 | tits 339 | titties 340 | titty 341 | tongue in a 342 | topless 343 | tosser 344 | towelhead 345 | tranny 346 | tribadism 347 | tub girl 348 | tubgirl 349 | tushy 350 | twat 351 | twink 352 | twinkie 353 | two girls one cup 354 | undressing 355 | upskirt 356 | urethra play 357 | urophilia 358 | vagina 359 | venus mound 360 | vibrator 361 | violet wand 362 | vorarephilia 363 | voyeur 364 | vulva 365 | wank 366 | wetback 367 | wet dream 368 | white power 369 | wrapping men 370 | wrinkled starfish 371 | xx 372 | xxx 373 | yaoi 374 | yellow showers 375 | yiffy 376 | zoophilia -------------------------------------------------------------------------------- /configuration.cfg: -------------------------------------------------------------------------------- 1 | [Training] 2 | batch_size=32 3 | n_iter=4096 4 | n_epoch=2 5 | 6 | [Model] 7 | sequence_length=8 8 | vocabulary_size=2048 9 | hidden_size=256 10 | weights_path=models/seq2seq_weights.h5 11 | 12 | [Data] 13 | blacklist_path=blacklist.txt 14 | pairs_path=data/processed/opus11/pairs.txt 15 | opus11_save_path=data/raw/opus11.tar.gz 16 | opus11_extract_dir=data/raw 17 | vocabulary_path=data/processed/opus11/vocabulary.txt 18 | filtered_path=data/processed/opus11/filtered_pairs.txt 19 | unk_ratio=.1 -------------------------------------------------------------------------------- /data/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/data/.gitkeep -------------------------------------------------------------------------------- /interface/server.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, jsonify 2 | from time import sleep 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/') 7 | def index_page(): 8 | return render_template('index.html') 9 | 10 | @app.route('/respond', methods=['POST']) 11 | def respond(): 12 | sleep(2) 13 | return jsonify({ 'response': 'i don\'t know' }) 14 | 15 | 16 | if __name__ == '__main__': 17 | app.run(port=8000) -------------------------------------------------------------------------------- /interface/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Chatbot 9 | 11 | 12 | 13 | 14 | 15 |
16 |
    17 |
18 | 19 |
20 | 21 | 22 |
23 | 24 |
25 | 26 | 27 | 28 | 30 | 79 | 80 | -------------------------------------------------------------------------------- /lib/setup.py: -------------------------------------------------------------------------------- 1 | import nltk 2 | import os 3 | from os import path 4 | 5 | 6 | if __name__ == '__main__': 7 | nltk.download('punkt') 8 | os.makedirs('data/raw') if not path.exists('data/raw') else None 9 | os.makedirs('data/processed/') if not path.exists('data/processed/') else None 10 | os.makedirs('data/processed/opus11') if not path.exists('data/processed/opus11') else None -------------------------------------------------------------------------------- /lib/wikifil.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | # Program to filter Wikipedia XML dumps to "clean" text consisting only of lowercase 4 | # letters (a-z, converted from A-Z), and spaces (never consecutive). 5 | # All other characters are converted to spaces. Only text which normally appears 6 | # in the web browser is displayed. Tables are removed. Image captions are 7 | # preserved. Links are converted to normal text. Digits are spelled out. 8 | 9 | # Written by Matt Mahoney, June 10, 2006. This program is released to the public domain. 10 | 11 | $/=">"; # input record separator 12 | while (<>) { 13 | if (/<\/s>/) {print "\n";} 14 | if (/ ... 15 | if (/#redirect/i) {$text=0;} # remove #REDIRECT 16 | if ($text) { 17 | 18 | # Remove any text not normally visible 19 | if (/<\/text>/) {$text=0;} 20 | s/<.*>//; # remove xml tags 21 | s/&/&/g; # decode URL encoded chars 22 | s/<//g; 24 | s///g; # remove references ... 25 | s/<[^>]*>//g; # remove xhtml tags 26 | s/\[http:[^] ]*/[/g; # remove normal url, preserve visible text 27 | s/\|thumb//ig; # remove images links, preserve caption 28 | s/\|left//ig; 29 | s/\|right//ig; 30 | s/\|\d+px//ig; 31 | s/\[\[image:[^\[\]]*\|//ig; 32 | s/\[\[category:([^|\]]*)[^]]*\]\]/[[$1]]/ig; # show categories without markup 33 | s/\[\[[a-z\-]*:[^\]]*\]\]//g; # remove links to other languages 34 | s/\[\[[^\|\]]*\|/[[/g; # remove wiki url, preserve visible text 35 | s/\{\{[^\}]*\}\}//g; # remove {{icons}} and {tables} 36 | s/\{[^\}]*\}//g; 37 | s/\[//g; # remove [ and ] 38 | s/\]//g; 39 | s/&[^;]*;/ /g; # remove URL encoded chars 40 | 41 | # convert to lowercase letters and spaces, spell digits 42 | $_=" $_ "; 43 | tr/A-Z/a-z/; 44 | s/0/ zero /g; 45 | s/1/ one /g; 46 | s/2/ two /g; 47 | s/3/ three /g; 48 | s/4/ four /g; 49 | s/5/ five /g; 50 | s/6/ six /g; 51 | s/7/ seven /g; 52 | s/8/ eight /g; 53 | s/9/ nine /g; 54 | tr/a-z.!?/ /cs; 55 | tr/.!? //s; 56 | chop; 57 | print $_; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/model.png -------------------------------------------------------------------------------- /model1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/model1.png -------------------------------------------------------------------------------- /models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/models/.gitkeep -------------------------------------------------------------------------------- /reports/report-review-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/reports/report-review-1.pdf -------------------------------------------------------------------------------- /reports/report-review-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/reports/report-review-2.pdf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.3 2 | click==6.7 3 | Flask==0.12 4 | funcsigs==1.0.2 5 | itsdangerous==0.24 6 | Jinja2==2.9.5 7 | Keras==2.0.2 8 | MarkupSafe==1.0 9 | mock==2.0.0 10 | nltk==3.2.2 11 | numpy==1.12.1 12 | packaging==16.8 13 | pbr==2.0.0 14 | pkg-resources==0.0.0 15 | protobuf==3.2.0 16 | pyparsing==2.2.0 17 | PyYAML==3.12 18 | requests==2.13.0 19 | scipy==0.19.0 20 | six==1.10.0 21 | tensorflow==1.0.1 22 | Theano==0.9.0 23 | tqdm==4.11.2 24 | Werkzeug==0.12.1 25 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/src/__init__.py -------------------------------------------------------------------------------- /src/data/cornell/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/src/data/cornell/__init__.py -------------------------------------------------------------------------------- /src/data/cornell/filter.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import zipfile 4 | import csv 5 | import json 6 | from tqdm import tqdm 7 | from itertools import chain 8 | from nltk import FreqDist 9 | 10 | sys.path.append('src/utils') 11 | from data_utils import PAD, START, END, UNK 12 | 13 | if __name__ == '__main__': 14 | data_file = 'data/processed/pairs.txt' 15 | print ('Reading {0}'.format(data_file)) 16 | with open(data_file) as handle: 17 | reader = csv.reader(handle) 18 | pairs = [(question.lower(), answer.lower()) for question, answer in reader] 19 | 20 | print ('Building Frequency Distribution') 21 | vocabulary_size = 8000 - 4 # pad, start, end, unk 22 | words = ' '.join(chain.from_iterable(pairs)).split() 23 | print ('Total {0} words'.format(len(words))) 24 | word_counts = FreqDist(words).most_common(vocabulary_size) 25 | vocabulary = [word for word, count in word_counts] 26 | 27 | length = 25 28 | vocabulary_set = set(vocabulary) 29 | def remove_unknown(line): 30 | return ' '.join(word if word in vocabulary_set else UNK for word in line.split()) 31 | 32 | def is_valid(line): 33 | words = line.split() 34 | return len(words) <= length and (words.count(UNK) / float(len(words))) < .2 35 | 36 | def mark_ends(line): 37 | return START + ' ' + line + ' ' + END 38 | 39 | pairs = [map(remove_unknown, pair) for pair in tqdm(pairs, desc='removing rare words')] 40 | pairs = [map(mark_ends, (question, answer)) for question, answer in tqdm(pairs, desc='filtering lines') if is_valid(question) and is_valid(answer)] 41 | 42 | vocabulary = [PAD, UNK, START, END] + vocabulary 43 | 44 | vocabulary_file = 'data/processed/vocabulary.txt' 45 | print ('Writing vocabulary to {0}'.format(vocabulary_file)) 46 | with open(vocabulary_file, 'w') as handle: 47 | json.dump(vocabulary, handle) 48 | 49 | filtered_file = 'data/processed/filtered_pairs.txt' 50 | print ('Writing filtered pairs to {0}'.format(filtered_file)) 51 | with open(filtered_file, 'w') as handle: 52 | writer = csv.writer(handle, quoting=csv.QUOTE_ALL) 53 | writer.writerows(pairs) 54 | -------------------------------------------------------------------------------- /src/data/cornell/make_pairs.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import zipfile 4 | import csv 5 | 6 | sys.path.append('src/utils') 7 | from data_utils import read_lines, make_pairs 8 | 9 | if __name__ == '__main__': 10 | movie_lines = 'data/raw/movie_lines.txt' 11 | lines = read_lines(movie_lines) 12 | 13 | movie_conversation = 'data/raw/movie_conversation.txt' 14 | pairs = make_pairs(movie_conversation, lines) 15 | 16 | data_file = 'data/processed/pairs.txt' 17 | with open(data_file, 'w') as handle: 18 | writer = csv.writer(handle, quoting=csv.QUOTE_ALL) 19 | writer.writerows(pairs) 20 | -------------------------------------------------------------------------------- /src/data/cornell/pull.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import zipfile 4 | 5 | sys.path.append('src/utils') 6 | from data_utils import download 7 | 8 | 9 | if __name__ == '__main__': 10 | url = 'http://www.mpi-sws.org/~cristian/data/cornell_movie_dialogs_corpus.zip' 11 | save_path = 'data/raw/cornell_movie_dialog_corpus.zip' 12 | # download(url, save_path) 13 | 14 | extract_path = 'data/raw' 15 | to_extract = [('cornell movie-dialogs corpus/movie_lines.txt', 'data/raw/movie_lines.txt'), 16 | ('cornell movie-dialogs corpus/movie_conversations.txt', 'data/raw/movie_conversation.txt')] 17 | with zipfile.ZipFile(save_path, 'r') as archive: 18 | for source, target in to_extract: 19 | contents = archive.read(source) 20 | with open(target, 'wb') as handle: 21 | handle.write(contents) 22 | 23 | # os.remove(save_path) -------------------------------------------------------------------------------- /src/data/opus11/filter.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import zipfile 4 | import csv 5 | import json 6 | from tqdm import tqdm 7 | from itertools import chain 8 | from nltk import FreqDist 9 | 10 | sys.path.append('src/utils') 11 | from data_utils import PAD, START, END, UNK 12 | from config_utils import settings 13 | 14 | if __name__ == '__main__': 15 | 16 | 17 | with open(settings.data.blacklist_path) as handle: 18 | blacklist = set(handle.read().split('\n')) 19 | 20 | data_file = settings.data.pairs_path 21 | print ('Reading {0}'.format(data_file)) 22 | with open(data_file) as handle: 23 | reader = csv.reader(handle) 24 | pairs = ((question, answer) for question, answer in reader if not any(w in question for w in blacklist) and not any(w in answer for w in blacklist)) 25 | 26 | print ('Building Frequency Distribution') 27 | vocabulary_size = settings.model.vocabulary_size - 4 # pad, start, end, unk 28 | freq_dist = FreqDist(chain.from_iterable(q.split() + a.split() for q, a in tqdm(pairs, total=3102698) )) 29 | 30 | print ('Total {0} unique words'.format(len(freq_dist))) 31 | word_counts = freq_dist.most_common(vocabulary_size) 32 | vocabulary = [word for word, count in word_counts] 33 | 34 | length = settings.model.sequence_length - 2 # start, end 35 | vocabulary_set = set(vocabulary) 36 | def remove_unknown(line): 37 | return ' '.join(word if word in vocabulary_set else UNK for word in line.split()) 38 | 39 | unk_ratio = settings.data.unk_ratio 40 | def is_valid(line): 41 | words = line.split() 42 | return len(words) <= length and (words.count(UNK) / float(len(words))) < unk_ratio 43 | 44 | def mark_ends(line): 45 | return START + ' ' + line + ' ' + END 46 | 47 | with open(data_file) as handle: 48 | reader = csv.reader(handle) 49 | pairs = ((question, answer) for question, answer in reader if not any(w in question for w in blacklist) and not any(w in answer for w in blacklist)) 50 | 51 | pairs = (map(remove_unknown, pair) for pair in tqdm(pairs, desc='removing rare words')) 52 | pairs = (map(mark_ends, (question, answer)) for question, answer in tqdm(pairs, desc='filtering lines') if is_valid(question) and is_valid(answer)) 53 | 54 | vocabulary = [PAD, UNK, START, END] + vocabulary 55 | 56 | vocabulary_file = settings.data.vocabulary_path 57 | print ('Writing vocabulary to {0}'.format(vocabulary_file)) 58 | with open(vocabulary_file, 'w') as handle: 59 | json.dump(vocabulary, handle) 60 | 61 | filtered_file = settings.data.filtered_path 62 | print ('Writing filtered pairs to {0}'.format(filtered_file)) 63 | with open(filtered_file, 'w') as handle: 64 | writer = csv.writer(handle, quoting=csv.QUOTE_ALL) 65 | writer.writerows(pairs) 66 | -------------------------------------------------------------------------------- /src/data/opus11/make_pairs.py: -------------------------------------------------------------------------------- 1 | import os 2 | from os import path 3 | import gzip 4 | from subprocess import PIPE, Popen 5 | from tqdm import tqdm 6 | import csv 7 | import re 8 | 9 | import sys 10 | sys.path.append('src/utils') 11 | from data_utils import augment 12 | from config_utils import settings 13 | 14 | 15 | def all_filenames(root): 16 | for each in os.listdir(root): 17 | each = path.join(root, each) 18 | if path.isfile(each): 19 | yield each 20 | elif path.isdir(each): 21 | for subpath in all_filenames(each): 22 | yield subpath 23 | 24 | if __name__ == '__main__': 25 | 26 | pairs_path = settings.data.pairs_path 27 | 28 | with open(pairs_path, 'w') as pairs_handle: 29 | writer = csv.writer(pairs_handle, quoting=csv.QUOTE_ALL) 30 | 31 | base_path = path.join(settings.data.extract_dir, 'OpenSubtitles', 'en') 32 | names = list(all_filenames(base_path)) 33 | for filepath in tqdm(names): 34 | try: 35 | with gzip.open(filepath) as handle: 36 | pipe = Popen(['perl', 'lib/wikifil.pl'], stdin=PIPE, stdout=PIPE) 37 | text, _ = pipe.communicate(handle.read()) 38 | lines = re.sub(r'([\.\?\!])[\.\?\! ]+', r'\1 ', text).strip().split('\n') 39 | 40 | 41 | lines = [line.strip() for line in lines] 42 | 43 | 44 | for question, answer in zip(lines[0::2], lines[1::2]): 45 | for q, a in augment([question, answer]): 46 | writer.writerow([q, a]) 47 | 48 | 49 | for question, answer in zip(lines[1::2], lines[2::2]): 50 | for q, a in augment([question, answer]): 51 | writer.writerow([q, a]) 52 | except IOError: 53 | pass 54 | # skip files that cause an error 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/data/opus11/pull.py: -------------------------------------------------------------------------------- 1 | import os 2 | from os import path 3 | import sys 4 | import tarfile 5 | 6 | sys.path.append('src/utils') 7 | from data_utils import download 8 | from config_utils import settings 9 | 10 | if __name__ == '__main__': 11 | 12 | url = 'http://opus.lingfil.uu.se/download.php?f=OpenSubtitles/en.tar.gz' 13 | save_path = settings.data.save_path 14 | download(url, save_path) 15 | 16 | extract_dir = settings.data.extract_dir 17 | with tarfile.open(save_path, 'r:gz') as f: 18 | f.extractall(extract_dir) 19 | 20 | os.remove(save_path) 21 | 22 | -------------------------------------------------------------------------------- /src/model/experiments.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import csv 3 | import json 4 | from itertools import count 5 | from tqdm import tqdm 6 | from models import seq2seq, seq2seq_attention 7 | from keras.optimizers import SGD, Adagrad, Adam 8 | 9 | sys.path.append('src/utils') 10 | from batch_utils import BatchIterator 11 | from config_utils import settings 12 | 13 | def questions_stream(filepath): 14 | while True: 15 | with open(filepath) as handle: 16 | reader = csv.reader(handle) 17 | yield next(reader)[0] 18 | 19 | def answers_stream(filepath): 20 | while True: 21 | with open(filepath) as handle: 22 | reader = csv.reader(handle) 23 | yield next(reader)[1] 24 | 25 | if __name__ == '__main__': 26 | vocabulary_file = settings.data.vocabulary_path 27 | with open(vocabulary_file) as handle: 28 | vocabulary = json.load(handle) 29 | 30 | batch_size = settings.train.batch_size 31 | n_iter = settings.train.n_iter # 16384 32 | n_epoch = settings.train.n_epoch 33 | 34 | 35 | 36 | 37 | experiment_no = 0 # can be 0 to 3 38 | 39 | 40 | 41 | data_file = settings.data.filtered_path 42 | questions = questions_stream(data_file) 43 | answers = answers_stream(data_file) 44 | 45 | sequence_length = settings.model.sequence_length 46 | vocabulary_size = settings.model.vocabulary_size 47 | hidden_size = settings.model.hidden_size 48 | print ('Creating model with configuration: {0}'.format(settings.model)) 49 | 50 | if experiment_no == 0: 51 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size, use_gru=False, bidirectional_decoder=False, use_elu=False) 52 | elif experiment_no == 1: 53 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size, use_gru=True, bidirectional_decoder=False, use_elu=False) 54 | elif experiment_no == 2: 55 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size, use_gru=True, bidirectional_decoder=True, use_elu=False) 56 | elif experiment_no == 3: 57 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size, use_gru=True, bidirectional_decoder=True, use_elu=True) 58 | else : 59 | print ('unknown experiment_no') 60 | 61 | print (model.summary()) 62 | 63 | print ('Initializing training with configuration: {0}'.format(settings.train)) 64 | iterator = BatchIterator(questions, answers, vocabulary, batch_size, sequence_length, one_hot_target=True, stream=True) 65 | # generator = (iterator.next_batch() for _ in count(start=0, step=1)) # infinite generator 66 | # model.fit_generator(generator, epochs=2, steps_per_epoch=n_iter * batch_size) 67 | # 68 | bar_format = '{n_fmt}/{total_fmt}|{bar}|ETA: {remaining} - {desc}' 69 | for epoch in range(n_epoch): 70 | print ('-' * 80) 71 | print ('Epoch {0}'.format(epoch)) 72 | print ('-' * 80) 73 | bar = tqdm(range(1, n_iter+1), total=n_iter, bar_format=bar_format, ncols=80) 74 | loss = 0.0 75 | losses = [] 76 | for i in bar: 77 | batch = iterator.next_batch() 78 | losses.append(float(model.train_on_batch(*batch))) 79 | loss += losses[-1] 80 | bar.set_description('loss: {0:.2f}'.format( float(loss)/i )) 81 | bar.refresh() 82 | 83 | losses_path = 'models/experiment_{0}_loss.txt'.format(experiment_no) 84 | print ('Saving training loss to {0}'.format(losses_path)) 85 | json.dump(losses, open(losses_path, 'w')) 86 | 87 | model_weights_path = 'models/experiment_{0}.h5'.format(experiment_no) 88 | print ('Saving model weights to {0}'.format(model_weights_path)) 89 | model.save_weights(model_weights_path) 90 | -------------------------------------------------------------------------------- /src/model/models.py: -------------------------------------------------------------------------------- 1 | from keras.models import Model 2 | from keras import backend as K 3 | from keras.layers import * 4 | from sequence_blocks import * 5 | from keras.optimizers import * 6 | 7 | def seq2seq(sequence_length, vocabulary_size, hidden_size, use_gru=True): 8 | 9 | # Input Block 10 | i = Input(shape=(sequence_length,)) 11 | x = Embedding(vocabulary_size, 128, mask_zero=True)(i) 12 | 13 | # Encoder Block 14 | x = Encoder(hidden_size, return_sequences=False, use_gru=use_gru)(x) 15 | x = Dropout(.5)(x) 16 | x = Encoder(hidden_size, return_sequences=False, use_gru=use_gru)(x) 17 | x = Dropout(.5)(x) 18 | 19 | x = Dense(hidden_size, activation='linear')(x) 20 | x = ELU()(x) 21 | x = RepeatVector(sequence_length)(x) 22 | 23 | # Decoder Block 24 | x = Decoder(hidden_size, return_sequences=True, use_gru=use_gru)(x) 25 | x = Dropout(.5)(x) 26 | x = Decoder(hidden_size, return_sequences=True, use_gru=use_gru)(x) 27 | x = Dropout(.5)(x) 28 | 29 | x = TimeDistributed(Dense(vocabulary_size, activation='softmax'))(x) 30 | 31 | model = Model(inputs=i, outputs=x) 32 | 33 | opt = Adam(lr=0.0001, clipvalue=1.) 34 | model.compile(optimizer=opt, loss='categorical_crossentropy') 35 | 36 | return model 37 | 38 | 39 | 40 | def seq2seq_attention(sequence_length, vocabulary_size, hidden_size, use_elu=True, use_gru=True, bidirectional_decoder=True): 41 | 42 | 43 | # Input Block 44 | i = Input(shape=(sequence_length,)) 45 | x = Embedding(vocabulary_size, 128, mask_zero=True)(i) 46 | 47 | 48 | # Encoder Block 49 | activation = ELU() if use_elu else Activation('tanh') 50 | x = Encoder(hidden_size, activation=activation, return_sequences=True, bidirectional=True, use_gru=use_gru)(x) 51 | x = Dropout(.5)(x) 52 | 53 | x = TimeDistributed(Dense(hidden_size, activation='linear'))(x) 54 | x = ELU()(x) 55 | attention = Maxpool(x) 56 | x = Dropout(.5)(x) 57 | 58 | # Decoder Block 59 | activation = ELU() if use_elu else Activation('tanh') 60 | x = AttentionDecoder(hidden_size, activation=activation, return_sequences=True, bidirectional=bidirectional_decoder, use_gru=use_gru)(x, attention) 61 | x = Dropout(.5)(x) 62 | 63 | 64 | x = TimeDistributed(Dense(vocabulary_size, activation='softmax'))(x) 65 | 66 | model = Model(inputs=i, outputs=x) 67 | 68 | opt = Adam(lr=0.0001, clipvalue=1.) 69 | model.compile(optimizer=opt, loss='categorical_crossentropy') 70 | 71 | return model 72 | 73 | -------------------------------------------------------------------------------- /src/model/sample.py: -------------------------------------------------------------------------------- 1 | from sampling import Sampler 2 | from models import seq2seq, seq2seq_attention 3 | import json 4 | 5 | 6 | import sys 7 | sys.path.append('src/utils') 8 | from config_utils import settings 9 | 10 | if __name__ == '__main__': 11 | sequence_length = settings.model.sequence_length 12 | vocabulary_size = settings.model.vocabulary_size 13 | hidden_size = settings.model.hidden_size 14 | print ('Creating model with configuration: {0}'.format(settings.model)) 15 | 16 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size) 17 | print ('Loading model weights from {0}'.format(settings.model.weights_path)) 18 | model.load_weights('models/seq2seq_weights.h5') 19 | 20 | vocabulary_file = settings.data.vocabulary_path 21 | with open(vocabulary_file, 'r') as handle: 22 | vocabulary = json.load(handle) 23 | 24 | sampler = Sampler(model, vocabulary, sequence_length) 25 | 26 | while True: 27 | question = raw_input('>>') 28 | response = sampler.respond(question, greedy=True) 29 | print (response) 30 | for t in (.7, .8, .9): 31 | response = sampler.respond(question, temperature=t) 32 | print (response) 33 | 34 | -------------------------------------------------------------------------------- /src/model/sampling.py: -------------------------------------------------------------------------------- 1 | from nltk import word_tokenize 2 | from keras.preprocessing.sequence import pad_sequences 3 | import numpy as np 4 | from numpy import random 5 | 6 | 7 | 8 | class Sampler(object): 9 | def __init__(self, model, vocabulary, sequence_length): 10 | self.model = model 11 | self.vocabulary = vocabulary 12 | self.sequence_length = sequence_length 13 | self.inverse_vocabulary = { word: i for i, word in enumerate(vocabulary) } 14 | 15 | def respond(self, input, temperature=1.0, greedy=False): 16 | input = pad_sequences([self._encode(input)], maxlen=self.sequence_length) 17 | print (input) 18 | output = self.model.predict(input)[0] 19 | print (output.shape) 20 | output[:, 1] = 0 21 | indices = [probability.argmax(axis=-1) for probability in output] if greedy \ 22 | else [self.sample(probability, temperature) for probability in output] 23 | 24 | return self._decode(indices) 25 | 26 | def sample(self, probabilities, temperature=1.0): 27 | probabilities = np.asarray(probabilities).astype("float64") 28 | probabilities = np.log(probabilities + 1e-8) / temperature 29 | e_probabilities = np.exp(probabilities) 30 | probabilities = e_probabilities / np.sum(e_probabilities) 31 | p = random.multinomial(1, probabilities, 1) 32 | return np.argmax(p) 33 | 34 | def _encode(self, statement): 35 | statement = '^ ' + statement.strip() + ' $' 36 | unk_id = self.inverse_vocabulary['unk'] 37 | return [self.inverse_vocabulary.get(word, unk_id) for word in word_tokenize(statement)] 38 | 39 | def _decode(self, indices): 40 | return ' '.join(self.vocabulary[i] for i in indices) -------------------------------------------------------------------------------- /src/model/sequence_blocks.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from keras import backend as K 4 | from keras.engine import InputSpec 5 | from keras.layers import LSTM, activations, Wrapper 6 | from keras.layers import Lambda, merge, GRU 7 | from keras.layers import ELU 8 | from keras.initializers import Zeros 9 | from keras.layers.merge import concatenate 10 | 11 | 12 | class AttentionWrapper(Wrapper): 13 | def __init__(self, layer, attention_vec, attn_activation='tanh', single_attention_param=False, **kwargs): 14 | assert isinstance(layer, LSTM) or isinstance(layer, GRU) 15 | super(AttentionWrapper, self).__init__(layer, **kwargs) 16 | self.supports_masking = True 17 | self.attention_vec = attention_vec 18 | self.attn_activation = activations.get(attn_activation) 19 | self.single_attention_param = single_attention_param 20 | 21 | def build(self, input_shape): 22 | assert len(input_shape) >= 3 23 | self.input_spec = [InputSpec(shape=input_shape)] 24 | 25 | if not self.layer.built: 26 | self.layer.build(input_shape) 27 | self.layer.built = True 28 | 29 | super(AttentionWrapper, self).build() 30 | 31 | if hasattr(self.attention_vec, '_keras_shape'): 32 | attention_dim = self.attention_vec._keras_shape[1] 33 | else: 34 | raise Exception( 35 | 'Layer could not be build: No information about expected input shape.') 36 | 37 | kernel_initializer = self.layer.kernel_initializer 38 | self.U_a = self.layer.add_weight((self.layer.units, self.layer.units), name='{}_U_a'.format( 39 | self.name), initializer=kernel_initializer) 40 | self.b_a = self.layer.add_weight( 41 | (self.layer.units,), name='{}_b_a'.format(self.name), initializer=Zeros()) 42 | 43 | self.U_m = self.layer.add_weight((attention_dim, self.layer.units), name='{}_U_m'.format( 44 | self.name), initializer=kernel_initializer) 45 | self.b_m = self.layer.add_weight( 46 | (self.layer.units,), name='{}_b_m'.format(self.name), initializer=Zeros()) 47 | 48 | if self.single_attention_param: 49 | self.U_s = self.layer.add_weight((self.layer.units, 1), name='{}_U_s'.format( 50 | self.name), initializer=kernel_initializer) 51 | self.b_s = self.layer.add_weight( 52 | (1,), name='{}_b_s'.format(self.name), initializer=Zeros()) 53 | else: 54 | self.U_s = self.layer.add_weight((self.layer.units, self.layer.units), name='{}_U_s'.format( 55 | self.name), initializer=kernel_initializer) 56 | self.b_s = self.layer.add_weight( 57 | (self.layer.units,), name='{}_b_s'.format(self.name), initializer=Zeros()) 58 | 59 | def compute_output_shape(self, input_shape): 60 | return self.layer.compute_output_shape(input_shape) 61 | 62 | def step(self, x, states): 63 | h, params = self.layer.step(x, states) 64 | attention = states[-1] 65 | 66 | m = self.attn_activation(K.dot(h, self.U_a) * attention + self.b_a) 67 | s = K.sigmoid(K.dot(m, self.U_s) + self.b_s) 68 | 69 | if self.single_attention_param: 70 | h = h * K.repeat_elements(s, self.layer.units, axis=1) 71 | else: 72 | h = h * s 73 | 74 | return h, params 75 | 76 | def get_constants(self, x): 77 | constants = self.layer.get_constants(x) 78 | constants.append(K.dot(self.attention_vec, self.U_m) + self.b_m) 79 | return constants 80 | 81 | def call(self, x, mask=None): 82 | # input shape: (nb_samples, time (padded with zeros), input_dim) 83 | # note that the .build() method of subclasses MUST define 84 | # self.input_spec with a complete input shape. 85 | input_shape = self.input_spec[0].shape 86 | if K._BACKEND == 'tensorflow': 87 | if not input_shape[1]: 88 | raise Exception('When using TensorFlow, you should define ' 89 | 'explicitly the number of timesteps of ' 90 | 'your sequences.\n' 91 | 'If your first layer is an Embedding, ' 92 | 'make sure to pass it an "input_length" ' 93 | 'argument. Otherwise, make sure ' 94 | 'the first layer has ' 95 | 'an "input_shape" or "batch_input_shape" ' 96 | 'argument, including the time axis. ' 97 | 'Found input shape at layer ' + self.name + 98 | ': ' + str(input_shape)) 99 | if self.layer.stateful: 100 | initial_states = self.layer.states 101 | else: 102 | initial_states = self.layer.get_initial_states(x) 103 | constants = self.get_constants(x) 104 | preprocessed_input = self.layer.preprocess_input(x) 105 | 106 | last_output, outputs, states = K.rnn(self.step, preprocessed_input, 107 | initial_states, 108 | go_backwards=self.layer.go_backwards, 109 | mask=mask, 110 | constants=constants, 111 | unroll=self.layer.unroll, 112 | input_length=input_shape[1]) 113 | if self.layer.stateful: 114 | self.updates = [] 115 | for i in range(len(states)): 116 | self.updates.append((self.layer.states[i], states[i])) 117 | 118 | if self.layer.return_sequences: 119 | return outputs 120 | else: 121 | return last_output 122 | 123 | 124 | Maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), 125 | output_shape=lambda x: (x[0], x[2])) 126 | Maxpool.supports_masking = True 127 | 128 | 129 | def Encoder(hidden_size, activation=None, return_sequences=True, bidirectional=False, use_gru=True): 130 | if activation is None: 131 | activation = ELU() 132 | if use_gru: 133 | def _encoder(x): 134 | if bidirectional: 135 | branch_1 = GRU(int(hidden_size/2), activation='linear', 136 | return_sequences=return_sequences, go_backwards=False)(x) 137 | branch_2 = GRU(int(hidden_size/2), activation='linear', 138 | return_sequences=return_sequences, go_backwards=True)(x) 139 | x = concatenate([branch_1, branch_2]) 140 | x = activation(x) 141 | return x 142 | else: 143 | x = GRU(hidden_size, activation='linear', 144 | return_sequences=return_sequences)(x) 145 | x = activation(x) 146 | return x 147 | else: 148 | def _encoder(x): 149 | if bidirectional: 150 | branch_1 = LSTM(int(hidden_size/2), activation='linear', 151 | return_sequences=return_sequences, go_backwards=False)(x) 152 | branch_2 = LSTM(int(hidden_size/2), activation='linear', 153 | return_sequences=return_sequences, go_backwards=True)(x) 154 | x = concatenate([branch_1, branch_2]) 155 | x = activation(x) 156 | return x 157 | else: 158 | x = LSTM(hidden_size, activation='linear', 159 | return_sequences=return_sequences)(x) 160 | x = activation(x) 161 | return x 162 | return _encoder 163 | 164 | 165 | def AttentionDecoder(hidden_size, activation=None, return_sequences=True, bidirectional=False, use_gru=True): 166 | if activation is None: 167 | activation = ELU() 168 | if use_gru: 169 | def _decoder(x, attention): 170 | if bidirectional: 171 | branch_1 = AttentionWrapper(GRU(int(hidden_size/2), activation='linear', return_sequences=return_sequences, 172 | go_backwards=False), attention, single_attention_param=True)(x) 173 | branch_2 = AttentionWrapper(GRU(int(hidden_size/2), activation='linear', return_sequences=return_sequences, 174 | go_backwards=True), attention, single_attention_param=True)(x) 175 | x = concatenate([branch_1, branch_2]) 176 | return activation(x) 177 | else: 178 | x = AttentionWrapper(GRU(hidden_size, activation='linear', 179 | return_sequences=return_sequences), attention, single_attention_param=True)(x) 180 | x = activation(x) 181 | return x 182 | else: 183 | def _decoder(x, attention): 184 | if bidirectional: 185 | branch_1 = AttentionWrapper(LSTM(int(hidden_size/2), activation='linear', return_sequences=return_sequences, 186 | go_backwards=False), attention, single_attention_param=True)(x) 187 | branch_2 = AttentionWrapper(LSTM(hidden_size, activation='linear', return_sequences=return_sequences, 188 | go_backwards=True), attention, single_attention_param=True)(x) 189 | x = concatenate([branch_1, branch_2]) 190 | x = activation(x) 191 | return x 192 | else: 193 | x = AttentionWrapper(LSTM(hidden_size, activation='linear', return_sequences=return_sequences), 194 | attention, single_attention_param=True)(x) 195 | x = activation(x) 196 | return x 197 | 198 | return _decoder 199 | 200 | 201 | def Decoder(hidden_size, activation=None, return_sequences=True, bidirectional=False, use_gru=True): 202 | if activation is None: 203 | activation = ELU() 204 | if use_gru: 205 | def _decoder(x): 206 | if bidirectional: 207 | x = Bidirectional( 208 | GRU(int(hidden_size/2), activation='linear', return_sequences=return_sequences))(x) 209 | x = activation(x) 210 | return x 211 | else: 212 | x = GRU(hidden_size, activation='linear', 213 | return_sequences=return_sequences)(x) 214 | x = activation(x) 215 | return x 216 | else: 217 | def _decoder(x): 218 | if bidirectional: 219 | x = Bidirectional( 220 | LSTM(int(hidden_size/2), activation='linear', return_sequences=return_sequences))(x) 221 | x = activation(x) 222 | return x 223 | else: 224 | x = LSTM(hidden_size, activation='linear', 225 | return_sequences=return_sequences)(x) 226 | x = activation(x) 227 | return x 228 | return _decoder 229 | -------------------------------------------------------------------------------- /src/model/train.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import csv 3 | import json 4 | from itertools import count 5 | from tqdm import tqdm 6 | from models import seq2seq, seq2seq_attention 7 | from keras.optimizers import SGD, Adagrad, Adam 8 | 9 | sys.path.append('src/utils') 10 | from batch_utils import BatchIterator 11 | from config_utils import settings 12 | 13 | if __name__ == '__main__': 14 | sequence_length = settings.model.sequence_length 15 | vocabulary_size = settings.model.vocabulary_size 16 | hidden_size = settings.model.hidden_size 17 | print ('Creating model with configuration: {0}'.format(settings.model)) 18 | model = seq2seq_attention(sequence_length, vocabulary_size, hidden_size) 19 | 20 | data_file = settings.data.filtered_path 21 | with open(data_file) as handle: 22 | reader = csv.reader(handle) 23 | questions, answers = zip(*reader) 24 | 25 | vocabulary_file = settings.data.vocabulary_path 26 | with open(vocabulary_file) as handle: 27 | vocabulary = json.load(handle) 28 | 29 | batch_size = settings.train.batch_size 30 | n_iter = settings.train.n_iter # 16384 31 | n_epoch = settings.train.n_epoch 32 | print ('Initializing training with configuration: {0}'.format(settings.train)) 33 | iterator = BatchIterator(questions, answers, vocabulary, batch_size, sequence_length, one_hot_target=True) 34 | # generator = (iterator.next_batch() for _ in count(start=0, step=1)) # infinite generator 35 | # model.fit_generator(generator, epochs=2, steps_per_epoch=n_iter * batch_size) 36 | # 37 | bar_format = '{n_fmt}/{total_fmt}|{bar}|ETA: {remaining} - {desc}' 38 | for epoch in range(n_epoch): 39 | print ('-' * 80) 40 | print ('Epoch {0}'.format(epoch)) 41 | print ('-' * 80) 42 | bar = tqdm(range(1, n_iter+1), total=n_iter, bar_format=bar_format, ncols=80) 43 | loss = 0.0 44 | for i in bar: 45 | batch = iterator.next_batch() 46 | loss += model.train_on_batch(*batch) 47 | bar.set_description('loss: {0:.2f}'.format( float(loss)/i )) 48 | bar.refresh() 49 | 50 | print ('Saving model to {0}'.format(settings.model.weights_path)) 51 | model.save_weights(settings.model.weights_path) 52 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabhmathur96/Neural-Chatbot/cd24eed8084de09674e397ebc43f5d8ac506c140/src/utils/__init__.py -------------------------------------------------------------------------------- /src/utils/batch_utils.py: -------------------------------------------------------------------------------- 1 | from keras.preprocessing.sequence import pad_sequences 2 | from numpy import random 3 | from numpy import zeros 4 | 5 | 6 | class BatchIterator(object): 7 | def __init__(self, questions, answers, vocabulary, batch_size, sequence_length, one_hot_target, stream=False): 8 | random.seed(0) 9 | self.sequence_length = sequence_length 10 | self.vocabulary = vocabulary 11 | self.batch_size = batch_size 12 | self.one_hot_target = one_hot_target 13 | self.stream = stream 14 | 15 | self.questions = questions 16 | self.answers = answers 17 | self.inverse_vocabulary = dict((word, i) for i, word in enumerate(self.vocabulary)) 18 | def to_one_hot(self, y): 19 | out = zeros(shape=(self.batch_size, self.sequence_length, len(self.vocabulary)), dtype=bool) 20 | for batch in range(self.batch_size): 21 | for index, word in enumerate(y[batch]): 22 | out[batch, index, word] = True 23 | return out 24 | 25 | def next_batch(self): 26 | inverse_vocabulary = self.inverse_vocabulary 27 | if self.stream: 28 | q = [[inverse_vocabulary[word] for word in next(self.questions).strip().split() ] for i in range(self.batch_size)] 29 | a = [[inverse_vocabulary[word] for word in next(self.answers).strip().split() ] for i in range(self.batch_size)] 30 | else: 31 | n_example = len(self.answers) 32 | indices = random.randint(0, n_example, size=(self.batch_size)) 33 | q = [[inverse_vocabulary[word] for word in self.questions[i].split()] for i in indices] 34 | a = [[inverse_vocabulary[word] for word in self.answers[i].split()] for i in indices] 35 | 36 | X = pad_sequences(q, maxlen=self.sequence_length) 37 | y = pad_sequences(a, maxlen=self.sequence_length) 38 | 39 | if self.one_hot_target: 40 | return (X, self.to_one_hot(y)) 41 | else: 42 | return (X, y) 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/utils/config_utils.py: -------------------------------------------------------------------------------- 1 | from ConfigParser import ConfigParser 2 | from collections import namedtuple 3 | from pprint import pprint 4 | 5 | 6 | parser = ConfigParser() 7 | parser.read('configuration.cfg') 8 | 9 | TrainConfig = namedtuple('TrainConfig', 'batch_size n_iter n_epoch') 10 | ModelConfig = namedtuple('ModelConfig', 'sequence_length vocabulary_size hidden_size weights_path') 11 | DataConfig = namedtuple('DataConfig', 'blacklist_path pairs_path save_path extract_dir vocabulary_path filtered_path unk_ratio') 12 | Settings = namedtuple('Settings', 'train model data') 13 | 14 | train = TrainConfig(int(parser.get('Training', 'batch_size')), 15 | int(parser.get('Training', 'n_iter')), 16 | int(parser.get('Training', 'n_epoch'))) 17 | 18 | model = ModelConfig(int(parser.get('Model', 'sequence_length')), 19 | int(parser.get('Model', 'vocabulary_size')), 20 | int(parser.get('Model', 'hidden_size')), 21 | parser.get('Model', 'weights_path')) 22 | 23 | data = DataConfig(parser.get('Data', 'blacklist_path'), 24 | parser.get('Data', 'pairs_path'), 25 | parser.get('Data', 'opus11_save_path'), 26 | parser.get('Data', 'opus11_extract_dir'), 27 | parser.get('Data', 'vocabulary_path'), 28 | parser.get('Data', 'filtered_path'), 29 | float(parser.get('Data', 'unk_ratio'))) 30 | 31 | settings = Settings(train, model, data) 32 | 33 | 34 | if __name__ == '__main__': 35 | print ('Settings: ') 36 | pprint(dict(settings._asdict())) 37 | -------------------------------------------------------------------------------- /src/utils/data_utils.py: -------------------------------------------------------------------------------- 1 | import sys 2 | reload(sys) 3 | sys.setdefaultencoding('utf-8') 4 | # fix encoding 5 | from io import open 6 | 7 | from tqdm import tqdm 8 | import requests 9 | from itertools import chain 10 | import json 11 | from nltk import sent_tokenize 12 | import string 13 | import re 14 | import unicodedata 15 | 16 | UNK = 'unk' 17 | START = '^' 18 | END = '$' 19 | PAD = '_' 20 | 21 | def download(url, save_path): 22 | response = requests.get(url, stream=True) 23 | length = int(response.headers.get('content-length')) 24 | with open(save_path, 'wb') as handle: 25 | for data in tqdm(response.iter_content(), total=length): 26 | handle.write(data) 27 | 28 | def read_lines(file_path): 29 | def process(line): 30 | tokens = line.strip().split(' +++$+++ ') 31 | return (tokens[0], clean(tokens[-1]) if len(tokens) == 5 else '') 32 | 33 | with open(file_path, encoding='latin-1') as handle: 34 | lines = dict(process(line) for line in tqdm(handle,total=304713) if line) 35 | return lines 36 | 37 | 38 | def normalize_unicode(s): 39 | return ''.join( 40 | c for c in unicodedata.normalize('NFD', s) 41 | if unicodedata.category(c) != 'Mn' 42 | and c in string.printable 43 | ) 44 | 45 | def clean(line): 46 | line = unicode(line) 47 | text = normalize_unicode(line) 48 | 49 | # remove html tags 50 | text = re.sub(r'', ' ', text) 51 | # remove duplicates 52 | text = re.sub(r'\b(\w+)( \1\b)+', r'\1', text) 53 | text = re.sub(r'[\?\.\!]+(?=[\?\.\!])', '', text) 54 | punctuation = ".?!' " 55 | allowed_chars = string.ascii_lowercase + string.ascii_uppercase + punctuation 56 | text = ''.join(c for c in text if c in allowed_chars) 57 | 58 | for p in punctuation: 59 | text = text.replace(p, ' ' + p + ' ') 60 | text = ' '.join(text.split()) 61 | return text 62 | 63 | def augment(pair): 64 | # convert single pair into multiple pairs 65 | question, answer = map(sent_tokenize, pair) 66 | q_sents = list(reversed(question)) 67 | for _ in range(len(q_sents)): 68 | a_sents = answer[:] 69 | for _ in range(len(a_sents)): 70 | yield (' '.join(reversed(q_sents)), ' '.join(a_sents)) 71 | a_sents.pop() 72 | q_sents.pop() 73 | 74 | def make_pairs(file_path, lines): 75 | def process(line, lines): 76 | tokens = line.strip().split(' +++$+++ ') 77 | text = tokens[3].replace("'", '"') 78 | convsersation = json.loads(text) 79 | 80 | # normal pairs 81 | pairs_1 = [(lines[question], lines[answer]) for question, answer in zip(convsersation[0::2], convsersation[1::2])] 82 | 83 | # pairs shifted by one 84 | pairs_2 = [(lines[question], lines[answer]) for question, answer in zip(convsersation[1::2], convsersation[2::2])] 85 | return pairs_1 + pairs_2 86 | 87 | with open(file_path, encoding='latin-1') as handle: 88 | pairs = chain.from_iterable(process(line, lines) for line in handle) 89 | augmented = chain.from_iterable(augment(pair) for pair in pairs) 90 | return list(augmented) 91 | 92 | 93 | 94 | --------------------------------------------------------------------------------