diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..0ca7537 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto +*.txt text +*.py text +*.ipynb text +*.c text +*.h text +*.jpg binary +*.png binary diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f53176d --- /dev/null +++ b/LICENSE @@ -0,0 +1,171 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md index d9d14ad..351e18e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,116 @@ -# bloatectomy -A python package for removing duplicate text in clinical notes +# Bloatectomy +Bloatectomy: a method for the identification and removal of duplicate text in the bloated notes of electronic health records and other documents. Takes in a list of notes or a single file (.docx, .txt, .rtf, etc) or single string to be marked for duplicates. Marked output and tokens are output. + +# Requirements +- Python>=3.7.x (in order for the regular expressions to work correctly) +- re +- sys +- pandas (optional, only necessary if using MIMIC III data) +- docx (optional, only necessary if input or output is a word/docx file) + +# Installation +using anaconda or miniconda +``` +conda install -c summerkrankin bloatectomy +``` + +using pip via PyPI +make sure to install it to python3 if your default is python2 +``` +python3 -m pip install bloatectomy +``` +using pip via github +``` +python3 -m pip install git+git://github.com/MIT-LCP/mimic-code TBA +``` +manual install by cloning the repository +``` +git clone git://github.com/MIT-LCP/mimic-code TBA +cd bloatectomy +python3 setup.py install +``` + +# Examples +To run bloatectomy on a sample string with the following options: +- highlighting duplicates +- display raw results +- output file as html +- output file of numbered tokens: + +``` +from bloatectomy import bloatectomy + +text = '''Assessment and Plan +61 yo male Hep C cirrhosis +Abd pain: +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +ICU Care +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +Assessment and Plan +''' + +bloatectomy(text, style='highlight', display=True, filename='sample_txt_highlight_output', output='html', output_numbered_tokens=True) +``` +To use with example text or load ipynb examples, download the repository or just the bloatectomy_examples folder +``` +cd bloatectomy_examples +from bloatectomy import bloatectomy + +bloatectomy('./input/sample_text.txt', + style='highlight', display=False, + filename='./output/sample_txt_highlight_output', + output='html', + output_numbered_tokens=True, + output_original_tokens=True) +``` + +# Documentation +The paper is located at TBA + +``` +class bloatectomy(input_text, + path = '', + filename='bloatectomized_file', + display=False, + style='highlight', + output='html', + output_numbered_tokens=False, + output_original_tokens=False, + regex1=r"(.+?\.[\s\n]+)", + regex2=r"(?=\n\s*[A-Z1-9#-]+.*)", + postgres_engine=None, + postgres_table=None) +``` +## Parameters +**input_text**: file, str, list +An input document (.txt, .rtf, .docx), a string of text, or list of hadm_ids for postgres mimiciii database or the raw text. + +**style**: str, optional, default=`highlight` +Method for denoting a duplicate. The following are allowed: `highlight`, `bold`, `remov`. + +**filename**: str, optional, default=`bloatectomized_file` +A string to name output file of the bloat-ectomized document. + +**path**: str, optional, default=`' '` +The directory for output files. + +**output_numbered_tokens**: bool, optional, default=`False` +If set to `True`, a .txt file with each token enumerated and marked for duplication, is output as `[filename]_token_numbers.txt`. This is useful when diagnosing your own regular expression for tokenization or testing the `remov` option for **style**. + +**output_original_tokens**: bool, optional, default=`False` +If set to `True`, a .txt file with each original (non-marked) token enumerated but not marked for duplication, is output as `[filename]_original_token_numbers.txt`. + +**display**: bool, optional, default=`False` +If set to `True`, the bloatectomized text will display in the console on completion. + +**regex1**: str, optional, default=`r"(.+?\.[\s\n]+)"` +The regular expression for the first tokenization. Split on a period (.) followed by one or more white space characters (space, tab, line breaks) or a line feed character (`\n`). This can be replaced with any valid regular expression to change the way tokens are created. + +**regex2**: str, optional, default=`r"(?=\n\s*[A-Z1-9#-]+.*)"` +The regular expression for the second tokenization. Split on any newline character (`\n`) followed by an uppercase letter, a number, or a dash. This can be replaced with any valid regular expression to change how sub-tokens are created. + +**postgres_engine**: str, optional +The postgres connection. Only relevant for use with the MIMIC III dataset. When data is pulled from postgres the hadm_id of the file will be appended to the `filename` if set or the default `bloatectomized_file`. See the jupyter notebook [mimic_bloatectomy_example](./bloatectomy_examples/mimic_bloatectomy_example.ipynb) for the example code. + +**postgres_table**: str, optional +The name of the postgres table containing the concatenated notes. Only relevant for use with the MIMIC III dataset. When data is pulled from postgres the hadm_id of the file will be appended to the `filename` if set or the default `bloatectomized_file`. See the jupyter notebook [mimic_bloatectomy_example](./bloatectomy_examples/mimic_bloatectomy_example.ipynb) for the example code. diff --git a/bloatectomy/__init__.py b/bloatectomy/__init__.py new file mode 100644 index 0000000..d8ffd44 --- /dev/null +++ b/bloatectomy/__init__.py @@ -0,0 +1,2 @@ +# -*- coding: utf-8 -*- +from .bloatectomy import bloatectomy diff --git a/bloatectomy/bloatectomy.py b/bloatectomy/bloatectomy.py new file mode 100644 index 0000000..1063f77 --- /dev/null +++ b/bloatectomy/bloatectomy.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +#Bloatectomy: a method for the identification and removal of duplicate text in the bloated notes of electronic health records and other documents. +#Copyright (C) 2020 Summer K. Rankin, Roselie A. Bright, Katherine R. Dowdy +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +#Authors: Summer K. Rankin summerkrankin@gmail.com, Roselie A. Bright roselie.bright@fda.hhs.gov, Katherine R. Dowdy katerdowdy@gmail.com + +import re +import sys + +class bloatectomy(): + def __init__(self, input_text, path = '', filename='bloatectomized_file', + display=False, style='highlight', output='html', output_numbered_tokens=False, output_original_tokens=False, + regex1=r"(.+?\.[\s\n]+)", regex2=r"(?=\n\s*[A-Z1-9#-]+.*)", postgres_engine=None, postgres_table=None): + + self.path = path + self.filename = filename + self.display = display + self.style = style # =['highlight','bold','remove'] + self.output_numbered_tokens = output_numbered_tokens + self.output_original_numbered_tokens = output_original_tokens + self.output = output + self.regex1 = regex1 + self.regex2 = regex2 + self.postgres_table = postgres_table + self.engine = postgres_engine + + assert float(sys.version[0:3]) >= 3.7, "Must use python 3.7.0 or higher for the regular expressions to work correctly." + + try: + if input_text.split('.')[1] == 'docx' or input_text.split('.')[1] == 'doc': + import docx + doc = docx.Document(input_text) + fullText = [] + for para in doc.paragraphs: + fullText.append(para.text) + self.input_text = '\n'.join(fullText) + print(style + "ing duplications in " + input_text + ". Output file = " + path + filename + '.' + output) + bloatectomy.main(self) + + elif input_text.split('.')[1] == 'txt' or input_text.split('.')[1] == 'rtf': + with open(input_text) as file: + self.input_text = file.read() + print(style + "ing duplications in " + input_text + ". Output file = " + path + filename + '.' + output) + bloatectomy.main(self) + + else: + assert type(input_text) == str, "unsupported format" + self.input_text = input_text + print(style + "ing duplications. Output file = " + path + filename + '.' + output) + bloatectomy.main(self) + + except IndexError: + assert type(input_text) == str, "unsupported format" + self.input_text = input_text + print(style + "ing duplications. Output file = " + path + filename + '.' + output) + bloatectomy.main(self) + + except AttributeError: + import numpy + import pandas as pd + assert (type(input_text) == list or type(input_text) == numpy.ndarray), "unsupported format" + print('pulling notes from postgres database') + # select one of the hadm_id s in the list and get the concatenated notes for that hadm_id + for i in input_text: + print(style + "ing duplications in ID " + str(i)) + # in this table, we have concatenated all notes from each hadm_id into a single document + query = """SELECT text FROM {0} WHERE hadm_id IN ({1})""" + query = query.format(self.postgres_table, i) + pt_text = pd.read_sql(query, self.engine) + self.input_text = '' + self.input_text = pt_text.text.to_list()[0] + self.filename = '' + self.filename = filename + '_' + str(i) + bloatectomy.main(self) + print("Output file = " + path + self.filename + '.' + output) + + def main(self): + bloatectomy.tokenize_mark(self) + if self.output=='html': + bloatectomy.make_html(self) + else: + bloatectomy.make_docx(self) + + def make_html(self): + """Takes the output of the just_replication_detection (list of strings) and returns an html file (in path + filename) for the admission with duplicates highlighted""" + + file_name = str(self.path) + str(self.filename) + '.html' + uniq = str("\n ".join(self.tokens)) + # replace line feed characters with html linebreaks + uniq = uniq.replace("\n", "
") + # save bloatectomized file as an html + with open(file_name, "w") as file: + file.write(uniq) + + if self.output_numbered_tokens == True: + with open(str(self.path) + str(self.filename) + '_token_numbers.txt',"w") as file: + for i in self.numbered_tokens: + file.write(str("$ ".join(i) + '\n')) + + if self.output_original_numbered_tokens == True: + with open(str(self.path) + str(self.filename) + '_original_token_numbers.txt',"w") as file: + for i in self.original_numbered_tokens: + file.write(str("$ ".join(i) + '\n')) + + if self.display==True: + print(uniq) + + def make_docx(self): + """Takes the output of the just_replication_detection (list of strings) and returns a docx file (in path + filename) for the admission with duplicates highlighted""" + import docx + document = docx.Document() + p = document.add_paragraph() + run = p.add_run() + font = run.font + file_name = str(self.path) + str(self.filename) + '.docx' + # adding the first entry, not duplicate by nature + p.add_run(self.tokens[0]) + # iterating through all the tokens in text + for i in range(1, len(self.tokens)): + if bool(re.search('[<][m][a][r][k][>]', self.tokens[i])): + new_text = self.tokens[i].replace("", "").replace("", "") + run = p.add_run() + run.add_text(new_text) + run.font.highlight_color = docx.enum.text.WD_COLOR_INDEX.YELLOW + run.add_break(docx.enum.text.WD_BREAK.TEXT_WRAPPING) + elif bool(re.search('[<][b][>]', self.tokens[i])): + new_text = self.tokens[i].replace("", "").replace("", "") + run = p.add_run() + run.add_text(new_text) + run.font.bold = True + run.add_break(docx.enum.text.WD_BREAK.TEXT_WRAPPING) + else: + run = p.add_run() + run.add_text(self.tokens[i]) + run.add_break(docx.enum.text.WD_BREAK.TEXT_WRAPPING) + + document.save(file_name) + if self.display==True: + print(self.tokens) + if self.output_numbered_tokens == True: + with open(str(self.path) + str(self.filename) + '_token_numbers.txt',"w") as file: + for i in self.numbered_tokens: + file.write(str("$ ".join(i) + '\n')) + if self.output_original_numbered_tokens == True: + with open(str(self.path) + str(self.filename) + '_original_token_numbers.txt',"w") as file: + for i in self.original_numbered_tokens: + file.write(str("$ ".join(i) + '\n')) + + def tokenize2(regex, token_in): + """ + Tokenize (2nd time) on a line feed character. + 1. for each token, split if a line feed character is followed by + 2. a capital letter, or a dash, or a number + """ + tok_new = [] + # find any \n followed by an uppercase letter, a number, or a dash + sent_token =re.split(regex, token_in) + # replace \n with a space with a space + sent_token = [re.sub(r"$\n+","",i) for i in sent_token] # remove from end + sent_token = [re.sub(r"^\n", "", i) for i in sent_token] #remove from front + # line feeds + whitespace or not + sent_token = [re.sub(r"\s+\n\s+", " ", i) for i in sent_token] + sent_token = [re.sub(r"\s+\n", " ", i) for i in sent_token] + sent_token = [re.sub(r"\n\s+", " ", i) for i in sent_token] + sent_token = [re.sub(r"\n", " ", i) for i in sent_token] + #remove front/end whitespace + sent_token = [i.strip(' ') for i in sent_token] + for i in sent_token: + if i != '': + tok_new.append(i) + return tok_new + + def number_tokens(token): + """create a list of enumerated (numbered) tokens""" + for enum_num, enum_token in enumerate(token): + yield str(enum_num), enum_token + + def tokenize_mark(self): + """ + 1. Take in raw text and do initial tokenization: on periods followed by one or more space, tab, or line feed character. + 2. Secondary tokenization of each token on line feed character followed by a capital letter, or a number, or a dash. + 3. Add tags to or remove duplicate tokens. + """ + # tokenize 1 + tok = re.split(self.regex1, self.input_text, flags=re.DOTALL) + # whitespace around tokens can cause a duplicate to be missed + tok = [i.strip(' ') for i in tok] + #tokenize 2 + new_tok = [] + for num, t in enumerate(tok): + n_tok = bloatectomy.tokenize2(self.regex2, t) + new_tok.extend(n_tok) + # save original data as numbered list + self.original_numbered_tokens = [] + self.original_numbered_tokens = list(bloatectomy.number_tokens(new_tok)) + # detect and mark/remove duplicates + self.tokens = [] + self.tokens = list(bloatectomy.mark_duplicates(self, new_tok)) + # save bloatectomized tokens as a numbered list + self.numbered_tokens = [] + self.numbered_tokens = list(bloatectomy.number_tokens(self.tokens)) + + def mark_duplicates(self, input_tokens): + ''' + Function uses a set() and list to generate each token with tags (of selected style) added to duplicate tokens. + INPUT: input_tokens = string of tokenized text (can be sentences, paragraphs, words etc) + style = ['bold','higlight','remov'] what to do with duplicate text. + OUTPUT: yield a single token at a time (generator) until the end of the input_tokens. + ''' + if self.style == 'bold': + tag = '' + tag_end = '' + remov = False + elif self.style == 'highlight': + tag = '' + tag_end = '' + remov = False + elif self.style == 'remov': + remov = True + else: + print("Select a style for duplicate text: 'bold' or 'highlight") + # create hash of tokens + tokens_set = set() + tokens_set_add = tokens_set.add + for token in input_tokens: + #skip any empty tokens + if token == '': + pass + elif token not in tokens_set: + tokens_set_add(token) + yield token + elif remov == False: + yield tag + token + tag_end + elif remov == True: + pass diff --git a/bloatectomy_examples/bloatectomy_example.ipynb b/bloatectomy_examples/bloatectomy_example.ipynb new file mode 100644 index 0000000..715240d --- /dev/null +++ b/bloatectomy_examples/bloatectomy_example.ipynb @@ -0,0 +1,180 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "from bloatectomy import bloatectomy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Example using a string as input" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "text = '''Assessment and Plan\n", + "61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and\n", + "renal failure of unclear duration.\n", + "Abd pain:\n", + "-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /\n", + "\n", + "Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9,\n", + "ICU Care\n", + "-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /\n", + " Communication: Comments:\n", + "icu Care\n", + "Assessment and Plan \n", + "Chief Complaint:\n", + "61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and\n", + "renal failure of unclear duration.\n", + "Abd pain:\n", + "'''" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "highlighting duplications. Output file = ./output/sample_string.html\n" + ] + } + ], + "source": [ + "bloatectomy(text, style='highlight', display=False, output='html', filename='./output/sample_string', output_numbered_tokens=True, output_original_tokens=True);\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "highlighting duplications. Output file = sample_string.html\n", + "Assessment and Plan
61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration.
Abd pain:
-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /
Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9,
ICU Care
-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /
Communication: Comments: icu Care
Assessment and Plan
Chief Complaint:
61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration.
Abd pain:\n" + ] + } + ], + "source": [ + "bloatectomy(text, style='highlight', display=True, output='html', filename='sample_string', output_numbered_tokens=True, output_original_tokens=True);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2. Example using a txt file as input" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "highlighting duplications. Output file = ./output/sample_txt_highlight_output.html\n" + ] + } + ], + "source": [ + "bloatectomy('./input/sample_text.txt', style='highlight', display=False, filename='./output/sample_txt_highlight_output', output='html', output_numbered_tokens=True, output_original_tokens=True);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 3. Example using an rtf file as input" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "removing duplications. Output file = ./output/sample_rtf_remov_output.html\n" + ] + } + ], + "source": [ + "bloatectomy('./input/sample_text.rtf', style='remov', display=False, filename='./output/sample_rtf_remov_output', output='html', output_numbered_tokens=True, output_original_tokens=True);\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 4. Example using a word document as input and output" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "bolding duplications. Output file = ./output/sample_docx_output.docx\n" + ] + } + ], + "source": [ + "bloatectomy('./input/sample_text.docx', style='bold', display=False, filename='./output/sample_docx_output', output='docx');\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/bloatectomy_examples/bloatectomy_example.py b/bloatectomy_examples/bloatectomy_example.py new file mode 100644 index 0000000..5f92421 --- /dev/null +++ b/bloatectomy_examples/bloatectomy_example.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + + +text = '''Assessment and Plan +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / + +Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9, +ICU Care +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / + Communication: Comments: +icu Care +Assessment and Plan +Chief Complaint: +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: +''' + +bloatectomy(text, style='highlight', display=False, output='html', output_numbered_tokens=True, output_original_tokens=True) + +bloatectomy('sample_text.txt', style='highlight', display=False, filename='sample_txt_output', output='html', output_numbered_tokens=True, output_original_tokens=True) + +bloatectomy('sample_text.docx', style='bold', display=False, filename='sample_docx_output', output='docx') diff --git a/bloatectomy_examples/input/sample_text.docx b/bloatectomy_examples/input/sample_text.docx new file mode 100644 index 0000000..ba271f1 Binary files /dev/null and b/bloatectomy_examples/input/sample_text.docx differ diff --git a/bloatectomy_examples/input/sample_text.rtf b/bloatectomy_examples/input/sample_text.rtf new file mode 100644 index 0000000..2a5b7e8 --- /dev/null +++ b/bloatectomy_examples/input/sample_text.rtf @@ -0,0 +1,17 @@ +Assessment and Plan +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / + +Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9, +ICU Care +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +Communication: +Comments: +icu Care +Assessment and Plan +Chief Complaint: +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: diff --git a/bloatectomy_examples/input/sample_text.txt b/bloatectomy_examples/input/sample_text.txt new file mode 100644 index 0000000..a79377c --- /dev/null +++ b/bloatectomy_examples/input/sample_text.txt @@ -0,0 +1,17 @@ +Assessment and Plan +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / + +Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9, +ICU Care +-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +Communication: +Comments: +icu Care +Assessment and Plan +Chief Complaint: +61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and +renal failure of unclear duration. +Abd pain: \ No newline at end of file diff --git a/bloatectomy_examples/mimic_bloatectomy_example.ipynb b/bloatectomy_examples/mimic_bloatectomy_example.ipynb new file mode 100644 index 0000000..4d72157 --- /dev/null +++ b/bloatectomy_examples/mimic_bloatectomy_example.ipynb @@ -0,0 +1,318 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Bloatectomy on MIMIC III \n", + "+ Concatenating notes for each admission into one document\n", + "+ This concatenation step is necessary for running bloatectomy on the MIMICiii database. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "import os\n", + "import psycopg2\n", + "import numpy\n", + "from sqlalchemy import create_engine, update, event\n", + "from bloatectomy import bloatectomy " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# if a mistake is made the connection will need to be closed before running again. uncomment the lines below to reset\n", + "#conn.commit()\n", + "#cur.close()\n", + "#conn.close()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "POSTGRES_CONNECT = os.environ.get(\"POSTGRES_CONNECT\")\n", + "#or enter here in the format\n", + "# POSTGRES_CONNECT = psycopg2.connect(\"dbname=mimic user=postgres_username password=postgres_password options=--search_path=mimiciii\");\n", + "\n", + "POSTGRES_ENGINE = os.environ.get(\"POSTGRES_ENGINE\")\n", + "#or enter here in the format\n", + "# POSTGRES_ENGINE = create_engine('postgresql://postgres_username:postgres_password@localhost/mimic'\n", + "\n", + "#connect to posgres\n", + "conn = psycopg2.connect(POSTGRES_CONNECT)\n", + "engine = create_engine(POSTGRES_ENGINE)\n", + "cur = conn.cursor();\n", + "\n", + "#set search path for the mimic schema in postgres\n", + "cur.execute(\"\"\"SET search_path = mimiciii;\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## One Document per Admission\n", + "\n", + "For each admission, concatenate all the notes for that admission into one note (thus, each admission has one **document**). Create a table of these admission notes using the hospital admission id (hadm_id) as the identifier rather than the note id (row_id)\n", + "\n", + "### Notes by Admission `notes_concatenated` with or without metadata\n", + "+ group by admission ID\n", + "+ order by note date ('note_dt')\n", + "+ concatenate all notes for that admission ID into one string\n", + "+ metadata==True: concatenate all notes and other data (date(s), provider=cgid, note, type=category,description) for that admission ID into one string\n", + "+ save as notes_concatenated or notes_concatenated_metadata\n", + "\n", + "### Create new table for results `notes_concatenated` or `notes_concatenated_metadata`\n", + "+ hadm_id\n", + "+ text (concatenate notes and/or other data)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# set whether you want to include metadata at the top of each note (we don't use this for the NLP, but is' useful for the viewing by SMEs)\n", + "metadata = False" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "if metadata==False:\n", + " cur.execute(\"\"\"DROP TABLE IF EXISTS mimiciii.notes_concatenated;\n", + " CREATE TABLE mimiciii.notes_concatenated\n", + " (hadm_id int,\n", + " text varchar);\"\"\") \n", + "else:\n", + " cur.execute(\"\"\"DROP TABLE IF EXISTS mimiciii.notes_concatenated_metadata;\n", + " CREATE TABLE mimiciii.notes_concatenated_metadata\n", + " (hadm_id int,\n", + " text varchar);\"\"\")\n", + "conn.commit();" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# select the specific hadm_ids for this operation. Try with a few to make sure it's working\n", + "xf = pd.read_sql(\"\"\"\n", + "SELECT hadm_id\n", + "FROM mimiciii.noteevents LIMIT 10 \"\"\", engine)\n", + "\n", + "xf_ids = xf.hadm_id.unique()\n", + "#xf_ids" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### function that lets us make multiple requests to the postgres using pandas read_sql" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "@event.listens_for(engine, 'before_cursor_execute')\n", + "def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):\n", + " if executemany:\n", + " cursor.fast_executemany = True" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### function to pull notes, concatenate and save\n", + "\n", + "+ this will take a few hours to run for about half of the hadm_ids in the database\n", + "+ iterate through for each unique admission (hadm_id)\n", + "+ pull all notes for an admission\n", + "+ order notes by charttime , then storetime\n", + "+ concatenate\n", + "+ save as one big note to new table" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "for j in xf_ids:\n", + " \n", + " if metadata == False:\n", + " table_name = 'notes_concatenated'\n", + " sql = \"\"\"\n", + " SELECT hadm_id, chartdate, charttime, storetime, text\n", + " FROM mimiciii.noteevents \n", + " WHERE hadm_id in ({0})\n", + " GROUP BY hadm_id, chartdate, charttime, storetime, text\n", + " ORDER BY chartdate, charttime, storetime\"\"\"\n", + "\n", + " # run sql query above to pull all notes for one admission (in order by date)\n", + " sql = sql.format(j)\n", + " xnotes=pd.read_sql(sql, engine) \n", + " xnotes = xnotes.loc[:,'text']\n", + " \n", + " else: \n", + " table_name = 'notes_concatenated_metadata'\n", + " sql = \"\"\"\n", + " SELECT subject_id, hadm_id, chartdate, charttime, storetime, category, cgid, description, text\n", + " FROM mimiciii.noteevents \n", + " WHERE hadm_id in ({0})\n", + " GROUP BY subject_id, hadm_id, chartdate, charttime, storetime, category, cgid, description, text\n", + " ORDER BY chartdate, charttime, storetime\"\"\"\n", + "\n", + " # run sql query above to pull all notes for one admission (in order by date)\n", + " # concatenate notes and all other cols (metadata)\n", + " # all the metadata gets put into one token for duplicate removal purposes\n", + " sql = sql.format(j)\n", + " xnotes=pd.read_sql(sql, engine)\n", + " xnotes.loc[:,'text2'] = xnotes.loc[:,'text'] \n", + " xnotes.iloc[:,-2] = '. '\n", + " \n", + " # put a a period + whitespace to designate the end start and end of a note \n", + " xnotes['separator'] = '. '\n", + " xtext = xnotes.to_csv(None, header=False, index=False) \n", + " # save as a new dataframe\n", + " xtext2 = [(j, xtext)]\n", + " xfulltext=pd.DataFrame(xtext2, columns=['hadm_id', 'text'])\n", + " # append user and single note to the new table in database\n", + " xfulltext.to_sql(table_name, con=engine, if_exists='append', chunksize=1, index=False, schema='mimiciii')\n", + "\n", + "conn.commit()" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "# load the new table into pandas for inspection\n", + "notes_concat = pd.read_sql(\"\"\"\n", + "SELECT *\n", + "FROM mimiciii.notes_concatenated\"\"\", engine)\n", + "#notes_concat.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Bloatectomy\n", + "Bloatectomize mimiciii data by passing a list of hadm_ids and the table name where the concatenated notes are located" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pulling notes from postgres database\n", + "highlighting duplications in ID 167853\n", + "Output file = ./output/mimic_167853.html\n", + "highlighting duplications in ID 107527\n", + "Output file = ./output/mimic_107527.html\n", + "highlighting duplications in ID 167118\n", + "Output file = ./output/mimic_167118.html\n", + "highlighting duplications in ID 196489\n", + "Output file = ./output/mimic_196489.html\n", + "highlighting duplications in ID 135453\n", + "Output file = ./output/mimic_135453.html\n", + "highlighting duplications in ID 170490\n", + "Output file = ./output/mimic_170490.html\n", + "highlighting duplications in ID 134727\n", + "Output file = ./output/mimic_134727.html\n", + "highlighting duplications in ID 114236\n", + "Output file = ./output/mimic_114236.html\n", + "highlighting duplications in ID 163469\n", + "Output file = ./output/mimic_163469.html\n", + "highlighting duplications in ID 189681\n", + "Output file = ./output/mimic_189681.html\n" + ] + } + ], + "source": [ + "bloatectomy(xf_ids, style='highlight', output='html', filename='./output/mimic', postgres_table='mimiciii.notes_concatenated', postgres_engine=engine);" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pulling notes from postgres database\n", + "highlighting duplications in ID 167853\n", + "Output file = bloatectomized_file_167853.html\n", + "highlighting duplications in ID 167118\n", + "Output file = bloatectomized_file_167118.html\n" + ] + } + ], + "source": [ + "list_example = [167853,167118]\n", + "bloatectomy(list_example, style='highlight', output='html', postgres_table='mimiciii.notes_concatenated', postgres_engine=engine);" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/bloatectomy_examples/output/sample_docx_output.docx b/bloatectomy_examples/output/sample_docx_output.docx new file mode 100644 index 0000000..7d0e359 Binary files /dev/null and b/bloatectomy_examples/output/sample_docx_output.docx differ diff --git a/bloatectomy_examples/output/sample_rtf_remov_output.html b/bloatectomy_examples/output/sample_rtf_remov_output.html new file mode 100644 index 0000000..3679f51 --- /dev/null +++ b/bloatectomy_examples/output/sample_rtf_remov_output.html @@ -0,0 +1 @@ +./input/sample_text.rtf \ No newline at end of file diff --git a/bloatectomy_examples/output/sample_rtf_remov_output_original_token_numbers.txt b/bloatectomy_examples/output/sample_rtf_remov_output_original_token_numbers.txt new file mode 100644 index 0000000..926c7b4 --- /dev/null +++ b/bloatectomy_examples/output/sample_rtf_remov_output_original_token_numbers.txt @@ -0,0 +1 @@ +0$ ./input/sample_text.rtf diff --git a/bloatectomy_examples/output/sample_rtf_remov_output_token_numbers.txt b/bloatectomy_examples/output/sample_rtf_remov_output_token_numbers.txt new file mode 100644 index 0000000..926c7b4 --- /dev/null +++ b/bloatectomy_examples/output/sample_rtf_remov_output_token_numbers.txt @@ -0,0 +1 @@ +0$ ./input/sample_text.rtf diff --git a/bloatectomy_examples/output/sample_string.html b/bloatectomy_examples/output/sample_string.html new file mode 100644 index 0000000..545b38c --- /dev/null +++ b/bloatectomy_examples/output/sample_string.html @@ -0,0 +1 @@ +Assessment and Plan
61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration.
Abd pain:
-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /
Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9,
ICU Care
-other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB /
Communication: Comments: icu Care
Assessment and Plan
Chief Complaint:
61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration.
Abd pain: \ No newline at end of file diff --git a/bloatectomy_examples/output/sample_string_original_token_numbers.txt b/bloatectomy_examples/output/sample_string_original_token_numbers.txt new file mode 100644 index 0000000..ca1999e --- /dev/null +++ b/bloatectomy_examples/output/sample_string_original_token_numbers.txt @@ -0,0 +1,12 @@ +0$ Assessment and Plan +1$ 61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration. +2$ Abd pain: +3$ -other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +4$ Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9, +5$ ICU Care +6$ -other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +7$ Communication: Comments: icu Care +8$ Assessment and Plan +9$ Chief Complaint: +10$ 61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration. +11$ Abd pain: diff --git a/bloatectomy_examples/output/sample_string_token_numbers.txt b/bloatectomy_examples/output/sample_string_token_numbers.txt new file mode 100644 index 0000000..4dbe7f9 --- /dev/null +++ b/bloatectomy_examples/output/sample_string_token_numbers.txt @@ -0,0 +1,12 @@ +0$ Assessment and Plan +1$ 61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration. +2$ Abd pain: +3$ -other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +4$ Troponin-T:4390/40/0.21, ALT / AST:258/575, Alk Phos / T Bili:232/5.9, +5$ ICU Care +6$ -other labs: PT / PTT / INR:16.6// 1.5, CK / CKMB / +7$ Communication: Comments: icu Care +8$ Assessment and Plan +9$ Chief Complaint: +10$ 61 yo male Hep C cirrhosis and HCC presents with probable lower GIB and renal failure of unclear duration. +11$ Abd pain: diff --git a/bloatectomy_examples/output/sample_txt_highlight_output.html b/bloatectomy_examples/output/sample_txt_highlight_output.html new file mode 100644 index 0000000..d9e49c6 --- /dev/null +++ b/bloatectomy_examples/output/sample_txt_highlight_output.html @@ -0,0 +1 @@ +./input/sample_text.txt \ No newline at end of file diff --git a/bloatectomy_examples/output/sample_txt_highlight_output_original_token_numbers.txt b/bloatectomy_examples/output/sample_txt_highlight_output_original_token_numbers.txt new file mode 100644 index 0000000..29b5e69 --- /dev/null +++ b/bloatectomy_examples/output/sample_txt_highlight_output_original_token_numbers.txt @@ -0,0 +1 @@ +0$ ./input/sample_text.txt diff --git a/bloatectomy_examples/output/sample_txt_highlight_output_token_numbers.txt b/bloatectomy_examples/output/sample_txt_highlight_output_token_numbers.txt new file mode 100644 index 0000000..29b5e69 --- /dev/null +++ b/bloatectomy_examples/output/sample_txt_highlight_output_token_numbers.txt @@ -0,0 +1 @@ +0$ ./input/sample_text.txt diff --git a/meta.yaml b/meta.yaml new file mode 100644 index 0000000..7a970de --- /dev/null +++ b/meta.yaml @@ -0,0 +1,44 @@ +{% set name = "bloatectomy" %} +{% set version = "0.0.11" %} + +package: + name: "{{ name|lower }}" + version: "{{ version }}" + +source: + url: "https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz" + sha256: d9df69119581a5266058b9270d8851350c394cc28248f3eb9e3347445d68abdb + MD5: 65d618851c2584be59847a67dd468dbb + BLAKE2-256: 1309f91e59e3f5e7e800f5c204fe1c9442472ba1d667e527b859d6e46c631d4f + +build: + script: "{{ PYTHON }} -m pip install . -vv" + skip: true # [py<37] + +requirements: + host: + - pip + - setuptools + - python + run: + - python + +test: + imports: + - bloatectomy + source_files: + - tests + +about: + home: "https://github.com/MIT-LCP/mimic-code" + license: GPL-3.0-or-later + license_family: GPL3 + license_file: LICENSE.txt + summary: "Bloatectomy: a method for the identification and removal of duplicate text in the bloated notes of electronic health records and other documents." + doc_url: + dev_url: + +extra: + recipe-maintainers: + - 1fmusic + - katerdowdy diff --git a/paper/example_output.png b/paper/example_output.png new file mode 100644 index 0000000..50d97b0 Binary files /dev/null and b/paper/example_output.png differ diff --git a/paper/flowchart.png b/paper/flowchart.png new file mode 100644 index 0000000..97d9ff6 Binary files /dev/null and b/paper/flowchart.png differ diff --git a/paper/graph_abstract.png b/paper/graph_abstract.png new file mode 100644 index 0000000..1164684 Binary files /dev/null and b/paper/graph_abstract.png differ diff --git a/paper/notes1.png b/paper/notes1.png new file mode 100644 index 0000000..c4a1640 Binary files /dev/null and b/paper/notes1.png differ diff --git a/paper/notes2.png b/paper/notes2.png new file mode 100644 index 0000000..cd0ead1 Binary files /dev/null and b/paper/notes2.png differ diff --git a/paper/output_notes1.png b/paper/output_notes1.png new file mode 100644 index 0000000..d280728 Binary files /dev/null and b/paper/output_notes1.png differ diff --git a/paper/output_notes2.png b/paper/output_notes2.png new file mode 100644 index 0000000..dd43b48 Binary files /dev/null and b/paper/output_notes2.png differ diff --git a/paper/paper.bib b/paper/paper.bib new file mode 100644 index 0000000..da8da0f --- /dev/null +++ b/paper/paper.bib @@ -0,0 +1,272 @@ +@electronic{Dean:2018, + Author = {Dean, Shannon M}, + Title = {AHRQ Patient Safety Network: EHR Copy and Paste and Patient Safety}, + Urldate = {Retrieved from https://psnet.ahrq.gov/perspectives/perspective/241}} + +@article{March:2016, + Author = {March, Christopher A and Scholl, Gretchen and Dversdal, Renee K and Richards, Matthew and Wilson, Leah M and Mohan, Vishnu and Gold, Jeffrey A}, + Doi = {10.4300/JGME-D-15-00201.1}, + Journal = {J Grad Med Educ}, + Journal-Full = {Journal of graduate medical education}, + Mesh = {Electronic Health Records; Humans; Internal Medicine; Internship and Residency; Simulation Training}, + Month = {May}, + Number = {2}, + Pages = {237-40}, + Pmc = {PMC4857515}, + Pmid = {27168894}, + Pst = {ppublish}, + Title = {Use of Electronic Health Record Simulation to Understand the Accuracy of Intern Progress Notes}, + Volume = {8}, + Year = {2016}, + Url = {https://doi.org/10.4300/JGME-D-15-00201.1}} + +@article{Tsou:2017, + Author = {Tsou, Amy Y and Lehmann, Christoph U and Michel, Jeremy and Solomon, Ronni and Possanza, Lorraine and Gandhi, Tejal}, + Doi = {10.4338/ACI-2016-09-R-0150}, + Journal = {Appl Clin Inform}, + Journal-Full = {Applied clinical informatics}, + Keywords = {Copy and paste; clinical documentation; electronic health records; health policy; information technology; patient safety}, + Mesh = {Cooperative Behavior; Documentation; Electronic Health Records; Humans; Medical Informatics; Patient Safety; Stakeholder Participation}, + Month = {01}, + Number = {1}, + Pages = {12-34}, + Pmc = {PMC5373750}, + Pmid = {28074211}, + Pst = {epublish}, + Title = {Safe Practices for Copy and Paste in the EHR. Systematic Review, Recommendations, and Novel Model for Health IT Collaboration}, + Volume = {8}, + Year = {2017}, + Url = {https://doi.org/10.4338/ACI-2016-09-R-0150}} + +@article{Corwin:2004, + Author = {Corwin, Howard L and Gettinger, Andrew and Pearl, Ronald G and Fink, Mitchell P and Levy, Mitchell M and Abraham, Edward and MacIntyre, Neil R and Shabot, M Michael and Duh, Mei-Sheng and Shapiro, Marc J}, + Doi = {10.1097/01.CCM.0000104112.34142.79}, + Journal = {Crit Care Med}, + Journal-Full = {Critical care medicine}, + Mesh = {Adult; Aged; Anemia; Blood Chemical Analysis; Blood Transfusion; Cohort Studies; Confidence Intervals; Critical Care; Critical Illness; Erythrocyte Transfusion; Female; Follow-Up Studies; Humans; Intensive Care Units; Male; Middle Aged; Multivariate Analysis; Practice Patterns, Physicians'; Probability; Prospective Studies; Risk Assessment; Severity of Illness Index; Survival Analysis; Treatment Outcome; United States}, + Month = {Jan}, + Number = {1}, + Pages = {39-52}, + Pmid = {14707558}, + Pst = {ppublish}, + Title = {The CRIT Study: Anemia and blood transfusion in the critically ill--current clinical practice in the United States}, + Volume = {32}, + Year = {2004}, + Url = {https://doi.org/10.1097/01.CCM.0000104112.34142.79}} + +@article{Cohen:2013, + Author = {Cohen, Raphael and Elhadad, Michael and Elhadad, No{\'e}mie}, + Doi = {10.1186/1471-2105-14-10}, + Journal = {BMC Bioinformatics}, + Journal-Full = {BMC bioinformatics}, + Mesh = {Algorithms; Data Mining; Electronic Health Records; Health Records, Personal; Humans; Semantics}, + Month = {Jan}, + Pages = {10}, + Pmc = {PMC3599108}, + Pmid = {23323800}, + Pst = {epublish}, + Title = {Redundancy in electronic health record corpora: analysis, impact on text mining performance and mitigation strategies}, + Volume = {14}, + Year = {2013}, + Url = {https://doi.org/10.1186/1471-2105-14-10}} + +@article{Cohen:2014, + Author = {Cohen, Raphael and Aviram, Iddo and Elhadad, Michael and Elhadad, No{\'e}mie}, + Doi = {10.1371/journal.pone.0087555}, + Journal = {PLoS One}, + Journal-Full = {PloS one}, + Mesh = {Algorithms; Data Mining; Documentation; Electronic Health Records; Health Records, Personal; Humans; Models, Statistical}, + Number = {2}, + Pages = {e87555}, + Pmc = {PMC3923754}, + Pmid = {24551060}, + Pst = {epublish}, + Title = {Redundancy-aware topic modeling for patient record notes}, + Volume = {9}, + Year = {2014}, + Url = {https://doi.org/10.1371/journal.pone.0087555}} + +@inproceedings{Ceglarek:2013, + Url = {http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.677.2660&rep=rep1&type=pdf}, + Author = {Ceglarek, D}, + Booktitle = {COGNITIVE 2013: The Fifth International Conference on Advanced Cognitive Technologies and Applications}, + Organization = {IARIA}, + Title = {Linearithmic corpus to corpus comparison by sentence hashing algorithm SHAPD2}, + Year = {2013}} + +@article{Carson:2012, + Author = {Carson, Jeffrey L and Grossman, Brenda J and Kleinman, Steven and Tinmouth, Alan T and Marques, Marisa B and Fung, Mark K and Holcomb, John B and Illoh, Orieji and Kaplan, Lewis J and Katz, Louis M and Rao, Sunil V and Roback, John D and Shander, Aryeh and Tobian, Aaron A R and Weinstein, Robert and Swinton McLaughlin, Lisa Grace and Djulbegovic, Benjamin and {Clinical Transfusion Medicine Committee of the AABB}}, + Doi = {10.7326/0003-4819-157-1-201206190-00429}, + Journal = {Ann Intern Med}, + Journal-Full = {Annals of internal medicine}, + Mesh = {Acute Coronary Syndrome; Adult; Blood Banks; Child; Decision Support Techniques; Erythrocyte Transfusion; Guideline Adherence; Hemoglobin A; Hospitalization; Humans; Randomized Controlled Trials as Topic; United States}, + Month = {Jul}, + Number = {1}, + Pages = {49-58}, + Pmid = {22751760}, + Pst = {ppublish}, + Title = {Red blood cell transfusion: a clinical practice guideline from the AABB*}, + Volume = {157}, + Year = {2012}, + Url = {https://doi.org/10.7326/0003-4819-157-1-201206190-00429}} + +@techreport{copyfind, + Author = {Bloomfield, LA}, + Lastchecked = {2019}, + Title = {The Plagiarism Resource Site: How WCopyfind and Copyfind work}, + Year = {2011} + Urldate = {Retrieved from http://plagiarism.bloomfieldmedia.com/How_WCopyfind_and_Copyfind_Work.pdf}} + +@electronic{aws, + Author = {Amazon Web Services, Inc.}, + Title = {Amazon Elastic Compute Cloud (Amazon EC2)}, + Urldate = {Retrieved from https://aws.amazon.com/ec2/}} + +@article{Altschul:1990, + Author = {Altschul, S F and Gish, W and Miller, W and Myers, EW and Lipman, DJ}, + Doi = {10.1016/S0022-2836(05)80360-2}, + Journal = {J Mol Biol}, + Journal-Full = {Journal of molecular biology}, + Mesh = {Algorithms; Amino Acid Sequence; Base Sequence; Databases, Factual; Mutation; Sensitivity and Specificity; Sequence Homology, Nucleic Acid; Software}, + Month = {Oct}, + Number = {3}, + Pages = {403-10}, + Pmid = {2231712}, + Pst = {ppublish}, + Title = {Basic local alignment search tool}, + Volume = {215}, + Year = {1990}, + Url = {https://doi.org/10.1016/S0022-2836(05)80360-2}} + +@article{mimiciii, + title={MIMIC-III, a freely accessible critical care database}, + author={Johnson, Alistair EW and Pollard, Tom J and Shen, Lu and Li-wei, H Lehman and Feng, Mengling and Ghassemi, Mohammad and Moody, Benjamin and Szolovits, Peter and Celi, Leo Anthony and Mark, Roger G}, + journal={Scientific data}, + volume={3}, + pages={160035}, + year={2016}, + publisher={Nature Publishing Group} + } + +@misc{mimiciiidata, + author={Pollard, Tom J abd Johnson, Alistair EW}, + title={The MIMIC-III Clinical Database}, + doi={10.13026/C2XW26}, + year={2016}, + howpublished= {http://dx.doi.org/10.13026/C2XW26} + } + +@article{physionet, + title={PhysioBank, PhysioToolkit, and PhysioNet: components of a new research resource for complex physiologic signals}, + author={Goldberger, Ary L and Amaral, Luis AN and Glass, Leon and Hausdorff, Jeffrey M and Ivanov, Plamen Ch and Mark, Roger G and Mietus, Joseph E and Moody, George B and Peng, Chung-Kang and Stanley, H Eugene}, + journal={Circulation}, + volume={101}, + number={23}, + pages={e215--e220}, + year={2000}, + publisher={Am Heart Assoc} + } + +@book{python3, + Doi = {10.5555/1593511}, + Author = {Van Rossum, Guido and Drake, Fred L}, + title = {Python 3 Reference Manual}, + year = {2009}, + isbn = {1441412697}, + publisher = {CreateSpace}, + address = {Scotts Valley, CA} + } + +@article{Lancichinetti:2015, + Author = {Lancichinetti, A., Sirer, M. I., Wang, J. X., Acuna, D., Koerding, K., & Amaral, L. A.}, + Year = {2015}, + Doi = {10.1103/PhysRevX.5.011007}, + Title = {High-reproducibility and high-accuracy method for automated topic classification}, + Journal = {Physical Review X}, + Volume = {5}, + Pages = {011007-1--011007-11} + } +@inproceedings{Mckinney:2010, + Author = {McKinney, W}, + Year = {2010}, + Title = {Data structures for statistical computing in python}, + Booktitle = {Proceedings of the 9th Python in Science Conference}, + Pages = {51--56} +} +@article{Meystre:2008, + Author = {Meystre, SM, and Savova, GK and Kipper-Schuler, KC and Hurdle, JF}, + Year = {2008}, + Title = {Extracting information from textual documents in the electronic health record: a review of recent research}, + Journal = {Yearbook of medical informatics}, + Volume = {17}, + Number = {1}, + Pages = {128--144} + } +@misc{Mikolov:2013, + title={Distributed Representations of Words and Phrases and their Compositionality}, + author={Tomas Mikolov and Ilya Sutskever and Kai Chen and Greg Corrado and Jeffrey Dean}, + year={2013}, + eprint={1310.4546}, + archivePrefix={arXiv}, + primaryClass={cs.CL} + } + @INPROCEEDINGS{Su:2008, + author={Z. {Su} and B. {Ahn} and K. {Eom} and M. {Kang} and J. {Kim} and M. {Kim}}, + booktitle={2008 3rd International Conference on Innovative Computing Information and Control}, + title={Plagiarism Detection Using the Levenshtein Distance and Smith-Waterman Algorithm}, + year={2008}, + volume={}, + number={}, + pages={569-569} + } +@article{Thielke:2007, + title = {Copying and pasting of examinations within the electronic medical record}, + journal = {International Journal of Medical Informatics}, + volume = {76}, + pages = {S122--S128}, + year = {2007}, + note = {Information Technology in Health Care: Sociotechnical Approaches}, + issn = {1386-5056}, + doi = {10.1016/j.ijmedinf.2006.06.004}, + url = {http://www.sciencedirect.com/science/article/pii/S1386505606001663}, + author = {Thielke, S and Hammond, K and Helbig, S} + } +@Article{Welch:1984, + author={ {Welch}}, + journal={Computer}, + title={A Technique for High-Performance Data Compression}, + year={1984}, + volume={17}, + number={6}, + pages={8-19} + } +@article{Wrenn:2010, + author = {Wrenn, Jesse O and Stein, Daniel M and Bakken, Suzanne and Stetson, Peter D}, + title = "{Quantifying clinical narrative redundancy in an electronic health record}", + journal = {Journal of the American Medical Informatics Association}, + volume = {17}, + number = {1}, + pages = {49-53}, + year = {2010}, + month = {01}, + issn = {1067-5027}, + doi = {10.1197/jamia.M3390}, + url = {https://doi.org/10.1197/jamia.M3390}, + eprint = {https://academic.oup.com/jamia/article-pdf/17/1/49/6026060/17-1-49.pdf}, + } +@article{Zhang:2011, + Author = {Zhang, R and Pakhomov, S and McInnes, B T and Melton, G B}, + Year = {2011}, + Title = {Evaluating measures of redundancy in clinical texts}, + Journal = {AMIA Annu Symp Proc}, + Pages = {1612--1620}, + Url = {https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3243221/} + } + +@article{Gabriel:2018, + Author = {Rodney A. Gabriel and Tsung-Ting Kuo and Julian McAuley and Chun-Nan Hsu}, + Journal = {Journal of Biomedical Informatics}, + Year = {2018}, + Volume = {82}, + Pages = {63--69} +} diff --git a/paper/paper.md b/paper/paper.md new file mode 100644 index 0000000..ef6d789 --- /dev/null +++ b/paper/paper.md @@ -0,0 +1,367 @@ +--- +title: 'Bloatectomy: A python package for the identification and removal of duplicate text in the bloated notes of electronic health records and other documents' +tags: + - python + - medical informatics + - electronic health records + - electronic medical records + - public health informatics + - clinical information extraction + - health informatics + - natural language processing +authors: + - name: Summer K. Rankin* + orcid: 0000-0002-6886-3983 + affiliation: "1" + - name: Roselie Bright + orcid: 0000-0002-7565-1284 + affiliation: "2" + - name: Katherine Dowdy + affiliation: "1" +affiliations: + - name: Booz Allen Hamilton, McLean, VA, USA + index: "1" + - name: Office of Health Informatics, Office of the Chief Scientist, Office of the Commissioner, U.S. Food and Drug Administration, 10903 New Hampshire Avenue, Silver Spring, MD, USA 20993-0002 roselie.bright@fda.hhs.gov. + index: "2" +date: 1 June 2020 +bibliography: paper.bib +--- + +*corresponding author +The authors are listed in order of contributions to the work and manuscript. + + +# Summary +Objective: Identify duplicate sentences in unstructured healthcare notes, mark them for manual review, and remove them from statistical analysis. +Introduction: Duplicated sentences (“note bloat”) in unstructured electronic healthcare records hamper scientific research. Existing methods did not meet our needs. +Methods: We adapted the LZW compression algorithm into a new method and designed parameters to allow customization for varying data and research needs. +Results: Examples are presented. +Conclusions: The Bloatectomy method works, is available for use, and can be adapted for other settings. + +![Graphical Abstract. ](graph_abstract.png) + +# Introduction +The authors are part of a team that is using the text notes in electronic healthcare records (EHRs). Our EHRs are a de-identified hospital critical care data set known as the Medical Information Mart for Intensive Care (MIMIC-III)[@mimiciii; @mimiciiidata; @physionet]. + +Most notes were made by physicians (attending, radiology, consulting) and CCU nurses. Most of these notes included sections that were duplicates of earlier notes (written by themselves or another provider) for the same patient’s hospitalization (their admission). Sometimes pasted sections were edited, and then the modified text was duplicated into later notes (see \autoref{notes1} and \autoref{notes2}). + +![Progressively longer nurse’s notes over one shift. In this figure, we used a manual method to highlight identical sentences with unique colors. The original sentences are in bold font as well. This and similar figures in this document are purposely small and low resolution to provide further patient and provider privacy protection without disturbing our point about duplicate text.\label{notes1}](notes1.png) + +![Example of two physicians’ notes from the same time period. In this figure, we used a manual method to highlight identical sentences with unique colors. The original sentences are in bold font as well.\label{notes2}](notes2.png) + +This type of duplication has been noticed in other health care settings [reviewed in @Dean:2018]. The duplications distort statistical analyses of terms used and hamper manual review of the notes for changes in patient care and status. Removing these duplicated notes allows us to use a wide variety of statistical methods without concern for the weights introduced by duplicates. + +For example, if we are using a simple frequency (count) vectorization method, the more times a word appears, the more important it is in the analysis. Furthermore, as length of stay increases, the burden of duplicates also increases, which inflates the importance of, for example, admission comments. Artificial repeats (copies) of text will artificially inflate the importance of the repeated words or phrases [@Cohen:2013]. Though existing methods can weight words (i.e., term-frequency x inverse document frequency [TF-IDF]), for this dataset these methods did not yield satisfactory results. + +Our goal was to identify duplicated sections to aid manual review and to delete them from statistical processes. We developed criteria for the tool that were based on the clinical setting and our desire to keep all new clinical information. Specifically: + +1. Minimum clinical concepts were at the sentence or partial or complete list level. Minor changes within a sentence or list could change the clinical meaning; for example, insertion of the word “not” reverses the meaning of a sentence. We wanted a tool that would find exact duplicate sentences and lists. +2. Duplications could occur as an entire note or partial note. We wanted to find both partial and entire duplicates of notes. +3. Duplications from more than one original source could occur in a single note, and we wanted to find all of them. +4. Exact or partial duplications could occur across many notes, and we wanted to find all of them. +5. Lists of clinical parameters and values could be completely or partially duplicated across notes. In addition to finding duplicates of entire lists, we wanted to find duplicates of significantly long sections of lists in the notes. +6. Document structure (headings, paragraph formats, list formats) of notes varied widely. We needed a method with broad independence of the internal structures. +7. We wanted the method to be simple and user-friendly if doing so resulted in an acceptably low level of error. +8. We wanted to be able to use the output for two purposes: + a. Aid manual review of notes by marking the duplicate sections + b. Statistical analyses + + +We evaluated existing available tools and strategies. +- Plagiarism tools typically compare documents and stop after finding the first instance of duplicate text [@Su:2008; @copyfind; @Ceglarek:2013]; some also appropriately account for paraphrasing. Some other duplication detection methods [@Thielke:2007; @Wrenn:2010] rely on the Bloomfield plagiarism tool. We focused on concepts at the sentence level because word meaning depends on its immediate sentence and paragraph, regardless of where it appears in the note. Genetic and protein sequence comparators also finish after finding similar sequences [@Altschul:1990]. We wanted to find exact duplicates and every instance of them. +- Some existing EHR deduplication methods have been applied only to the discharge note [@Cohen:2013]. Unfortunately, the discharge notes in MIMIC III are not comprehensive accounts of all observations and treatments that may be key to specific research questions; for example, blood transfusions are sometimes noted in coded data or nursing notes yet were absent from the discharge summary. +- Fingerprinting identifies redundant entire notes based on similarity [@Cohen:2013], but it finds inexact duplicates (which could be clinically different in some way). Also, we wanted to identify duplicate concepts within notes even if some other parts of the note were original. +- Clustering entire notes, and then looking for entire and near duplicate pairs of notes within clusters [@Gabriel:2018] works only on entire notes. We wanted to detect duplicate sentences and lists within notes, even if new material existed among the duplicates. +- Detecting duplicates through topic modeling, an unsupervised and unreplicable [@Lancichinetti:2015] method of clustering related words and expressions within documents, [@Cohen:2014] involved comparing two simplifications that did not fit our needs + - Selection and use of a best note within the admission. We found that crucial clinical information was missing from any one best note in an admission. + - Selection of the one source note, the longest one, in the admission. We found that in MIMIC III, there is no single source note in an admission. +- Sliding windows [@Zhang:2011], similar to frameshifting in other fields, were a possibility if we adapted them to sentences and lists. We believe our method is simpler to implement. + + +The LZW compression algorithm [@Welch:1984] hashes words by assigning sequential numeric addresses to them. Any word that has been hashed before is assigned the original numeric address. We adapted the method to sentences rather than words because the altered sentences in pasted text also had new meanings. The hashing system allowed us to both highlight pasted sentences in text documents and remove the duplicate sentences during preprocessing for statistical analysis. + +# Duplicate Detection +![High-level flowchart of the Bloatectomy method. ](flowchart.png) + +## Document Selection +In Natural Language Processing (NLP), we refer to a unit of text as a document. In the MIMIC-III database, free-text notes from multiple sources are associated with a patient's admission (HADM_ID). For our analysis, a document consisted of the concatenation of all notes for an admission into one single document in chronological order. Thus, there is one document per admission. + +## Code and Example +The Bloatectomy (v.2.1) tool can be found in the python package ``bloatectomy.py``. The MIMIC-III database was stored in a PostgreSQL (v.9.4) database. The Bloatectomy tool was written using only Python 3 (v.3.7.3) [@python3]. No other libraries are needed to identify duplicate text. An option to ingest or output a word document requires the python-docx library. +The Bloatectomy method is as follows: +1. Create sentence tokens. +2. Create list tokens. +3. Assign either new or old hash number. +4. Use the hash table of tokens to: + - Mark duplicate tokens in a recreated document for manual review. + - Create a string from the unduplicated tokens for statistical analysis. + +### Create Sentence Tokens +First, we tokenized (separated) an admission's concatenated notes (a single document) based on the presence of: +- a period ( . ) followed by one or more + white space characters (space, tab, line breaks) or a + line feed character (\n). + +An example of the text seen in an EHR looks like the following: +```No CP. Became tachycardic to 160s on dopa. No CP. +Tmax: 36.6 +C (97.8 +HR: 100 (97 - 166) bpm +Tmax: 36.6 +C (97.8 +``` + +The plain text—i.e., only the characters used to represent the text—looks like the following: +``` +No CP. Became tachycardic to 160s on dopa. No CP.\nTmax: 36.6\nC (97.8\nHR: 100 (97 - 166) bpm\nTmax: 36.6\nC (97.8 +``` +The first tokenization was accomplished using a regular expression \autoref{regex1} in python (v.3.7.3) using the `re` (regular expression) library. This regular expression can be changed by passing any valid regular expression for the `regex1` parameter. +![The regular expression used for the first tokenization.\label{regex1}](regex1.png) + +At this point, we have two tokens because there are two periods followed by a line feed character. + +| Token Number | Token | +| :------------- | :------------- | +| 1 | No CP. | +| 2 |Became tachycardic to 160s on dopa. | +| 3 | No CP. | +|4 | \nTmax: 36.6\nC (97.8\nHR: 100 (97 - 166) bpm\nTmax: 36.6\nC (97.8 | + + + +### Create List Token +Next, each token is examined and split again if it contains a line feed character followed by one or more: +- Upper case character +- Digit +- En dash (-) +- Number sign (#) + +Using our sample text, token 4 is split into several new tokens, which are then inserted into our token list. If a token does not need to be split further, it is added to our list as-is. The regular expression for the split described in \autoref{regex2}. This regular expression can be changed by passing any valid regular expression for the `regex2` parameter. + +![The regular expression used to calculate the second tokenization.\label{regex2}](regex2.png) + +After the token has been split, the text is cleaned up to increase the matches and focus on the text rather than the formatting. All line feed characters are replaced with one white space. White spaces at the beginning and end of a token are removed, then the token is added to the new token list. + +``` +# replace \n with a space with a space +sent_token = [re.sub(r"$\n+","",i) for i in sent_token] # remove from end +sent_token = [re.sub(r"^\n", "", i) for i in sent_token] #remove from front + +# line feeds + whitespace or not +sent_token = [re.sub(r"\s+\n\s+", " ", i) for i in sent_token] +sent_token = [re.sub(r"\s+\n", " ", i) for i in sent_token] +sent_token = [re.sub(r"\n\s+", " ", i) for i in sent_token] +sent_token = [re.sub(r"\n", " ", i) for i in sent_token] + +#remove front/end whitespace +sent_token = [i.strip(' ') for i in sent_token] +``` + +Specifically, token 4 becomes 5 new tokens: + + +| Token Number | Token | +| :------------- | :------------- | +| 1 | No CP. | +| 2 |Became tachycardic to 160s on dopa. | +| 3 | No CP. | +|4 | Tmax: 36.6 | +| 5 | C (97.8 | +|6 | HR: 100 (97 - 166) bpm | +|7 | Tmax: 36.6 | +|8 | C (97.8 | + + +### Assign Either New or Old Hash Number +Next, we create a dynamic set structure that accepts tokens one at a time. The function is a generator that yields one token at a time; when the output is stored as a list, the original order of tokens is maintained while providing the flexibility to either remove or mark (highlight, bold) a duplicate token. +As each token is passed through the loop, one of two outcomes will result: +1. If the token is not in the dynamic set, it will be added to the set, and the token is yielded as-is. +2. If the token is already contained in the set, it is NOT added to the set; HTML tags are added to the token, yielding a marked token. If we want to remove the token, nothing is yielded at this step. + +``` +tokens_set = set() +tokens_set_add = tokens_set.add + +for token in input_tokens: + + if token == '': + pass + + elif token not in tokens_set: + tokens_set_add(token) + yield token + + elif remov == False: + yield tag + token + tag_end + + elif remov == True: + pass +``` +The token table essentially becomes the following hash table of tokens: + +| Token Number | Token | Bloat | Hash # | +| :------------- | :------------- |:------------- |:------------- | +| 1 | No CP. | No | 1 | +| 2 |Became tachycardic to 160s on dopa. | No | 2| +| 3 | No CP. | Yes | 1| +|4 | Tmax: 36.6 | No | 3| +| 5 | C (97.8 | No | 4 | +|6 | HR: 100 (97 - 166) bpm | No | 5 | +|7 | Tmax: 36.6 | Yes | 3 | +|8 | C (97.8 | Yes | 4 | + + +### Use the Hash Table of Tokens +The output is a document with a list of our original tokens with highlight formatting marks around the duplicates. The user can choose to highlight, bold, or remove duplicates by setting the ``style`` argument. + +``` +import bloatectomy from bloatectomy +bloatectomy(text, style='highlight')) +``` + +| Token Number | Token | +| :------------- | :------------- | +| 1 | No CP. | +| 2 |Became tachycardic to 160s on dopa. | +| duplicate | No CP. | +|4 | Tmax: 36.6 | +| 5 | C (97.8 | +|6 | HR: 100 (97 - 166) bpm | +|duplicate | Tmax: 36.6 | +|duplicate | C (97.8 | + +Last, we concatenate this marked (or de-duplicated) set of tokens together to create a document of original sentences. A line feed is placed between each token for ease of viewing (due to removing the line feed characters at the beginning and end of each token). How this is executed depends on the type of output (e.g., docx, HTML). +``` +uniq = str("\n".join(text)) +``` +The final output contains three highlighted duplicate tokens: + +![Marked output for the example text. ](example_output.png) + +The marked text can be deleted for statistical analyses. +``` +bloatectomy(text, style='remov')) +``` + +## Parameter Adjustments +We incorporated parameters that users can set to fit the features of the documents they are using. The following input types can be used: +1. Plain text files (.txt, .rtf) +2. Word documents (.docx) +3. A variable containing a string of raw text +4. A list of HADM_ID values for a PostgreSQL database (specific to MIMIC III database) + +The following output types are available: +1. HTML file (.html) +2. Word document (.docx) +3. Print the text to the console +4. Numbered tokens from original (raw) text (.txt) +5. Numbered tokens after duplication detection (.txt) + +The duplicates can be marked using: +1. highlighting +2. bold +3. remove + + +# Results +\autoref{output_notes1} and \autoref{output_notes2} show the sample nurse’s and physicians’ notes after Bloatectomy. + +![Figure 4. The same nurse’s notes from \autoref{notes1}, after Bloatectomy.\label{output_notes1}](output_notes1.png) +![Figure 5. The same physicians’ notes from \autoref{notes2}, after Bloatectomy.\label{output_notes2}](output_notes2.png) + +We note that Bloatectomy doesn’t exactly replicate manual evaluation of duplications. + +# Conclusions +We accepted some error in favor of simplicity and our reluctance to over-customize the algorithm. We favored leaving in duplicates over marking new information because of our research goals. Other users will find the amount of error, of either type, depends on the software parameters and the data. At least some manual review of their data will help users choose their own balance of types of errors to accept, depending on their goals. + +Bloatectomy is an effective tool for identifying duplicate text in EHRs and would be useful for other types of documents with multiple instances of duplicate sentences or paragraphs. + +# Summary +Duplicated sentences (“note bloat”) in unstructured electronic healthcare records hamper scientific research. +Existing methods did not meet our needs. +We adapted the LZW compression algorithm into a new method and designed parameters to allow customization for varying data and research needs. +The Bloatectomy method works, is available for use, and can be adapted for other settings. + +# Sample Text +To run bloatectomy on the sample text, use this in python 3.7.x or higher + +``` +from bloatectomy import bloatectomy + +bloatectomy('sample_text.txt', + filename='sampletxt_output', + display=False, + style='highlight', + output='html', + output_numbered_tokens=True, + output_original_tokens=True ) +``` +This takes in the single text file (i.e., sample_text.txt) to be marked for duplicates. The marked output, original numbered tokens and marked numbered tokens can be output. Note that the tokens in the two numbered token files will have the same token numbers unless style='remov'. + +## Parameters +``` +class bloatectomy(input_text, + path = '', + filename='bloatectomized_file', + display=False, + style='highlight', + output='html', + output_numbered_tokens=False, + output_original_tokens=False, + regex1=r"(.+?\.[\s\n]+)", + regex2=r"(?=\n\s*[A-Z1-9#-]+.*)", + postgres_engine=None, + postgres_table=None) +``` + +**input_text**: file, str, list +An input document (.txt, .rtf, .docx), a string of text, or list of hadm_ids for postgres mimiciii database or the raw text. + +**style**: str, optional, default=`highlight` +Method for denoting a duplicate. The following are allowed: `highlight`, `bold`, `remov`. + +**filename**: str, optional, default=`bloatectomized_file` +A string to name output file of the bloat-ectomized document. + +**path**: str, optional, default=`' '` +The directory for output files. + +**output_numbered_tokens**: bool, optional, default=`False` +If set to `True`, a .txt file with each token enumerated and marked for duplication, is output as `[filename]_token_numbers.txt`. This is useful when diagnosing your own regular expression for tokenization or testing the `remov` option for **style**. + +**output_original_tokens**: bool, optional, default=`False` +If set to `True`, a .txt file with each original (non-marked) token enumerated but not marked for duplication, is output as `[filename]_original_token_numbers.txt`. + +**display**: bool, optional, default=`False` +If set to `True`, the bloatectomized text will display in the console on completion. + +**regex1**: str, optional, default=`r"(.+?\.[\s\n]+)"` +The regular expression for the first tokenization. Split on a period (.) followed by one or more white space characters (space, tab, line breaks) or a line feed character (\n). This can be replaced with any valid regular expression to change the way tokens are created. + +**regex2**: str, optional, default=`r"(?=\n\s*[A-Z1-9#-]+.*)"` +The regular expression for the second tokenization. Split on any newline character (\n) followed by an uppercase letter, a number, or a dash. This can be replaced with any valid regular expression to change how sub-tokens are created. + +**postgres_engine**: str, optional +The postgres connection. Only relevant for use with the MIMIC III dataset. See the jupyter notebook [mimic_bloatectomy_example](../bloatectomy_examples/mimic_ bloatectomy_example.ipynb). + +**postgres_table**: str, optional +The name of the postgres table containing the concatenated notes. Only relevant for use with the MIMIC III dataset. + + + +# Acknowledgements +The authors thank Walter G. Bright, originator of the D language (WalterBright.com), for suggesting the LZW algorithm. Serge Blok, PhD, of Booz Allen Hamilton, offered the name Bloatectomy and reviewed the draft manuscript. Daily project support was provided by George Plopper, PhD, and Lauren Neal, PhD at Booz Allen Hamilton, and Letria Hall and Elaine Johanson at FDA. Susan Bright, DVM, MPH, and Lee Anne Palmer, VMD, MPH, both in the Office of Surveillance and Compliance, Center for Veterinary Medicine, FDA, participated in establishing the need to identify and remove duplicate text. + +# Funding +This work was supported by the FDA Shakespeare Electronic Health Records (EHR) Text Mining Project HHSF223201510027B. + +# Conflicts of Interest +The authors have declared that no competing interests exist. + +# Disclaimer +The statements made in this article are not necessarily the official policy of the Food and Drug Administration. + +# Data +All data for the development of this tool are located at the MIMIC-III website https://mimic.physionet.org. The code is located at https://github.com/MIT-LCP/mimic-code + +# References diff --git a/paper/regex1.png b/paper/regex1.png new file mode 100644 index 0000000..1b979bc Binary files /dev/null and b/paper/regex1.png differ diff --git a/paper/regex2.png b/paper/regex2.png new file mode 100644 index 0000000..2263ed6 Binary files /dev/null and b/paper/regex2.png differ diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..82eda0d --- /dev/null +++ b/setup.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +with open("README.md", "r") as fh: + long_description = fh.read() + +setup( + name="bloatectomy", # Replace with your own username + version="0.0.11", + author="Summer Rankin, Roselie Bright, Katherine Dowdy", + author_email="summerKRankin@gmail.com", + description="Bloatectomy: a method for the identification and removal of duplicate text in the bloated notes of electronic health records and other documents.", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/MIT-LCP/bloatectomy", + packages=['bloatectomy'], + license="GPLv3", + keywords=["python", "medical informatics","electronic health records", + "electronic medical records", "public health informatics", + "clinical information extraction", "informatics", "natural language processing"], + classifiers=[ + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Operating System :: OS Independent", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Information Analysis", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: Text Processing", + "Topic :: Utilities", + ], + python_requires='>=3.7', +)