plainqafact 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. plainqafact-0.1.0/LICENSE +201 -0
  2. plainqafact-0.1.0/MANIFEST.in +8 -0
  3. plainqafact-0.1.0/PKG-INFO +167 -0
  4. plainqafact-0.1.0/README.md +120 -0
  5. plainqafact-0.1.0/models/README.md +1 -0
  6. plainqafact-0.1.0/plainqafact/plainqafact/__init__.py +8 -0
  7. plainqafact-0.1.0/plainqafact/plainqafact/bertscore_scorer.py +41 -0
  8. plainqafact-0.1.0/plainqafact/plainqafact/classifier.py +113 -0
  9. plainqafact-0.1.0/plainqafact/plainqafact/default_config.py +33 -0
  10. plainqafact-0.1.0/plainqafact/plainqafact/plainqafact.py +121 -0
  11. plainqafact-0.1.0/plainqafact/plainqafact/run.py +187 -0
  12. plainqafact-0.1.0/plainqafact/plainqafact/transformers_old_tokenizer-3.1.0-py3-none-any.whl +0 -0
  13. plainqafact-0.1.0/plainqafact.egg-info/PKG-INFO +167 -0
  14. plainqafact-0.1.0/plainqafact.egg-info/SOURCES.txt +51 -0
  15. plainqafact-0.1.0/plainqafact.egg-info/dependency_links.txt +1 -0
  16. plainqafact-0.1.0/plainqafact.egg-info/entry_points.txt +2 -0
  17. plainqafact-0.1.0/plainqafact.egg-info/requires.txt +22 -0
  18. plainqafact-0.1.0/plainqafact.egg-info/top_level.txt +1 -0
  19. plainqafact-0.1.0/qaeval/__init__.py +6 -0
  20. plainqafact-0.1.0/qaeval/answer_selection.py +209 -0
  21. plainqafact-0.1.0/qaeval/answering/__init__.py +1 -0
  22. plainqafact-0.1.0/qaeval/answering/__pycache__/__init__.cpython-38.pyc +0 -0
  23. plainqafact-0.1.0/qaeval/answering/__pycache__/__init__.cpython-39.pyc +0 -0
  24. plainqafact-0.1.0/qaeval/answering/__pycache__/utils.cpython-38.pyc +0 -0
  25. plainqafact-0.1.0/qaeval/answering/__pycache__/utils.cpython-39.pyc +0 -0
  26. plainqafact-0.1.0/qaeval/answering/model.py +243 -0
  27. plainqafact-0.1.0/qaeval/answering/utils.py +259 -0
  28. plainqafact-0.1.0/qaeval/generation/__init__.py +0 -0
  29. plainqafact-0.1.0/qaeval/generation/__pycache__/__init__.cpython-38.pyc +0 -0
  30. plainqafact-0.1.0/qaeval/generation/__pycache__/__init__.cpython-39.pyc +0 -0
  31. plainqafact-0.1.0/qaeval/generation/__pycache__/util.cpython-38.pyc +0 -0
  32. plainqafact-0.1.0/qaeval/generation/__pycache__/util.cpython-39.pyc +0 -0
  33. plainqafact-0.1.0/qaeval/generation/model.py +103 -0
  34. plainqafact-0.1.0/qaeval/generation/util.py +4 -0
  35. plainqafact-0.1.0/qaeval/metric.py +335 -0
  36. plainqafact-0.1.0/qaeval/scoring/__init__.py +0 -0
  37. plainqafact-0.1.0/qaeval/scoring/scorers/__init__.py +5 -0
  38. plainqafact-0.1.0/qaeval/scoring/scorers/em.py +24 -0
  39. plainqafact-0.1.0/qaeval/scoring/scorers/f1.py +24 -0
  40. plainqafact-0.1.0/qaeval/scoring/scorers/is_answered.py +23 -0
  41. plainqafact-0.1.0/qaeval/scoring/scorers/lerc.py +80 -0
  42. plainqafact-0.1.0/qaeval/scoring/scorers/meta.py +44 -0
  43. plainqafact-0.1.0/qaeval/scoring/scorers/scorer.py +85 -0
  44. plainqafact-0.1.0/requirements.txt +22 -0
  45. plainqafact-0.1.0/setup.cfg +4 -0
  46. plainqafact-0.1.0/setup.py +38 -0
  47. plainqafact-0.1.0/src/data/pubmed.py +59 -0
  48. plainqafact-0.1.0/src/data/statpearls.py +104 -0
  49. plainqafact-0.1.0/src/data/textbooks.py +31 -0
  50. plainqafact-0.1.0/src/data/wikipedia.py +42 -0
  51. plainqafact-0.1.0/src/medrag.py +82 -0
  52. plainqafact-0.1.0/src/template.py +97 -0
  53. plainqafact-0.1.0/src/utils.py +384 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt
