├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── assets
└── imgs
│ ├── docker_build.gif
│ ├── medichatbot.gif
│ ├── medichatbot.png
│ ├── medichatbot_walle.png
│ ├── streamlit1.gif
│ ├── streamlit2.gif
│ ├── streamlit3.png
│ └── streamlit_app2.gif
├── chatbot.py
├── docker-compose.yml
├── dockerfile
├── main.py
├── modules
├── __init__.py
└── chatbot
│ ├── config.py
│ ├── const.py
│ ├── dataloader.py
│ ├── inferencer.py
│ └── preprocessor.py
├── requirements.txt
└── scripts
├── 01.chatgpt_api_app_example.py
└── 99.tester.ipynb
/.gitattributes:
--------------------------------------------------------------------------------
1 | question_extractor_model/** filter=lfs diff=lfs merge=lfs -text
2 | C:/Users/parkm/Desktop/git/medical-chatbot-GPT2/question_extractor_model/variables/variables.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /notebooks
2 |
3 |
4 |
5 | /notebooks/*
6 |
7 |
8 |
9 | # Byte-compiled / optimized / DLL files
10 | __pycache__/
11 | *.py[cod]
12 | *$py.class
13 |
14 | # C extensions
15 | *.so
16 |
17 | # Distribution / packaging
18 | .Python
19 | build/
20 | develop-eggs/
21 | dist/
22 | downloads/
23 | eggs/
24 | .eggs/
25 | lib/
26 | lib64/
27 | parts/
28 | sdist/
29 | var/
30 | wheels/
31 | pip-wheel-metadata/
32 | share/python-wheels/
33 | *.egg-info/
34 | .installed.cfg
35 | *.egg
36 | MANIFEST
37 |
38 | # PyInstaller
39 | # Usually these files are written by a python script from a template
40 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
41 | *.manifest
42 | *.spec
43 |
44 | # Installer logs
45 | pip-log.txt
46 | pip-delete-this-directory.txt
47 |
48 | # Unit test / coverage reports
49 | htmlcov/
50 | .tox/
51 | .nox/
52 | .coverage
53 | .coverage.*
54 | .cache
55 | nosetests.xml
56 | coverage.xml
57 | *.cover
58 | *.py,cover
59 | .hypothesis/
60 | .pytest_cache/
61 |
62 | # Translations
63 | *.mo
64 | *.pot
65 |
66 | # Django stuff:
67 | *.log
68 | local_settings.py
69 | db.sqlite3
70 | db.sqlite3-journal
71 |
72 | # Flask stuff:
73 | instance/
74 | .webassets-cache
75 |
76 | # Scrapy stuff:
77 | .scrapy
78 |
79 | # Sphinx documentation
80 | docs/_build/
81 |
82 | # PyBuilder
83 | target/
84 |
85 | # Jupyter Notebook
86 | .ipynb_checkpoints
87 |
88 | # IPython
89 | profile_default/
90 | ipython_config.py
91 |
92 | # pyenv
93 | .python-version
94 |
95 | # pipenv
96 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
98 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
99 | # install all needed dependencies.
100 | #Pipfile.lock
101 |
102 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
103 | __pypackages__/
104 |
105 | # Celery stuff
106 | celerybeat-schedule
107 | celerybeat.pid
108 |
109 | # SageMath parsed files
110 | *.sage.py
111 |
112 | # Environments
113 | .env
114 | .venv
115 | env/
116 | venv/
117 | ENV/
118 | env.bak/
119 | venv.bak/
120 |
121 | # Spyder project settings
122 | .spyderproject
123 | .spyproject
124 |
125 | # Rope project settings
126 | .ropeproject
127 |
128 | # mkdocs documentation
129 | /site
130 |
131 | # mypy
132 | .mypy_cache/
133 | .dmypy.json
134 | dmypy.json
135 |
136 | # Pyre type checker
137 | .pyre/
138 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Development Status :: 3 - Alpha
2 | *Copyright (c) 2023 MinWoo Park*
3 |
4 |
5 | # GPT-BERT Medical QA Chatbot
6 | [](code_of_conduct.md)
7 | [](code_of_conduct.md)
8 | 
9 | 
10 |
11 | > **Be careful when cloning this repository**: It contains large NLP model weight. (>0.45GB, [`git-lfs`](https://git-lfs.com/))
12 | > If you want to clone without git-lfs, use this command before `git clone`. *The bandwidth provided by git-lfs for free is only 1GB per month, so there is almost no chance that a 0.45GB git-lfs download will work. So please download it manually.*
13 | ```
14 | git lfs install --skip-smudge &
15 | export GIT_LFS_SKIP_SMUDGE=1
16 | ```
17 |
18 | [](https://github.com/DSDanielPark/medical-qa-bert-chatgpt/blob/main/assets/imgs/medichatbot_walle.png)
19 |
20 | Since the advent of Chat GPT-4, there have been significant changes in the field. Nevertheless, Chat GPT-2 and Chat GPT-3 continue to be effective in specific domains as large-scale auto-regressive natural language processing models. This repository aims to qualitatively compare the performance of Chat GPT-2 and Chat GPT-4 in the medical domain, and estimate the resources and costs needed for Chat GPT-2 fine-tuning to reach the performance level of Chat GPT-4. Additionally, it seeks to assess how well up-to-date information can be incorporated and applied.
21 |
22 | Although a few years behind GPT-4, the ultimate goal of this repository is to minimize costs and resources required for updating and obtaining usable weights after acquiring them. We plan to design experiments for few-shot learning in large-scale natural language processing models and test existing research. Please note that this repository is intended for research and practice purposes only, and we do not assume responsibility for any usage.
23 |
24 | Additionally, this repository ultimately aims to achieve similar qualitative and quantitative performance as GPT-4 in certain domain areas through model lightweighting and optimization. For more details, please refer to my technical blog.
25 |
26 | *Keywords: GPT-2, Streamlit, Vector DB, Medical*
27 |
28 |
29 |
30 | # Contents
31 | - [GPT-BERT Medical QA Chatbot](#gpt-bert-medical-qa-chatbot)
32 | - [Contents](#contents)
33 | - [Quick Start](#quick-start)
34 | - [Command-Line Interface](#command-line-interface)
35 | - [Streamlit application](#streamlit-application)
36 | - [Docker](#docker)
37 | - [Build from Docker Image](#build-from-docker-image)
38 | - [Build from Docker Compose](#build-from-docker-compose)
39 | - [Build from Docker Hub](#build-from-docker-hub)
40 | - [Pre-trained model infomation](#pre-trained-model-infomation)
41 | - [Dataset](#dataset)
42 | - [Pretrained Models](#pretrained-models)
43 | - [Cites](#cites)
44 | - [How to cite this project](#how-to-cite-this-project)
45 | - [Tips](#tips)
46 | - [About data handling](#about-data-handling)
47 | - [About Tensorflow-GPU handling](#about-tensorflow-gpu-handling)
48 | - [Remark](#remark)
49 | - [References](#references)
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | # Quick Start
59 | ## Command-Line Interface
60 | You can chat with the chatbot through the command-line interface using the following command.
61 | 
62 | ```
63 | git clone https://github.com/DSDanielPark/medical-qa-bert-chatgpt.git
64 | cd medical-qa-bert-chatgpt
65 | pip install -e .
66 | python main.py
67 | ```
68 | 
69 |
70 |
71 |
72 | ## Streamlit application
73 | A simple application can be implemented with streamlit as follows:
74 | 
75 | ```
76 | git clone https://github.com/DSDanielPark/medical-qa-bert-chatgpt.git
77 | cd medical-qa-bert-chatgpt
78 | pip install -e .
79 | streamlit run chatbot.py
80 | ```
81 |
82 |
83 | # Docker
84 | Check Docker Hub: https://hub.docker.com/r/parkminwoo91/medical-chatgpt-streamlit-v1
85 | Docker version 20.10.24, build 297e128
86 |
87 | ## Build from Docker Image
88 | ```
89 | git clone https://github.com/DSDanielPark/medical-qa-bert-chatgpt.git
90 | cd medical-qa-bert-chatgpt
91 | docker build -t chatgpt .
92 | docker run -p 8501:8501 -v ${PWD}/:/usr/src/app/data chatgpt # There is no cost to pay for git-lfs, just download and mount it.
93 | ```
94 | ##### Since git clone downloads what needs to be downloaded from git-lfs, the volume must be mounted as follows. Or modify `chatbot/config.py` to mount to a different folder.
95 |
96 | ## Build from Docker Compose
97 | You can also implement it in a docker container like this:
98 | 
99 | ```
100 | git clone https://github.com/DSDanielPark/medical-qa-bert-chatgpt.git
101 | cd medical-qa-bert-chatgpt
102 |
103 | docker compose up
104 | ```
105 |
106 | ## Build from Docker Hub
107 |
108 | ```
109 | docker pull parkminwoo91/medical-chatgpt-streamlit-v1:latest
110 | docker compose up
111 | ```
112 | http://localhost:8501/
113 |
114 | ###### Streamlit is very convenient and quick to view landing pages, but lacks design flexibility and lacks control over the application layout. Also, if your application or data set is large, the entire source code will be re-run on every new change or interaction, so application flow can cause speed issues. That landing page will be replaced by flask with further optimizations. Streamlit chatbot has been recently developed, so it seems difficult to have the meaning of a simple demo now.
115 |
116 | ## Pre-trained model infomation
117 | `Pre-trained model weight needed`
118 | Downloading datasets and model weights through the Hugging Face Hub is executed, but for some TensorFlow models, you need to manually download and place them at the top of the project folder. The information for the downloadable model is as follows, and you can visit my Hugging Face repository to check it.
119 |
120 | `modules/chatbot/config.py`
121 | ```python
122 | class Config:
123 | chat_params = {"gpt_tok":"danielpark/medical-QA-chatGPT2-tok-v1",
124 | "tf_gpt_model":"danielpark/medical-QA-chatGPT2-v1",
125 | "bert_tok":"danielpark/medical-QA-BioRedditBERT-uncased-v1",
126 | "tf_q_extractor": "question_extractor_model",
127 | "data":"danielpark/MQuAD-v1",
128 | "max_answer_len": 20,
129 | "isEval": False,
130 | "runDocker":True, # Exceeds the bandwidth of git-lfs, mounts to local storage to find folder location for free use. I use the python utifunction package.
131 | "container_mounted_folder_path": "/usr/src/app/data"}
132 | ```
133 |
134 |
135 |
136 | # Dataset
137 | The Medical Question and Answering dataset(MQuAD) has been refined, including the following datasets. You can download it through the Hugging Face dataset. Use the DATASETS method as follows. You can find more infomation at [here.](https://huggingface.co/datasets/danielpark/MQuAD-v1)
138 |
139 | ```python
140 | from datasets import load_dataset
141 | dataset = load_dataset("danielpark/MQuAD-v1")
142 | ```
143 |
144 | Medical Q/A datasets gathered from the following websites.
145 | - eHealth Forum
146 | - iCliniq
147 | - Question Doctors
148 | - WebMD
149 | Data was gathered at the 5th of May 2017.
150 |
151 |
152 |
153 | # Pretrained Models
154 | Hugging face pretrained models
155 | - GPT2 pretrained model [[download]](https://huggingface.co/danielpark/medical-QA-chatGPT2-v1)
156 | - GPT2 tokenizer [[download]](https://huggingface.co/danielpark/medical-QA-chatGPT2-tok-v1)
157 | - BIO Reddit BERT pretrained model [[download]](https://huggingface.co/danielpark/medical-QA-BioRedditBERT-uncased-v1)
158 |
159 | TensorFlow models for extracting context from QA.
160 | I temporarily share TensorFlow model weights through my personal Google Drive.
161 | - Q extractor [[download]](https://drive.google.com/drive/folders/1VjljBW_HXXIXoh0u2Y1anPCveQCj9vnQ?usp=share_link)
162 | - A extractor [[download]](https://drive.google.com/drive/folders/1iZ6jCiZPqjsNOyVoHcagEf3hDC5H181j?usp=share_link)
163 |
164 |
165 |
166 |
167 | # Cites
168 | ```BibTex
169 | @misc {hf_canonical_model_maintainers_2022,
170 | author = { {HF Canonical Model Maintainers} },
171 | title = { gpt2 (Revision 909a290) },
172 | year = 2022,
173 | url = { https://huggingface.co/gpt2 },
174 | doi = { 10.57967/hf/0039 },
175 | publisher = { Hugging Face }
176 | }
177 |
178 | @misc{vaswani2017attention,
179 | title = {Attention Is All You Need},
180 | author = {Ashish Vaswani and Noam Shazeer and Niki Parmar and Jakob Uszkoreit and Llion Jones and Aidan N. Gomez and Lukasz Kaiser and Illia Polosukhin},
181 | year = {2017},
182 | eprint = {1706.03762},
183 | archivePrefix = {arXiv},
184 | primaryClass = {cs.CL}
185 | }
186 | ```
187 |
188 |
189 |
190 | # How to cite this project
191 | ```BibTex
192 | @misc{medical_qa_bert_chatgpt,
193 | title = {Medical QA Bert Chat GPT},
194 | author = {Minwoo Park},
195 | year = {2023},
196 | url = {https://github.com/dsdanielpark/medical-qa-bert-chatgpt},
197 | }
198 | ```
199 |
200 |
201 |
202 |
203 | # Tips
204 |
205 | ## About data handling
206 | The MQuAD provides embedded question and answer arrays in string format, so it is recommended to convert the string-formatted arrays into float format as follows. This measure has been applied to save resources and time used for embedding.
207 |
208 | ```python
209 | from datasets import load_dataset
210 | from utilfunction import col_convert
211 | import pandas as pd
212 |
213 | qa = load_dataset("danielpark/MQuAD-v1", "csv")
214 | df_qa = pd.DataFrame(qa['train'])
215 | df_qa = col_convert(df_qa, ['Q_FFNN_embeds', 'A_FFNN_embeds'])
216 | ```
217 |
218 | ## About Tensorflow-GPU handling
219 | Since the nvidia GPU driver fully supports wsl2, the method of supporting TensorFlow's gpu has changed. Please refer to the following pages to install it.
220 | - https://docs.nvidia.com/cuda/wsl-user-guide/index.html
221 | - https://www.tensorflow.org/install/pip?hl=ko
222 |
223 |
224 |
225 | ## Remark
226 | I have trained the model for 2 epochs using the mentioned dataset, utilizing 40 computing units from Google Colab Pro. The training was conducted for about 12 hours using an A100 multi-GPU with 56 GB of RAM or more. In the case of relatively simple question extractor or answer extractor models that perform summarization and indexing, the time required for training is minimal, and they are included in the inference module to evaluate whether the learning has been carried out appropriately. If the model is only responding to simple questions, the inference module should be changed;
227 | however, it is currently included in the evaluation unnecessarily to check performance and calculate the time and resources consumed. I plan to update this information once sufficient training is completed (by incorporating additional datasets), or when funding for experiments and resources to derive adequate learning.
228 |
229 | - Training 2 Epoch with `MQuAD` dataset, Comsuming 40 Google Colab Pro Computing unit, Take 12 hours using an A100 multi-GPU with 56 GB of RAM or more.
230 |
231 |
232 |
233 | # References
234 | 1. [Paper: Attention is All You Need](https://arxiv.org/abs/1706.03762)
235 | 2. [Paper: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)
236 | 3. [Paper: GPT-2: Language Models are Unsupervised Multitask Learners](https://arxiv.org/ftp/arxiv/papers/1901/1901.08746.pdf)
237 | 4. [Paper: Language Models are Unsupervised Multitask Learners](https://d4mucfpksywv.cloudfront.net/better-language-models/languagemodels.pdf%C2%A0)
238 | 5. [GitHub Repository: DocProduct](https://github.com/ash3n/DocProduct#start-of-content)
239 | 6. [Applied AI Course](https://appliedaicourse.com)
240 | 7. [Medium Article: Medical Chatbot using BERT and GPT-2](https://suniljammalamadaka.medium.com/medical-chatbot-using-bert-and-gpt2-62f0c973162f)
241 | 8. [GitHub Repository: Medical Question Answer Data](https://github.com/LasseRegin/medical-question-answer-data)
242 | 9. [Hugging Face Model Hub: GPT-2](https://huggingface.co/gpt2)
243 | 10. [GitHub Repository: Streamlit Chat](https://github.com/AI-Yash/st-chat)
244 | 11. [Streamlit Documentation](https://streamlit.io/)
245 | 12. [Streamlit Tutorial: Deploying Streamlit Apps with Docker](https://docs.streamlit.io/knowledge-base/tutorials/deploy/docker)
246 | 13. [ChatterBot Documentation](https://chatterbot.readthedocs.io/en/stable/logic/index.html)
247 | 14. [Blog Post: 3 Steps to Fix App Memory Leaks](https://blog.streamlit.io/3-steps-to-fix-app-memory-leaks/)
248 | 15. [Blog Post: Common App Problems & Resource Limits](https://blog.streamlit.io/common-app-problems-resource-limits/)
249 | 16. [GitHub Gist: Streamlit Chatbot Example](https://gist.github.com/DSDanielPark/5d34b2f53709a7007b0d3a5e9f23c0a6) (Lightweight and optimized)
250 | 17. [Databricks Blog: Democratizing Magic: ChatGPT and Open Models](https://www.databricks.com/blog/2023/03/24/hello-dolly-democratizing-magic-chatgpt-open-models.html)
251 | 18. [GitHub Repository: Pyllama](https://github.com/juncongmoo/pyllama)
--------------------------------------------------------------------------------
/assets/imgs/docker_build.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/docker_build.gif
--------------------------------------------------------------------------------
/assets/imgs/medichatbot.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/medichatbot.gif
--------------------------------------------------------------------------------
/assets/imgs/medichatbot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/medichatbot.png
--------------------------------------------------------------------------------
/assets/imgs/medichatbot_walle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/medichatbot_walle.png
--------------------------------------------------------------------------------
/assets/imgs/streamlit1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/streamlit1.gif
--------------------------------------------------------------------------------
/assets/imgs/streamlit2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/streamlit2.gif
--------------------------------------------------------------------------------
/assets/imgs/streamlit3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/streamlit3.png
--------------------------------------------------------------------------------
/assets/imgs/streamlit_app2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/assets/imgs/streamlit_app2.gif
--------------------------------------------------------------------------------
/chatbot.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import tensorflow as tf
3 | from streamlit_chat import message
4 | from transformers import GPT2Tokenizer, TFGPT2LMHeadModel, AutoTokenizer
5 | from modules.chatbot.inferencer import Inferencer
6 | from modules.chatbot.dataloader import get_bert_index, get_dataset
7 | from modules.chatbot.config import Config as CONF
8 | from utilfunction import find_path
9 |
10 | # Streamlit App
11 | st.header("GPT-BERT-Medical-QA-Chatbot")
12 |
13 | # Load necessary models and data
14 | gpt2_tokenizer = GPT2Tokenizer.from_pretrained(CONF.chat_params["gpt_tok"])
15 | medi_qa_chatGPT2 = TFGPT2LMHeadModel.from_pretrained(CONF.chat_params["tf_gpt_model"])
16 | biobert_tokenizer = AutoTokenizer.from_pretrained(CONF.chat_params["bert_tok"])
17 | df_qa = get_dataset(CONF.chat_params["data"])
18 | max_answer_len = CONF.chat_params["max_answer_len"]
19 | isEval = CONF.chat_params["isEval"]
20 | answer_index = get_bert_index(df_qa, "A_FFNN_embeds")
21 |
22 |
23 | # Load question extractor model
24 | @st.cache_resource
25 | def load_tf_model(path):
26 | return tf.keras.models.load_model(path)
27 |
28 |
29 | try:
30 | if CONF.chat_params["runDocker"]:
31 | tf_q_extractor_path = find_path(
32 | CONF.chat_params["container_mounted_folder_path"],
33 | "folder",
34 | "question_extractor_model",
35 | )
36 | question_extractor_model_v1 = load_tf_model(tf_q_extractor_path[0])
37 | else:
38 | question_extractor_model_v1 = load_tf_model(CONF.chat_params["tf_q_extractor"])
39 | except Exception as e:
40 | tf_q_extractor_path = find_path("./", "folder", "question_extractor_model")
41 | question_extractor_model_v1 = load_tf_model(tf_q_extractor_path[0])
42 |
43 | # Initialize chatbot inferencer
44 | chatbot = Inferencer(
45 | medi_qa_chatGPT2,
46 | biobert_tokenizer,
47 | gpt2_tokenizer,
48 | question_extractor_model_v1,
49 | df_qa,
50 | answer_index,
51 | max_answer_len,
52 | )
53 |
54 |
55 | # Function to get model's answer
56 | def get_model_answer(chatbot, user_input):
57 | return chatbot.run(user_input, isEval)
58 |
59 |
60 | # Function to interact with chatbot
61 | def chatgpt(input, history):
62 | history = history or []
63 | output = get_model_answer(chatbot, input)
64 | history.append(output)
65 | return history
66 |
67 |
68 | # Maintain user input history
69 | history_input = []
70 | if "generated" not in st.session_state:
71 | st.session_state["generated"] = []
72 | if "past" not in st.session_state:
73 | st.session_state["past"] = []
74 |
75 |
76 | # Function to get user input
77 | def get_text():
78 | input_text = st.text_input("You: ", key="input")
79 | return input_text
80 |
81 |
82 | # Main interaction loop
83 | user_input = get_text()
84 |
85 | if user_input:
86 | output = chatgpt(user_input, history_input)
87 | history_input.append(output)
88 | st.session_state.past.append(user_input)
89 | st.session_state.generated.append(output[0])
90 |
91 | if st.session_state["generated"]:
92 | for i in range(len(st.session_state["generated"]) - 1, -1, -1):
93 | message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
94 | message(
95 | st.session_state["past"][i],
96 | is_user=True,
97 | key=str(i) + "_user",
98 | avatar_style="thumbs",
99 | )
100 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '1.0'
2 |
3 | services:
4 | app:
5 | build:
6 | dockerfile: dockerfile
7 | ports:
8 | - '8501:8501'
9 | volumes:
10 | - './:/usr/src/app/data'
11 | environment:
12 | - USER_ID=1000
13 | - GROUP_ID=1000
14 |
15 | image: parkminwoo91/medical-chatgpt-streamlit-v1:latest
--------------------------------------------------------------------------------
/dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.9-slim
2 |
3 | WORKDIR /app
4 |
5 | RUN pip install --upgrade setuptools
6 | RUN pip install --upgrade pip
7 |
8 | RUN apt-get update && apt-get install -y \
9 | build-essential \
10 | curl \
11 | software-properties-common \
12 | git \
13 | && rm -rf /var/lib/apt/lists/*
14 |
15 | RUN pip install --upgrade pip
16 |
17 | RUN git clone https://github.com/DSDanielPark/GPT-BERT-Medical-QA-Chatbot.git .
18 |
19 | RUN pip3 install -r requirements.txt
20 |
21 | EXPOSE 8501
22 |
23 | HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
24 |
25 | ENTRYPOINT ["streamlit", "run", "chatbot.py", "--server.port=8501", "--server.address=0.0.0.0"]
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | from transformers import GPT2Tokenizer, TFGPT2LMHeadModel, AutoTokenizer, TFAutoModel
3 | from modules.chatbot.inferencer import Inferencer
4 | from modules.chatbot.dataloader import convert, get_bert_index, get_dataset
5 | from modules.chatbot.config import Config as CONF
6 | from colorama import Fore, Back, Style
7 | import warnings
8 | import logging
9 |
10 | warnings.filterwarnings("ignore")
11 | logging.basicConfig(level=logging.CRITICAL)
12 |
13 |
14 | def main():
15 | # Load the chatbot model from the config.
16 | gpt2_tokenizer = GPT2Tokenizer.from_pretrained(CONF.chat_params["gpt_tok"])
17 | medi_qa_chatGPT2 = TFGPT2LMHeadModel.from_pretrained(
18 | CONF.chat_params["tf_gpt_model"]
19 | )
20 | biobert_tokenizer = AutoTokenizer.from_pretrained(CONF.chat_params["bert_tok"])
21 | try:
22 | question_extractor_model_v1 = tf.keras.models.load_model(
23 | CONF.chat_params["tf_q_extractor"]
24 | )
25 | except Exception as e:
26 | print(e)
27 |
28 | df_qa = get_dataset(CONF.chat_params["data"])
29 | max_answer_len = CONF.chat_params["max_answer_len"]
30 | isEval = CONF.chat_params["isEval"]
31 |
32 | # Get answer index from Answer from FFNN embedding column.
33 | answer_index = get_bert_index(df_qa, "A_FFNN_embeds")
34 |
35 | # Make chatbot inference object
36 | cahtbot = Inferencer(
37 | medi_qa_chatGPT2,
38 | biobert_tokenizer,
39 | gpt2_tokenizer,
40 | question_extractor_model_v1,
41 | df_qa,
42 | answer_index,
43 | max_answer_len,
44 | )
45 |
46 | # Start chatbot
47 | print("========================================")
48 | print(Back.BLUE + " Welcome to MediChatBot " + Back.RESET)
49 | print("========================================")
50 | print("If you enter quit, q, stop, chat will be ended.")
51 | print(
52 | "MediChatBot v1 is not an official service and is not responsible for any usage."
53 | )
54 | print(
55 | "Please enter your message below.\nThis chatbot is not sufficiently trained and the dataset is not properly cleaned, so it does not have a meaning beyond the demo version."
56 | )
57 |
58 | # Chat
59 | while True:
60 | user_input = input(Fore.BLUE + "You: " + Fore.RESET)
61 | if user_input.lower() in ["quit", "q", "stop"]:
62 | print("========================================")
63 | print(
64 | Fore.RED
65 | + " Chat Ended. "
66 | + Fore.RESET
67 | + "\n\nThank you for using DSDanielPark's chatbot. Please visit our GitHub and Hugging Face for more information. \n\n - github: https://github.com/DSDanielPark/GPT-BERT-Medical-QA-Chatbot \n - hugging-face: https://huggingface.co/datasets/danielpark/MQuAD-v1 "
68 | )
69 | print("========================================")
70 | break
71 |
72 | response = cahtbot.run(user_input, isEval)
73 | print(
74 | Fore.BLUE
75 | + Style.BRIGHT
76 | + "MediChatBot: "
77 | + response
78 | + Fore.RESET
79 | + Style.RESET_ALL
80 | )
81 | response = ""
82 |
83 |
84 | if __name__ == "__main__":
85 | main()
86 |
--------------------------------------------------------------------------------
/modules/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dsdanielpark/gpt2-bert-medical-qa-chat/ef5cfdd2d6577395886f61e74df5da5db5603448/modules/__init__.py
--------------------------------------------------------------------------------
/modules/chatbot/config.py:
--------------------------------------------------------------------------------
1 | class Config:
2 | chat_params = {
3 | "gpt_tok": "danielpark/medical-QA-chatGPT2-tok-v1",
4 | "tf_gpt_model": "danielpark/medical-QA-chatGPT2-v1",
5 | "bert_tok": "danielpark/medical-QA-BioRedditBERT-uncased-v1",
6 | "tf_q_extractor": "question_extractor_model",
7 | "data": "danielpark/MQuAD-v1",
8 | "max_answer_len": 20,
9 | "isEval": False,
10 | "runDocker": True, # Exceeds the bandwidth of git-lfs, mounts to local storage to find folder location for free use. I use the python utifunction package.
11 | "container_mounted_folder_path": "/usr/src/app/data",
12 | }
13 |
--------------------------------------------------------------------------------
/modules/chatbot/const.py:
--------------------------------------------------------------------------------
1 | CONTRACTIONS = {
2 | "won't": "will not",
3 | "can't": "can not",
4 | "n't": " not",
5 | "'re": " are",
6 | "'s": " is",
7 | "'d": " would",
8 | "'ll": " will",
9 | "'ve": " have",
10 | "'m": " am",
11 | "won\’t": "will not",
12 | "can\’t": "can not",
13 | "n\’t": " not",
14 | "\’re": " are",
15 | "\’s": " is",
16 | "\’d": " would",
17 | "\’ll": " will",
18 | "\’ve": " have",
19 | "\’m": " am",
20 | }
21 |
--------------------------------------------------------------------------------
/modules/chatbot/dataloader.py:
--------------------------------------------------------------------------------
1 | import faiss
2 | import numpy as np
3 | import pandas as pd
4 | from datasets import load_dataset
5 |
6 |
7 | def convert(item: str) -> np.ndarray:
8 | """
9 | Convert a string representation of an array to a numpy array.
10 |
11 | Args:
12 | item (str): String representation of an array.
13 |
14 | Returns:
15 | np.ndarray: Numpy array converted from the string representation.
16 | """
17 | item = item.strip()
18 | item = item[1:-1]
19 | item = np.fromstring(item, sep=" ")
20 | return item
21 |
22 |
23 | def get_dataset(huggingface_repo: str) -> pd.DataFrame:
24 | """
25 | Load dataset from Hugging Face repository and convert to pandas DataFrame.
26 |
27 | Args:
28 | huggingface_repo (str): Name of the Hugging Face repository.
29 |
30 | Returns:
31 | pd.DataFrame: Pandas DataFrame containing the loaded dataset.
32 | """
33 | df = load_dataset(huggingface_repo, "csv")
34 | df = pd.DataFrame(df["train"])
35 | df["Q_FFNN_embeds"] = df["Q_FFNN_embeds"].apply(convert)
36 | df["A_FFNN_embeds"] = df["A_FFNN_embeds"].apply(convert)
37 |
38 | return df
39 |
40 |
41 | def get_bert_index(
42 | df: pd.DataFrame, target_columns: Union[str, List[str]]
43 | ) -> faiss.IndexFlatIP:
44 | """
45 | Build and return the FAISS index for BERT embeddings.
46 |
47 | Args:
48 | df (pd.DataFrame): DataFrame containing the BERT embeddings.
49 | target_columns (Union[str, List[str]]): Name or list of names of the columns containing BERT embeddings.
50 |
51 | Returns:
52 | faiss.IndexFlatIP: FAISS index for BERT embeddings.
53 | """
54 | embedded_bert = df[target_columns].tolist()
55 | embedded_bert = np.array(embedded_bert, dtype="float32")
56 | index = faiss.IndexFlatIP(embedded_bert.shape[-1])
57 | index.add(embedded_bert)
58 |
59 | return index
60 |
--------------------------------------------------------------------------------
/modules/chatbot/inferencer.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import tensorflow as tf
3 | from typing import List
4 | from nltk.translate.bleu_score import sentence_bleu
5 | from modules.chatbot.preprocessor import preprocess
6 |
7 |
8 | class Inferencer:
9 | def __init__(
10 | self,
11 | medical_qa_gpt_model: tf.keras.Model,
12 | bert_tokenizer: tf.keras.preprocessing.text.Tokenizer,
13 | gpt_tokenizer: tf.keras.preprocessing.text.Tokenizer,
14 | question_extractor_model: tf.keras.Model,
15 | df_qa: pd.DataFrame,
16 | answer_index: faiss.IndexFlatIP,
17 | answer_len: int,
18 | ) -> None:
19 | """
20 | Initialize Inferencer with necessary components.
21 |
22 | Args:
23 | medical_qa_gpt_model (tf.keras.Model): Medical Q&A GPT model.
24 | bert_tokenizer (tf.keras.preprocessing.text.Tokenizer): BERT tokenizer.
25 | gpt_tokenizer (tf.keras.preprocessing.text.Tokenizer): GPT tokenizer.
26 | question_extractor_model (tf.keras.Model): Question extractor model.
27 | df_qa (pd.DataFrame): DataFrame containing Q&A pairs.
28 | answer_index (faiss.IndexFlatIP): FAISS index for answers.
29 | answer_len (int): Length of the answer.
30 | """
31 | self.biobert_tokenizer = bert_tokenizer
32 | self.question_extractor_model = question_extractor_model
33 | self.answer_index = answer_index
34 | self.gpt_tokenizer = gpt_tokenizer
35 | self.medical_qa_gpt_model = medical_qa_gpt_model
36 | self.df_qa = df_qa
37 | self.answer_len = answer_len
38 |
39 | def get_gpt_inference_data(
40 | self, question: str, question_embedding: np.ndarray
41 | ) -> List[int]:
42 | """
43 | Get GPT inference data.
44 |
45 | Args:
46 | question (str): Input question.
47 | question_embedding (np.ndarray): Embedding of the question.
48 |
49 | Returns:
50 | List[int]: GPT inference data.
51 | """
52 | topk = 20
53 | scores, indices = self.answer_index.search(
54 | question_embedding.astype("float32"), topk
55 | )
56 | q_sub = self.df_qa.iloc[indices.reshape(20)]
57 | line = "`QUESTION: %s `ANSWER: " % (question)
58 | encoded_len = len(self.gpt_tokenizer.encode(line))
59 | for i in q_sub.iterrows():
60 | line = (
61 | "`QUESTION: %s `ANSWER: %s " % (i[1]["question"], i[1]["answer"]) + line
62 | )
63 | line = line.replace("\n", "")
64 | encoded_len = len(self.gpt_tokenizer.encode(line))
65 | if encoded_len >= 1024:
66 | break
67 | return self.gpt_tokenizer.encode(line)[-1024:]
68 |
69 | def get_gpt_answer(self, question: str, answer_len: int) -> str:
70 | """
71 | Get GPT answer.
72 |
73 | Args:
74 | question (str): Input question.
75 | answer_len (int): Length of the answer.
76 |
77 | Returns:
78 | str: GPT generated answer.
79 | """
80 | preprocessed_question = preprocess(question)
81 | truncated_question = (
82 | " ".join(preprocessed_question.split(" ")[:500])
83 | if len(preprocessed_question.split(" ")) > 500
84 | else preprocessed_question
85 | )
86 | encoded_question = self.biobert_tokenizer.encode(truncated_question)
87 | padded_question = tf.keras.preprocessing.sequence.pad_sequences(
88 | [encoded_question], maxlen=512, padding="post"
89 | )
90 | question_mask = np.where(padded_question != 0, 1, 0)
91 | embeddings = self.question_extractor_model(
92 | {"question": padded_question, "question_mask": question_mask}
93 | )
94 | gpt_input = self.get_gpt_inference_data(truncated_question, embeddings.numpy())
95 | mask_start = len(gpt_input) - list(gpt_input[::-1]).index(4600) + 1
96 | input = gpt_input[: mask_start + 1]
97 | if len(input) > (1024 - answer_len):
98 | input = input[-(1024 - answer_len) :]
99 | gpt2_output = self.gpt_tokenizer.decode(
100 | self.medical_qa_gpt_model.generate(
101 | input_ids=tf.constant([np.array(input)]),
102 | max_length=1024,
103 | temperature=0.7,
104 | )[0]
105 | )
106 | answer = gpt2_output.rindex("`ANSWER: ")
107 | return gpt2_output[answer + len("`ANSWER: ") :]
108 |
109 | def inf_func(self, question: str) -> str:
110 | """
111 | Run inference for the given question.
112 |
113 | Args:
114 | question (str): Input question.
115 |
116 | Returns:
117 | str: Generated answer.
118 | """
119 | answer_len = self.answer_len
120 | return self.get_gpt_answer(question, answer_len)
121 |
122 | def eval_func(self, question: str, answer: str) -> float:
123 | """
124 | Evaluate generated answer against ground truth.
125 |
126 | Args:
127 | question (str): Input question.
128 | answer (str): Generated answer.
129 |
130 | Returns:
131 | float: BLEU score.
132 | """
133 | answer_len = 20
134 | generated_answer = self.get_gpt_answer(question, answer_len)
135 | reference = [answer.split(" ")]
136 | candidate = generated_answer.split(" ")
137 | score = sentence_bleu(reference, candidate)
138 | return score
139 |
140 | def run(self, question: str, isEval: bool) -> str:
141 | """
142 | Run inference for the given question.
143 |
144 | Args:
145 | question (str): Input question.
146 | isEval (bool): Whether to evaluate or not.
147 |
148 | Returns:
149 | str: Generated answer.
150 | """
151 | answer = self.inf_func(question)
152 | if isEval:
153 | bleu_score = self.eval_func(question, answer)
154 | print(f"The sentence_bleu score is {bleu_score}")
155 | return answer
156 |
--------------------------------------------------------------------------------
/modules/chatbot/preprocessor.py:
--------------------------------------------------------------------------------
1 | import re
2 | from modules.chatbot.const import CONTRACTIONS
3 |
4 |
5 | def decontracted(phrase):
6 | """
7 | Decontract a phrase.
8 |
9 | Args:
10 | phrase (str): The input phrase.
11 |
12 | Returns:
13 | str: Decontracted phrase.
14 | """
15 | for key, value in CONTRACTIONS.items():
16 | phrase = phrase.replace(key, value)
17 | return phrase
18 |
19 |
20 | def preprocess(text):
21 | """
22 | Preprocess text.
23 |
24 | Args:
25 | text (str): The input text.
26 |
27 | Returns:
28 | str: Preprocessed text.
29 | """
30 | text = text.lower()
31 | text = decontracted(text)
32 | text = re.sub(r"[$)\?\"’.°!;'€%:,(/]", "", text)
33 | text = re.sub(r"\u200b|\xa0|-", " ", text)
34 | return text
35 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | absl-py==1.4.0
2 | aiohttp==3.8.4
3 | aiosignal==1.3.1
4 | altair==4.2.2
5 | astunparse==1.6.3
6 | async-timeout==4.0.2
7 | attrs==22.2.0
8 | backports.zoneinfo==0.2.1
9 | blinker==1.6
10 | cachetools==5.3.0
11 | charset-normalizer==3.1.0
12 | click==8.1.3
13 | colorama==0.4.6
14 | datasets==2.11.0
15 | decorator==5.1.1
16 | dill==0.3.6
17 | entrypoints==0.4
18 | faiss-cpu==1.7.3
19 | filelock==3.10.7
20 | flatbuffers==23.3.3
21 | frozenlist==1.3.3
22 | fsspec==2023.3.0
23 | gast==0.4.0
24 | gitdb==4.0.10
25 | GitPython==3.1.31
26 | google-auth==2.17.2
27 | google-auth-oauthlib==0.4.6
28 | google-pasta==0.2.0
29 | grpcio==1.53.0
30 | h5py==3.8.0
31 | huggingface-hub==0.13.3
32 | idna==3.4
33 | importlib-metadata==6.1.0
34 | importlib-resources==5.12.0
35 | Jinja2==3.1.2
36 | joblib==1.2.0
37 | jsons==1.6.3
38 | jsonschema==4.17.3
39 | keras==2.10.0
40 | Keras-Preprocessing==1.1.2
41 | kmi2122==0.1.8
42 | libclang==16.0.0
43 | Markdown==3.4.3
44 | markdown-it-py==2.2.0
45 | MarkupSafe==2.1.2
46 | mdurl==0.1.2
47 | multidict==6.0.4
48 | multiprocess==0.70.14
49 | nltk==3.8.1
50 | numpy==1.24.2
51 | oauthlib==3.2.2
52 | opt-einsum==3.3.0
53 | packaging==23.0
54 | pandas==1.5.3
55 | Pillow==9.5.0
56 | pkgutil_resolve_name==1.3.10
57 | protobuf==3.19.6
58 | pyarrow==11.0.0
59 | pyasn1==0.4.8
60 | pyasn1-modules==0.2.8
61 | pydeck==0.8.0
62 | Pygments==2.14.0
63 | Pympler==1.0.1
64 | pyrsistent==0.19.3
65 | python-dateutil==2.8.2
66 | pytz==2023.3
67 | pytz-deprecation-shim==0.1.0.post0
68 | PyYAML==6.0
69 | regex==2023.3.23
70 | requests==2.28.2
71 | requests-oauthlib==1.3.1
72 | responses==0.18.0
73 | rich==13.3.3
74 | rsa==4.9
75 | semver==3.0.0
76 | six==1.16.0
77 | smmap==5.0.0
78 | streamlit==1.20.0
79 | streamlit-chat==0.0.2.2
80 | tensorboard==2.10.1
81 | tensorboard-data-server==0.6.1
82 | tensorboard-plugin-wit==1.8.1
83 | tensorflow==2.10.1
84 | tensorflow-estimator==2.10.0
85 | tensorflow-io-gcs-filesystem==0.31.0
86 | termcolor==2.2.0
87 | tokenizers==0.13.3
88 | toml==0.10.2
89 | toolz==0.12.0
90 | tornado==6.2
91 | tqdm==4.65.0
92 | transformers==4.27.4
93 | typing_extensions==4.5.0
94 | typish==1.9.3
95 | tzdata==2023.3
96 | tzlocal==4.3
97 | urllib3==1.26.15
98 | validators==0.20.0
99 | watchdog==3.0.0
100 | Werkzeug==2.2.3
101 | wincertstore==0.2
102 | wrapt==1.15.0
103 | xxhash==3.2.0
104 | yarl==1.8.2
105 | zipp==3.15.0
106 | utilfunction==0.1.2
--------------------------------------------------------------------------------
/scripts/01.chatgpt_api_app_example.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import openai
3 |
4 |
5 | openai.api_key = YOUR_API_KEY
6 |
7 | st.set_page_config(page_title="Chat GPT API EXAMPLE", page_icon=":tada:", layout="wide")
8 |
9 | st.subheader(
10 | """
11 | This is Test Landing Page
12 | """
13 | )
14 | st.title("EXAMPLE")
15 |
16 | title = st.text_input("YOU:")
17 | response = openai.Completion.create(
18 | model="text-davinci-003",
19 | prompt=title,
20 | temperature=0,
21 | max_tokens=60,
22 | top_p=1,
23 | frequency_penalty=0.5,
24 | presence_penalty=0,
25 | )
26 | if st.button("Send"):
27 | st.success(response.choices[0].text)
28 |
--------------------------------------------------------------------------------
/scripts/99.tester.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from utilfunction import col_convert\n",
10 | "import pandas as pd"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": 4,
16 | "metadata": {},
17 | "outputs": [
18 | {
19 | "name": "stderr",
20 | "output_type": "stream",
21 | "text": [
22 | "Found cached dataset csv (C:/Users/parkm/.cache/huggingface/datasets/danielpark___csv/danielpark--MQuAD-v1-87d38281de25bbdb/0.0.0/6954658bab30a358235fa864b05cf819af0e179325c740e4bc853bcc7ec513e1)\n"
23 | ]
24 | },
25 | {
26 | "data": {
27 | "application/vnd.jupyter.widget-view+json": {
28 | "model_id": "666e409b2e434e94be2a7455f5063123",
29 | "version_major": 2,
30 | "version_minor": 0
31 | },
32 | "text/plain": [
33 | " 0%| | 0/1 [00:00, ?it/s]"
34 | ]
35 | },
36 | "metadata": {},
37 | "output_type": "display_data"
38 | }
39 | ],
40 | "source": [
41 | "from datasets import load_dataset\n",
42 | "from utilfunction import col_convert\n",
43 | "\n",
44 | "qa = load_dataset(\"danielpark/MQuAD-v1\", \"csv\")\n",
45 | "df_qa = pd.DataFrame(qa['train'])\n",
46 | "\n",
47 | "df_qa = col_convert(df_qa, ['Q_FFNN_embeds', 'A_FFNN_embeds'])"
48 | ]
49 | }
50 | ],
51 | "metadata": {
52 | "kernelspec": {
53 | "display_name": "miccai",
54 | "language": "python",
55 | "name": "miccai"
56 | },
57 | "language_info": {
58 | "codemirror_mode": {
59 | "name": "ipython",
60 | "version": 3
61 | },
62 | "file_extension": ".py",
63 | "mimetype": "text/x-python",
64 | "name": "python",
65 | "nbconvert_exporter": "python",
66 | "pygments_lexer": "ipython3",
67 | "version": "3.8.5"
68 | },
69 | "orig_nbformat": 4
70 | },
71 | "nbformat": 4,
72 | "nbformat_minor": 2
73 | }
74 |
--------------------------------------------------------------------------------