4
+ include plainqafact/plainqafact/transformers_old_tokenizer-3.1.0-py3-none-any.whl
5
+ recursive-include plainqafact/plainqafact *.py
6
+ recursive-include models *
7
+ recursive-include qaeval *
8
+ recursive-include src *
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.2
2
+ Name: plainqafact
3
+ Version: 0.1.0
4
+ Summary: A framework for evaluating plain language summaries using question answering
5
+ Home-page: https://github.com/zhiwenyou103/PlainQAFact
6
+ Author: Zhiwen You
7
+ Author-email: zhiweny2@illinois.edu
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: openai==1.64.0
17
+ Requires-Dist: bert-score==0.3.13
18
+ Requires-Dist: sentence-transformers==3.4.1
19
+ Requires-Dist: edlib==1.3.9.post1
20
+ Requires-Dist: overrides==7.7.0
21
+ Requires-Dist: spacy==3.8.3
22
+ Requires-Dist: sentencepiece==0.2.0
23
+ Requires-Dist: sacremoses==0.1.1
24
+ Requires-Dist: gdown
25
+ Requires-Dist: faiss-cpu==1.7.4
26
+ Requires-Dist: python-liquid==1.10.2
27
+ Requires-Dist: openai==0.28.0
28
+ Requires-Dist: langchain==0.0.345
29
+ Requires-Dist: tqdm==4.66.1
30
+ Requires-Dist: transformers==4.44.2
31
+ Requires-Dist: sentence_transformers==2.2.2
32
+ Requires-Dist: pyserini==0.22.1
33
+ Requires-Dist: tiktoken==0.6.0
34
+ Requires-Dist: datasets==2.16.1
35
+ Requires-Dist: torch
36
+ Requires-Dist: torchvision
37
+ Requires-Dist: torchaudio
38
+ Dynamic: author
39
+ Dynamic: author-email
40
+ Dynamic: classifier
41
+ Dynamic: description
42
+ Dynamic: description-content-type
43
+ Dynamic: home-page
44
+ Dynamic: requires-dist
45
+ Dynamic: requires-python
46
+ Dynamic: summary
47
+
48
+ # PlainQAFact
49
+
50
+ ## News
51
+ - [2025.02.24] Our PlainFact dataset can be downloaded here: [`PlainFact`](https://drive.google.com/drive/folders/1mbb06BbZWogweoxc1I5AE7I7m13qhiRL?usp=sharing), including sentence-level and summary-level granularities.
52
+ - Target_Sentence: The plain language sentence/summary.
53
+ - Original_Abstract: The scientific abstract corresponding to each sentence/summary.
54
+ - External: Whether the sentence includes information does not explicitly present in the scientific abstract. ('yes': explanation, 'no': simplification)
55
+ - [2025.02.24] Our fine-tuned Question Generation model is available on 🤗 Hugging Face: [`QG model`](https://huggingface.co/uzw/bart-large-question-generation) (or download it [here](https://drive.google.com/file/d/1-MA9dfOtCm38yTfiQN9Xm8sRvcRD_Cmc/view?usp=drive_link))
56
+
57
+ > NOTE: This repo is heavily relied on [QAFactEval](https://github.com/salesforce/QAFactEval), [QAEval](https://github.com/danieldeutsch/qaeval), and [MedRAG](https://github.com/Teddy-XiongGZ/MedRAG).
58
+
59
+
60
+ ## Overall Framework
61
+ <div align="center">
62
+ <img src="https://github.com/zhiwenyou103/PlainQAFact/blob/main/pics/system.jpg" height="500" width="750">
63
+ </div>
64
+
65
+
66
+ ## Installation
67
+
68
+ ### Option 1: Install via pip (Recommended)
69
+ ```bash
70
+ pip install plainqafact
71
+ ```
72
+
73
+ After installation, you can use PlainQAFact directly in your Python code:
74
+ ```python
75
+ from plainqafact import PlainQAFact
76
+
77
+ # Initialize the framework
78
+ qafact = PlainQAFact(
79
+ classifier_type='learned',
80
+ classifier_path='path/to/learned_classifier',
81
+ llm_model_path='meta-llama/Llama-3.1-8B-Instruct',
82
+ question_generation_model_path='uzw/bart-large-question-generation',
83
+ qa_answering_model_dir='models/answering',
84
+ knowledge_base='combined',
85
+ answer_selection_strategy='llm-keywords'
86
+ )
87
+
88
+ # Run evaluation
89
+ results = qafact.evaluate(input_file='your_data.csv')
90
+ ```
91
+
92
+ ### Option 2: Install from source
93
+ - First, create a new conda env: `conda create -n plainqafact python=3.9` and clone our repo.
94
+ - `cd PlainQAFact`
95
+ - Follow the instructions in [MedRAG](https://github.com/Teddy-XiongGZ/MedRAG?tab=readme-ov-file#requirements) to install PyTorch and other required packages.
96
+ - Then, run the following command:
97
+ ```bash
98
+ conda install git
99
+ pip install -r requirements.txt
100
+ ```
101
+ - Finally, install the old tokenizer package through:
102
+ ```bash
103
+ pip install transformers_old_tokenizer-3.1.0-py3-none-any.whl
104
+ ```
105
+
106
+ ## Model Downloading
107
+ In PlainQAFact, we use [`Llama 3.1 8B Instruct`](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct) for answer extraction, fine-tuned [`QG model`](https://huggingface.co/uzw/bart-large-question-generation), and the original question answering model from [QAFactEval](https://github.com/salesforce/QAFactEval).
108
+
109
+ Download the pre-trained QA model and our pre-trained classifier through `bash download_question_answering.sh`.
110
+
111
+
112
+ ## Usage of PlainQAFact
113
+ ### Running through our PlainFact dataset
114
+ Before running the following command, please download the question answering and learned classifier models through above instructions.
115
+ ```bash
116
+ python3 run.py \
117
+ --classifier_type learned \ # Options: 'learned', 'llama', 'gpt'
118
+ --input_file data/summary_level.csv \ # path of the input dataset
119
+ --classifier_path path/to/learned_classifier \ # path of the classifier
120
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \ # path of the answer extractor
121
+ --question_generation_model_path uzw/bart-large-question-generation \ # path of the question generation model
122
+ --qa_answering_model_dir models/answering \ # path of the question answering model
123
+ --knowledge_base combined \ # knowledge bases for retrieval
124
+ --answer_selection_strategy llm-keywords # Options: 'llm-keywords', 'gpt-keywords', 'none'
125
+ ```
126
+
127
+ ### Running through your own data
128
+ Please modify the [`default_config.py`](https://github.com/zhiwenyou103/PlainQAFact/blob/main/default_config.py#L17) file `Line 17-19` to indicate the heading/key names of your dataset. We currently support `.json`, `.txt`, and `.csv` file.
129
+ ```bash
130
+ python3 run.py \
131
+ --classifier_type learned \
132
+ --input_file your_own_data.json \
133
+ --input_file_format json \
134
+ --classifier_path path/to/learned_classifier \
135
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \
136
+ --question_generation_model_path uzw/bart-large-question-generation \
137
+ --qa_answering_model_dir models/answering \
138
+ --knowledge_base textbooks \
139
+ --answer_selection_strategy llm-keywords
140
+ ```
141
+
142
+ ### Easily replace the pre-trained classifier to OpenAI models or your own
143
+ We provides options to easily replace our pre-trained classisifer tailored for the biomedical plain language summarization tasks to other tasks. You may simply set `--classifier_type` as `gpt` and provide your OpenAI API key in the [`default_config.py`](https://github.com/zhiwenyou103/PlainQAFact/blob/main/default_config.py#L26) file `Line 26` to run PlainQAFact.
144
+ ```bash
145
+ python3 run.py \
146
+ --classifier_type gpt \
147
+ --input_file your_own_data.json \
148
+ --input_file_format json \
149
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \
150
+ --question_generation_model_path uzw/bart-large-question-generation \
151
+ --qa_answering_model_dir models/answering \
152
+ --knowledge_base textbooks \
153
+ --answer_selection_strategy llm-keywords
154
+ ```
155
+
156
+ ### Using other Knowledge Bases for retrieval
157
+ Currently, we only experiment with two KBs: Textbooks and StatPearls. You may want to use your customized KBs for more accurate retrieval. In PlainQAFact, we combine both Textbooks and StatPearls and concatenate with the scientific abstracts. Set `--knowledge_base textbooks` as `combined` to reproduce our results.
158
+
159
+
160
+ > NOTE: Using Llama 3.1 8B model for both classification and answer extraction would take over 40 GB GPU memory. We recommend to use our pre-trained classifier or OpenAI models for classification if the GPU memory is limited.
161
+
162
+
163
+ ## Citation Information
164
+ For the use of PlainQAFact and PlainFact benchmark, please cite:
165
+
166
+ ## Contact Information
167
+ If you have any questions, please email `zhiweny2@illinois.edu`.
@@ -0,0 +1,120 @@
1
+ # PlainQAFact
2
+
3
+ ## News
4
+ - [2025.02.24] Our PlainFact dataset can be downloaded here: [`PlainFact`](https://drive.google.com/drive/folders/1mbb06BbZWogweoxc1I5AE7I7m13qhiRL?usp=sharing), including sentence-level and summary-level granularities.
5
+ - Target_Sentence: The plain language sentence/summary.
6
+ - Original_Abstract: The scientific abstract corresponding to each sentence/summary.
7
+ - External: Whether the sentence includes information does not explicitly present in the scientific abstract. ('yes': explanation, 'no': simplification)
8
+ - [2025.02.24] Our fine-tuned Question Generation model is available on 🤗 Hugging Face: [`QG model`](https://huggingface.co/uzw/bart-large-question-generation) (or download it [here](https://drive.google.com/file/d/1-MA9dfOtCm38yTfiQN9Xm8sRvcRD_Cmc/view?usp=drive_link))
9
+
10
+ > NOTE: This repo is heavily relied on [QAFactEval](https://github.com/salesforce/QAFactEval), [QAEval](https://github.com/danieldeutsch/qaeval), and [MedRAG](https://github.com/Teddy-XiongGZ/MedRAG).
11
+
12
+
13
+ ## Overall Framework
14
+ <div align="center">
15
+ <img src="https://github.com/zhiwenyou103/PlainQAFact/blob/main/pics/system.jpg" height="500" width="750">
16
+ </div>
17
+
18
+
19
+ ## Installation
20
+
21
+ ### Option 1: Install via pip (Recommended)
22
+ ```bash
23
+ pip install plainqafact
24
+ ```
25
+
26
+ After installation, you can use PlainQAFact directly in your Python code:
27
+ ```python
28
+ from plainqafact import PlainQAFact
29
+
30
+ # Initialize the framework
31
+ qafact = PlainQAFact(
32
+ classifier_type='learned',
33
+ classifier_path='path/to/learned_classifier',
34
+ llm_model_path='meta-llama/Llama-3.1-8B-Instruct',
35
+ question_generation_model_path='uzw/bart-large-question-generation',
36
+ qa_answering_model_dir='models/answering',
37
+ knowledge_base='combined',
38
+ answer_selection_strategy='llm-keywords'
39
+ )
40
+
41
+ # Run evaluation
42
+ results = qafact.evaluate(input_file='your_data.csv')
43
+ ```
44
+
45
+ ### Option 2: Install from source
46
+ - First, create a new conda env: `conda create -n plainqafact python=3.9` and clone our repo.
47
+ - `cd PlainQAFact`
48
+ - Follow the instructions in [MedRAG](https://github.com/Teddy-XiongGZ/MedRAG?tab=readme-ov-file#requirements) to install PyTorch and other required packages.
49
+ - Then, run the following command:
50
+ ```bash
51
+ conda install git
52
+ pip install -r requirements.txt
53
+ ```
54
+ - Finally, install the old tokenizer package through:
55
+ ```bash
56
+ pip install transformers_old_tokenizer-3.1.0-py3-none-any.whl
57
+ ```
58
+
59
+ ## Model Downloading
60
+ In PlainQAFact, we use [`Llama 3.1 8B Instruct`](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct) for answer extraction, fine-tuned [`QG model`](https://huggingface.co/uzw/bart-large-question-generation), and the original question answering model from [QAFactEval](https://github.com/salesforce/QAFactEval).
61
+
62
+ Download the pre-trained QA model and our pre-trained classifier through `bash download_question_answering.sh`.
63
+
64
+
65
+ ## Usage of PlainQAFact
66
+ ### Running through our PlainFact dataset
67
+ Before running the following command, please download the question answering and learned classifier models through above instructions.
68
+ ```bash
69
+ python3 run.py \
70
+ --classifier_type learned \ # Options: 'learned', 'llama', 'gpt'
71
+ --input_file data/summary_level.csv \ # path of the input dataset
72
+ --classifier_path path/to/learned_classifier \ # path of the classifier
73
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \ # path of the answer extractor
74
+ --question_generation_model_path uzw/bart-large-question-generation \ # path of the question generation model
75
+ --qa_answering_model_dir models/answering \ # path of the question answering model
76
+ --knowledge_base combined \ # knowledge bases for retrieval
77
+ --answer_selection_strategy llm-keywords # Options: 'llm-keywords', 'gpt-keywords', 'none'
78
+ ```
79
+
80
+ ### Running through your own data
81
+ Please modify the [`default_config.py`](https://github.com/zhiwenyou103/PlainQAFact/blob/main/default_config.py#L17) file `Line 17-19` to indicate the heading/key names of your dataset. We currently support `.json`, `.txt`, and `.csv` file.
82
+ ```bash
83
+ python3 run.py \
84
+ --classifier_type learned \
85
+ --input_file your_own_data.json \
86
+ --input_file_format json \
87
+ --classifier_path path/to/learned_classifier \
88
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \
89
+ --question_generation_model_path uzw/bart-large-question-generation \
90
+ --qa_answering_model_dir models/answering \
91
+ --knowledge_base textbooks \
92
+ --answer_selection_strategy llm-keywords
93
+ ```
94
+
95
+ ### Easily replace the pre-trained classifier to OpenAI models or your own
96
+ We provides options to easily replace our pre-trained classisifer tailored for the biomedical plain language summarization tasks to other tasks. You may simply set `--classifier_type` as `gpt` and provide your OpenAI API key in the [`default_config.py`](https://github.com/zhiwenyou103/PlainQAFact/blob/main/default_config.py#L26) file `Line 26` to run PlainQAFact.
97
+ ```bash
98
+ python3 run.py \
99
+ --classifier_type gpt \
100
+ --input_file your_own_data.json \
101
+ --input_file_format json \
102
+ --llm_model_path meta-llama/Llama-3.1-8B-Instruct \
103
+ --question_generation_model_path uzw/bart-large-question-generation \
104
+ --qa_answering_model_dir models/answering \
105
+ --knowledge_base textbooks \
106
+ --answer_selection_strategy llm-keywords
107
+ ```
108
+
109
+ ### Using other Knowledge Bases for retrieval
110
+ Currently, we only experiment with two KBs: Textbooks and StatPearls. You may want to use your customized KBs for more accurate retrieval. In PlainQAFact, we combine both Textbooks and StatPearls and concatenate with the scientific abstracts. Set `--knowledge_base textbooks` as `combined` to reproduce our results.
111
+
112
+
113
+ > NOTE: Using Llama 3.1 8B model for both classification and answer extraction would take over 40 GB GPU memory. We recommend to use our pre-trained classifier or OpenAI models for classification if the GPU memory is limited.
114
+
115
+
116
+ ## Citation Information
117
+ For the use of PlainQAFact and PlainFact benchmark, please cite:
118
+
119
+ ## Contact Information
120
+ If you have any questions, please email `zhiweny2@illinois.edu`.
@@ -0,0 +1 @@
1
+ Your downloaded model will be shown here.
@@ -0,0 +1,8 @@
1
+
2
+ __version__ = '0.1.0'
3
+
4
+ from .plainqafact import PlainQAFact
5
+ from .classifier import Classifier
6
+ from .default_config import DefaultConfig
7
+
8
+ __all__ = ['PlainQAFact', 'Classifier', 'DefaultConfig']
@@ -0,0 +1,41 @@
1
+ from typing import Dict, List, Set
2
+ import bert_score
3
+ import numpy as np
4
+ from qaeval.scoring.scorers.scorer import Scorer
5
+
6
+ class BertScoreScorer(Scorer):
7
+ def __init__(self, cuda_device: int, batch_size: int = 8) -> None:
8
+ self.device = f'cuda:{cuda_device}' if cuda_device >= 0 else 'cpu'
9
+ self.batch_size = batch_size
10
+
11
+ def keys(self) -> Set[str]:
12
+ return {'bertscore'}
13
+
14
+ def _score_single_ref(
15
+ self,
16
+ context: str,
17
+ questions: List[str],
18
+ answers: List[str],
19
+ predictions: List[str],
20
+ probabilities: List[float],
21
+ null_probabilities: List[float]
22
+ ) -> List[Dict[str, float]]:
23
+ indices = []
24
+ valid_answers = []
25
+ valid_predictions = []
26
+
27
+ for i, (answer, prediction, probability, null_probability) in \
28
+ enumerate(zip(answers, predictions, probabilities, null_probabilities)):
29
+ if probability > null_probability:
30
+ valid_answers.append(answer)
31
+ valid_predictions.append(prediction)
32
+ indices.append(i)
33
+
34
+ scores = [0.0] * len(questions)
35
+ if valid_predictions:
36
+ _, _, F1 = bert_score.score(valid_predictions, valid_answers,
37
+ lang="en", device=self.device)
38
+ for idx, score in zip(indices, F1.tolist()):
39
+ scores[idx] = score
40
+
41
+ return [{'bertscore': s} for s in scores]
@@ -0,0 +1,113 @@
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import re
4
+ from transformers import pipeline
5
+ from openai import OpenAI
6
+
7
+ class LearnedClassifier:
8
+ def __init__(self, model_path, device):
9
+ self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
10
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
11
+ self.model = AutoModelForSequenceClassification.from_pretrained(model_path, use_safetensors=True)
12
+ self.model.to(self.device)
13
+ self.model.eval()
14
+
15
+ def predict(self, abstract, sentence, return_probability=False):
16
+ encoding = self.tokenizer.encode_plus(
17
+ text=abstract,
18
+ text_pair=sentence,
19
+ add_special_tokens=True,
20
+ max_length=512,
21
+ padding='max_length',
22
+ truncation=True,
23
+ return_attention_mask=True,
24
+ return_tensors='pt'
25
+ )
26
+
27
+ input_ids = encoding['input_ids'].to(self.device)
28
+ attention_mask = encoding['attention_mask'].to(self.device)
29
+
30
+ with torch.no_grad():
31
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
32
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
33
+
34
+ predicted_class = torch.argmax(probabilities, dim=1).item()
35
+ probabilities = probabilities[0].cpu().numpy()
36
+
37
+ label = 'yes' if predicted_class == 1 else 'no'
38
+
39
+ if return_probability:
40
+ return label, {'no': probabilities[0], 'yes': probabilities[1]}
41
+ else:
42
+ confidence = probabilities[predicted_class]
43
+ return label, confidence
44
+
45
+
46
+ class LLMClassifier:
47
+ def __init__(self, classifier_type: str, model_path: str = None, device: int = None, openai_key: str = None):
48
+ self.max_tokens = 512
49
+ self.classifier_type = classifier_type
50
+
51
+ if classifier_type == 'llama':
52
+ self.generator = pipeline(
53
+ "text-generation",
54
+ model=model_path,
55
+ device=device
56
+ )
57
+ elif classifier_type == 'gpt':
58
+ self.client = OpenAI(api_key=openai_key)
59
+
60
+ def predict(self, abstract: str, sentence: str) -> tuple:
61
+ if self.classifier_type == 'llama':
62
+ label = self.llama_classifier(sentence, abstract)
63
+ else:
64
+ label = self.gpt_classifier(sentence, abstract)
65
+
66
+ confidence = 1.0 # placeholder
67
+ return label, confidence
68
+
69
+ def gpt_classifier(self, summary: str, abstract: str) -> str:
70
+ response = self.client.chat.completions.create(
71
+ model="gpt-4o-2024-11-20",
72
+ messages=[
73
+ {"role": "developer",
74
+ "content": "Annotate whether a sentence or summary includes information not present in the original abstract. \n The sentence or summary contains external information that is not explicitly mentioned, paraphrased, or implied in the original abstract will be labeled as 'Yes'. \n The sentence or summary contains information that is explicitly stated or closely paraphrased from the original abstract will be labeled as 'No'."},
75
+ {"role": "user",
76
+ "content": "Sentence or summary: " + summary + "\n Original abstract: " + abstract},
77
+ ],
78
+ max_tokens=self.max_tokens,
79
+ temperature=0,
80
+ )
81
+ if response.choices[0].message.content == '':
82
+ print('empty')
83
+ result = 'Yes'
84
+ else:
85
+ result = response.choices[0].message.content
86
+ result = re.sub(r'[^a-zA-Z0-9\s]', '', result)
87
+
88
+ return result.lower().strip()
89
+
90
+ def llama_classifier(self, summary: str, abstract: str) -> str:
91
+ messages = [
92
+ {"role": "system",
93
+ "content": "Annotate whether a summary includes information not present in the original abstract. \n The summary contains external information that is not explicitly mentioned, paraphrased, or implied in the original abstract will be labeled as 'Yes'. \n The summary contains information that is explicitly stated or closely paraphrased from the original abstract will be labeled as 'No'."},
94
+ {"role": "user",
95
+ "content": "Summary: " + summary + "\n Original abstract: " + abstract + "\n Your annotation: "}
96
+ ]
97
+
98
+ outputs = self.generator(messages, do_sample=True, temperature=0.01, max_new_tokens=self.max_tokens)
99
+ generated_text = outputs[0]['generated_text'][-1]['content']
100
+
101
+ pattern = r'annotation is:\s*(Yes|No)\b'
102
+ match = re.search(pattern, generated_text, flags=re.IGNORECASE)
103
+ if match:
104
+ final_answer = match.group(1)
105
+ else:
106
+ match = re.search(r'(Yes|No)\s*$', generated_text, flags=re.IGNORECASE)
107
+ if match:
108
+ final_answer = match.group(1)
109
+ else:
110
+ print("empty")
111
+ final_answer = 'Yes'
112
+
113
+ return final_answer.lower().strip()