NotShrirang commited on
Commit
19a6fbb
·
1 Parent(s): 4962477

feat: add app

Browse files
.gitignore ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
172
+
173
+ images/
174
+ vectorstore/
175
+ trial.py
176
+ annotations/
LICENSE ADDED
@@ -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.
README.md CHANGED
@@ -11,4 +11,133 @@ license: apache-2.0
11
  short_description: 🧠 Multimodal RAG that "weaves" together text and images 🪡
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  short_description: 🧠 Multimodal RAG that "weaves" together text and images 🪡
12
  ---
13
 
14
+ # 🌟 LoomRAG: Multimodal Retrieval-Augmented Generation for AI-Powered Search
15
+
16
+ ![GitHub stars](https://img.shields.io/github/stars/NotShrirang/LoomRAG?style=social)
17
+ ![GitHub forks](https://img.shields.io/github/forks/NotShrirang/LoomRAG?style=social)
18
+ ![GitHub commits](https://img.shields.io/github/commit-activity/t/NotShrirang/LoomRAG)
19
+ ![GitHub issues](https://img.shields.io/github/issues/NotShrirang/LoomRAG)
20
+ ![GitHub pull requests](https://img.shields.io/github/issues-pr/NotShrirang/LoomRAG)
21
+ ![GitHub](https://img.shields.io/github/license/NotShrirang/LoomRAG)
22
+ ![GitHub last commit](https://img.shields.io/github/last-commit/NotShrirang/LoomRAG)
23
+ ![GitHub repo size](https://img.shields.io/github/repo-size/NotShrirang/LoomRAG)
24
+ <a href="https://loomrag.streamlit.app/"><img src="https://img.shields.io/badge/Streamlit%20App-red?style=flat-rounded-square&logo=streamlit&labelColor=white"/></a>
25
+
26
+ This project implements a Multimodal Retrieval-Augmented Generation (RAG) system, named **LoomRAG**, that leverages OpenAI's CLIP model for neural cross-modal retrieval and semantic search. The system allows users to input text queries and retrieve both text and image responses seamlessly through vector embeddings. It also supports uploading images and PDFs for enhanced interaction and intelligent retrieval capabilities through a Streamlit-based interface.
27
+
28
+ Experience the project in action:
29
+
30
+ [![LoomRAG Streamlit App](https://img.shields.io/badge/Streamlit%20App-red?style=for-the-badge&logo=streamlit&labelColor=white)](https://loomrag.streamlit.app/)
31
+
32
+ ---
33
+
34
+ ## 📸 Implementation Screenshots
35
+
36
+ | ![Screenshot 2024-12-30 111906](https://github.com/user-attachments/assets/13c0bd0d-1569-4d9e-aae5-ea5801a69beb) | ![Screenshot 2024-12-30 114200](https://github.com/user-attachments/assets/d74e9d75-7716-4705-9564-0c6fdc26790b) |
37
+ | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
38
+ | Screenshot 1 | Screenshot 2 |
39
+
40
+ ---
41
+
42
+ ## ✨ Features
43
+
44
+ - 🔄 **Cross-Modal Retrieval**: Search text to retrieve both text and image results using deep learning
45
+ - 🌐 **Streamlit Interface**: Provides a user-friendly web interface for interacting with the system
46
+ - 📤 **Upload Options**: Allows users to upload images and PDFs for AI-powered processing and retrieval
47
+ - 🧠 **Embedding-Based Search**: Uses OpenAI's CLIP model to align text and image embeddings in a shared latent space
48
+ - 🔍 **Augmented Text Generation**: Enhances text results using LLMs for contextually rich outputs
49
+
50
+ ---
51
+
52
+ ## 🏗️ Architecture Overview
53
+
54
+ 1. **Data Indexing**:
55
+
56
+ - Text, images, and PDFs are preprocessed and embedded using the CLIP model
57
+ - Embeddings are stored in a vector database for fast and efficient retrieval
58
+
59
+ 2. **Query Processing**:
60
+
61
+ - Text queries are converted into embeddings for semantic search
62
+ - Uploaded images and PDFs are processed and embedded for comparison
63
+ - The system performs a nearest neighbor search in the vector database to retrieve relevant text and images
64
+
65
+ 3. **Response Generation**:
66
+ - For text results: Optionally refined or augmented using a language model
67
+ - For image results: Directly returned or enhanced with image captions
68
+ - For PDFs: Extracts text content and provides relevant sections
69
+
70
+ ---
71
+
72
+ ## 🚀 Installation
73
+
74
+ 1. Clone the repository:
75
+
76
+ ```bash
77
+ git clone https://github.com/NotShrirang/LoomRAG.git
78
+ cd LoomRAG
79
+ ```
80
+
81
+ 2. Create a virtual environment and install dependencies:
82
+ ```bash
83
+ pip install -r requirements.txt
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 📖 Usage
89
+
90
+ 1. **Running the Streamlit Interface**:
91
+
92
+ - Start the Streamlit app:
93
+
94
+ ```bash
95
+ streamlit run app.py
96
+ ```
97
+
98
+ - Access the interface in your browser to:
99
+ - Submit natural language queries
100
+ - Upload images or PDFs to retrieve contextually relevant results
101
+
102
+ 2. **Example Queries**:
103
+ - **Text Query**: "sunset over mountains"
104
+ Output: An image of a sunset over mountains along with descriptive text
105
+ - **PDF Upload**: Upload a PDF of a scientific paper
106
+ Output: Extracted key sections or contextually relevant images
107
+
108
+ ---
109
+
110
+ ## ⚙️ Configuration
111
+
112
+ - 📊 **Vector Database**: It uses FAISS for efficient similarity search
113
+ - 🤖 **Model**: Uses OpenAI CLIP for neural embedding generation
114
+ - ✍️ **Augmentation**: Optional LLM-based augmentation for text responses
115
+
116
+ ---
117
+
118
+ ## 🗺️ Roadmap
119
+
120
+ - [ ] Fine-tuning CLIP for domain-specific datasets
121
+ - [ ] Adding support for audio and video modalities
122
+ - [ ] Improving the re-ranking system for better contextual relevance
123
+ - [ ] Enhanced PDF parsing with semantic section segmentation
124
+
125
+ ---
126
+
127
+ ## 🤝 Contributing
128
+
129
+ Contributions are welcome! Please open an issue or submit a pull request for any feature requests or bug fixes.
130
+
131
+ ---
132
+
133
+ ## 📄 License
134
+
135
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
136
+
137
+ ---
138
+
139
+ ## 🙏 Acknowledgments
140
+
141
+ - [OpenAI CLIP](https://openai.com/research/clip)
142
+ - [FAISS](https://github.com/facebookresearch/faiss)
143
+ - [Hugging Face](https://huggingface.co/)
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ import faiss
3
+ import os
4
+ import pandas as pd
5
+ from PIL import Image
6
+ import streamlit as st
7
+ from streamlit_option_menu import option_menu
8
+ import time
9
+ import torch
10
+
11
+ from data_upload import data_upload_page
12
+ from data_search import data_search_page
13
+ from data_annotations import data_annotation_page
14
+ from model_finetuning import model_finetuning_page
15
+ from utils import load_clip_model, load_text_embedding_model
16
+
17
+ os.environ['KMP_DUPLICATE_LIB_OK']='True'
18
+
19
+ st.set_page_config(layout="wide", page_title="LoomRAG", page_icon="🔍")
20
+
21
+ device = "cuda" if torch.cuda.is_available() else "cpu"
22
+ clip_model, preprocess = load_clip_model()
23
+ text_embedding_model = load_text_embedding_model()
24
+
25
+ sidebar = st.sidebar
26
+
27
+ with st.sidebar:
28
+ st.title("LoomRAG")
29
+ page = option_menu(
30
+ menu_title=None,
31
+ options=["Data Upload", 'Data Search', "Data Annotation", "Model Fine-Tuning"],
32
+ icons=['cloud-upload', 'search', 'bi-card-checklist', 'sliders'],
33
+ menu_icon="list", default_index=0
34
+ )
35
+
36
+ if page == "Data Upload":
37
+ data_upload_page.data_upload(clip_model, preprocess, text_embedding_model)
38
+ if page == "Data Search":
39
+ data_search_page.data_search(clip_model, preprocess, text_embedding_model, device)
40
+ if page == "Data Annotation":
41
+ data_annotation_page.data_annotations()
42
+ if page == "Model Fine-Tuning":
43
+ model_finetuning_page.model_finetuning()
config/constants.py ADDED
File without changes
data_annotations/data_annotation_page.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import clip
3
+ import io
4
+ import json
5
+ import os
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import streamlit as st
9
+ import sys
10
+ import torch
11
+ import uuid
12
+
13
+ from utils import get_local_files
14
+
15
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
16
+
17
+
18
+ def data_annotations():
19
+ @st.dialog("Add Annotations", width="large")
20
+ def add_annotations_dialog(selected_image):
21
+ if not os.path.exists("annotations/"):
22
+ os.makedirs("annotations/")
23
+ annotation_project_key = st.session_state.get('annotation_project_key', None)
24
+ if not annotation_project_key:
25
+ annotation_project_key = str(uuid.uuid4())
26
+ st.session_state['annotation_project_key'] = annotation_project_key
27
+ if not os.path.exists(f"annotations/{annotation_project_key}/"):
28
+ os.makedirs(f"annotations/{annotation_project_key}/")
29
+ with open(f"annotations/{annotation_project_key}/annotations.json", "w") as f:
30
+ json.dump({}, f)
31
+ with open(f"annotations/{annotation_project_key}/annotations.json", "r") as f:
32
+ annotations_dict: dict = json.load(f)
33
+
34
+ current_image_annotation = annotations_dict.get(f"images/{selected_image['file_name']}", None)
35
+ if not current_image_annotation:
36
+ current_image_annotation = ""
37
+
38
+ st.image(f"images/{selected_image['file_name']}")
39
+ annotation = st.text_area("Add Annotations", value=current_image_annotation, height=100, key="annotation_text_area")
40
+ if st.button("Add Annotations", key="add_annotations_dialog"):
41
+ if annotation.strip() == "" or annotation is None:
42
+ st.warning("Please add annotations.")
43
+ else:
44
+ annotations_dict[f"images/{selected_image['file_name']}"] = annotation
45
+ with open(f"annotations/{annotation_project_key}/annotations.json", "w") as f:
46
+ json.dump(annotations_dict, f, indent=4)
47
+ st.toast("Annotations added successfully.", icon="🎉")
48
+ st.rerun()
49
+
50
+ st.title("Data Annotations")
51
+
52
+ files = get_local_files("images/", extensions=["jpg", "jpeg", "png"], get_details=True)
53
+
54
+ if not files:
55
+ st.warning("No images found in the data directory.")
56
+ return
57
+
58
+ st.write(f"Total {len(files)} images found in the data directory.")
59
+
60
+ files_df = pd.DataFrame(files)
61
+
62
+ files_df['Image'] = files_df['file_name'].apply(lambda x: f"data:image/{x.split('.')[-1]};base64,{base64.b64encode(open(f'images/{x}', 'rb').read()).decode()}")
63
+
64
+ files_df = files_df[["Image", "file_name", "file_size", "file_created"]]
65
+
66
+ if "annotation_project_key" in st.session_state:
67
+ annotation_project_key = st.session_state['annotation_project_key']
68
+ if os.path.exists(f"annotations/{annotation_project_key}/annotations.json"):
69
+ with open(f"annotations/{annotation_project_key}/annotations.json", "r") as f:
70
+ annotations_dict: dict = json.load(f)
71
+ files_df["Annotation"] = files_df["file_name"].apply(lambda x: annotations_dict.get(f"images/{x}", ""))
72
+
73
+ event = st.dataframe(files_df, hide_index=True, use_container_width=True, column_config={"Image" : st.column_config.ImageColumn('Image', pinned=True)}, selection_mode="single-row", on_select='rerun', key="image_table")
74
+
75
+ if len(event.selection['rows']):
76
+ selected_image = files[event.selection['rows'][0]]
77
+ add_annotations_dialog(selected_image)
data_search/data_search_page.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ import os
3
+ import pandas as pd
4
+ from PIL import Image
5
+ import streamlit as st
6
+ import sys
7
+ import torch
8
+ from vectordb import search_image_index, search_text_index
9
+ from utils import load_image_index, load_text_index, get_local_files
10
+
11
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
12
+
13
+
14
+ def data_search(clip_model, preprocess, text_embedding_model, device):
15
+
16
+ @st.cache_resource
17
+ def load_finetuned_model(file_name):
18
+ model, preprocess = clip.load("ViT-B/32", device=device)
19
+ model.load_state_dict(torch.load(f"annotations/{file_name}/finetuned_model.pt", weights_only=True))
20
+ return model, preprocess
21
+
22
+ st.title("Data Search")
23
+
24
+ annotation_projects = get_local_files("annotations/", get_details=True)
25
+
26
+ if annotation_projects or st.session_state.get('selected_annotation_project', None) is not None:
27
+ annotation_projects_with_model = []
28
+ for annotation_project in annotation_projects:
29
+ if os.path.exists(f"annotations/{annotation_project['file_name']}/finetuned_model.pt"):
30
+ annotation_projects_with_model.append(annotation_project)
31
+
32
+ if annotation_projects_with_model or st.session_state.get('selected_annotation_project', None) is not None:
33
+ if st.button("Use Default Model"):
34
+ st.session_state.pop('selected_annotation_project', None)
35
+ annotation_projects_df = pd.DataFrame(annotation_projects_with_model)
36
+ annotation_projects_df['file_created'] = annotation_projects_df['file_created'].dt.strftime("%Y-%m-%d %H:%M:%S")
37
+ annotation_projects_df['display_text'] = annotation_projects_df.apply(lambda x: f"ID: {x['file_name']} | Time Created: ({x['file_created']})", axis=1)
38
+
39
+ annotation_project = st.selectbox("Select Annotation Project", options=annotation_projects_df['display_text'].tolist())
40
+ annotation_project = annotation_projects_df[annotation_projects_df['display_text'] == annotation_project].iloc[0]
41
+ if st.button("Use Selected Fine-Tuned Model") or st.session_state.get('selected_annotation_project', None) is not None:
42
+ with st.spinner("Loading Fine-Tuned Model..."):
43
+ st.session_state['selected_annotation_project'] = annotation_project
44
+ clip_model, preprocess = load_finetuned_model(annotation_project['file_name'])
45
+ st.info(f"Using Fine-Tuned Model from {annotation_project['file_name']}")
46
+ else:
47
+ st.info("Using Default Model")
48
+
49
+ text_input = st.text_input("Search Database")
50
+ if st.button("Search", disabled=text_input.strip() == ""):
51
+ if os.path.exists("./vectorstore/image_index.index"):
52
+ image_index, image_data = load_image_index()
53
+ if os.path.exists("./vectorstore/text_index.index"):
54
+ text_index, text_data = load_text_index()
55
+ with torch.no_grad():
56
+ if not os.path.exists("./vectorstore/image_data.csv"):
57
+ st.warning("No Image Index Found. So not searching for images.")
58
+ image_index = None
59
+ if not os.path.exists("./vectorstore/text_data.csv"):
60
+ st.warning("No Text Index Found. So not searching for text.")
61
+ text_index = None
62
+ if image_index is not None:
63
+ image_indices = search_image_index(text_input, image_index, clip_model, k=3)
64
+ if text_index is not None:
65
+ text_indices = search_text_index(text_input, text_index, text_embedding_model, k=3)
66
+ if not image_index and not text_index:
67
+ st.error("No Data Found! Please add data to the database.")
68
+ st.subheader("Top 3 Results")
69
+ cols = st.columns(3)
70
+ for i in range(3):
71
+ with cols[i]:
72
+ if image_index:
73
+ image_path = image_data['path'].iloc[image_indices[0][i]]
74
+ image = Image.open(image_path)
75
+ image = preprocess(image).unsqueeze(0).to(device)
76
+ text = clip.tokenize([text_input]).to(device)
77
+ image_features = clip_model.encode_image(image)
78
+ text_features = clip_model.encode_text(text)
79
+ cosine_similarity = torch.cosine_similarity(image_features, text_features)
80
+ st.write(f"Similarity: {cosine_similarity.item() * 100:.2f}%")
81
+ st.image(image_path)
82
+ cols = st.columns(3)
83
+ for i in range(3):
84
+ with cols[i]:
85
+ if text_index:
86
+ text_content = text_data['content'].iloc[text_indices[0][i]]
87
+ st.write(text_content)
data_upload/data_upload_page.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import sys
4
+ from vectordb import add_image_to_index, add_pdf_to_index
5
+
6
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
7
+
8
+
9
+ def data_upload(clip_model, preprocess, text_embedding_model):
10
+ st.title("Data Upload")
11
+ upload_choice = st.selectbox(options=["Upload Image", "Upload PDF"], label="Select Upload Type")
12
+ if upload_choice == "Upload Image":
13
+ st.subheader("Add Image to Database")
14
+ images = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
15
+ if images:
16
+ cols = st.columns(5, vertical_alignment="center")
17
+ for count, image in enumerate(images[:4]):
18
+ with cols[count]:
19
+ st.image(image)
20
+ with cols[4]:
21
+ st.info(f"and more {len(images) - 5} images...")
22
+ st.info(f"Total {len(images)} files selected.")
23
+ if st.button("Add Images"):
24
+ progress_bar = st.progress(0)
25
+ for image in images:
26
+ add_image_to_index(image, clip_model, preprocess)
27
+ progress_bar.progress((images.index(image) + 1) / len(images), f"{images.index(image) + 1}/{len(images)}")
28
+ st.success("Images Added to Database")
29
+ else:
30
+ st.subheader("Add PDF to Database")
31
+ st.warning("Please note that the images in the PDF will also be extracted and added to the database.")
32
+ pdfs = st.file_uploader("Upload PDF", type=["pdf"], accept_multiple_files=True)
33
+ if pdfs:
34
+ st.info(f"Total {len(pdfs)} files selected.")
35
+ if st.button("Add PDF"):
36
+ for pdf in pdfs:
37
+ add_pdf_to_index(
38
+ pdf=pdf,
39
+ clip_model=clip_model,
40
+ preprocess=preprocess,
41
+ text_embedding_model=text_embedding_model,
42
+ )
43
+ st.success("PDF Added to Database")
model_finetuning/components/model_training_component.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ import clip.model
3
+ from datasets import Dataset
4
+ import json
5
+ import numpy as np
6
+ import pandas as pd
7
+ from PIL import Image
8
+ from sklearn.model_selection import train_test_split
9
+ import streamlit as st
10
+ import time
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.optim as optim
14
+ from torch.utils.data import DataLoader
15
+ import tqdm
16
+ import os
17
+
18
+
19
+ def model_training():
20
+ dataset_path = st.session_state.get("selected_dataset", None)
21
+ if not dataset_path:
22
+ st.error("Please select a dataset to proceed.")
23
+ return
24
+
25
+ if not os.path.exists(f"annotations/{dataset_path}/annotations.json"):
26
+ st.error("No annotations found for the selected dataset.")
27
+ return
28
+
29
+ with open(f"annotations/{dataset_path}/annotations.json", "r") as f:
30
+ annotations_dict = json.load(f)
31
+
32
+ annotations_df = pd.DataFrame(annotations_dict.items(), columns=['image_path', 'annotation'])
33
+ annotations_df.columns = ['file_name', 'text']
34
+ st.subheader("Data Preview")
35
+ st.dataframe(annotations_df.head(), use_container_width=True)
36
+
37
+ test_size = st.selectbox("Select Test Size", options=[0.1, 0.2, 0.3, 0.4, 0.5], index=1)
38
+ train_df, val_df = train_test_split(annotations_df, test_size=test_size, random_state=42)
39
+ st.write(f"Train Size: {len(train_df)} | Validation Size: {len(val_df)}")
40
+ col1, col2 = st.columns(2)
41
+ with col1:
42
+ optimizer = st.selectbox("Select Optimizer", options=optim.__all__, index=3)
43
+ optimizer = getattr(optim, optimizer)
44
+ with col2:
45
+ batch_size_options = [2, 4, 8, 16, 32, 64, 128]
46
+ ideal_batch_size = int(np.sqrt(len(train_df)))
47
+ if ideal_batch_size in batch_size_options:
48
+ ideal_batch_size_index = batch_size_options.index(ideal_batch_size)
49
+ else:
50
+ for batch_size in batch_size_options:
51
+ if batch_size > ideal_batch_size:
52
+ ideal_batch_size_index = batch_size_options.index(batch_size) - 1
53
+ break
54
+ batch_size = st.selectbox("Select Batch Size", options=[2, 4, 8, 16, 32, 64, 128], index=ideal_batch_size_index)
55
+
56
+ col1, col2 = st.columns(2)
57
+ with col1:
58
+ weight_decay = st.number_input("Weight Decay", value=0.3, format="%.5f")
59
+ with col2:
60
+ learning_rate = st.number_input("Learning Rate", value=1e-3, format="%.5f")
61
+
62
+ device = "cuda" if torch.cuda.is_available() else "cpu"
63
+
64
+ if st.button("Train", key="train_button", use_container_width=True, type="primary"):
65
+ def convert_models_to_fp32(model):
66
+ for p in model.parameters():
67
+ p.data = p.data.float()
68
+ p.grad.data = p.grad.data.float()
69
+
70
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
71
+ with st.spinner("Loading Model..."):
72
+ model, preprocess = clip.load("ViT-B/32", device=device, jit=False)
73
+ clip.model.convert_weights(model)
74
+
75
+ loss_img = nn.CrossEntropyLoss()
76
+ loss_txt = nn.CrossEntropyLoss()
77
+ optimizer = optimizer(model.parameters(), lr=learning_rate, betas=(0.9, 0.98), eps=1e-6, weight_decay=weight_decay)
78
+
79
+ def collate_fn(batch):
80
+ images = []
81
+ texts = []
82
+ for entry in batch:
83
+ img = entry['file_name']
84
+ text = entry['text']
85
+ images.append(img)
86
+ texts.append(text)
87
+ images = [preprocess(Image.open(img_path)) for img_path in images]
88
+ images = torch.stack(images)
89
+ return images, list(texts)
90
+
91
+ train_df['file_name'] = train_df['file_name'].str.strip()
92
+ val_df['file_name'] = val_df['file_name'].str.strip()
93
+
94
+ dataset = Dataset.from_pandas(train_df)
95
+ dataloader = DataLoader(
96
+ dataset,
97
+ batch_size=batch_size,
98
+ shuffle=True,
99
+ collate_fn=collate_fn
100
+ )
101
+
102
+ val_dataset = Dataset.from_pandas(val_df)
103
+ val_dataloader = DataLoader(
104
+ val_dataset,
105
+ batch_size=batch_size,
106
+ shuffle=False,
107
+ collate_fn=collate_fn
108
+ )
109
+
110
+ def calculate_val_loss(model):
111
+ model.eval()
112
+ total_loss = 0
113
+ with torch.no_grad():
114
+ for batch_idx, (images, texts) in enumerate(val_dataloader):
115
+ texts = clip.tokenize(texts).to(device)
116
+
117
+ images = images.to(device)
118
+ texts = texts.to(device)
119
+
120
+ logits_per_image, logits_per_text = model(images, texts)
121
+
122
+ ground_truth = torch.arange(len(images)).to(device)
123
+ image_loss = loss_img(logits_per_image, ground_truth)
124
+ text_loss = loss_txt(logits_per_text, ground_truth)
125
+
126
+ total_loss += (image_loss + text_loss) / 2
127
+
128
+ model.train()
129
+ return total_loss / len(val_dataloader)
130
+
131
+ step = 0
132
+ progress_bar = st.progress(0, text=f"Model Training in progress... \nStep: {step}/{len(dataloader)} | {0 / len(dataloader)}% Completed | Loss: 0.0")
133
+ for batch_idx, (images, texts) in enumerate(dataloader):
134
+ optimizer.zero_grad()
135
+
136
+ texts = clip.tokenize(texts).to(device)
137
+
138
+ images = images.to(device)
139
+ texts = texts.to(device)
140
+
141
+ logits_per_image, logits_per_text = model(images, texts)
142
+
143
+ ground_truth = torch.arange(len(images)).to(device)
144
+ image_loss = loss_img(logits_per_image, ground_truth)
145
+ text_loss = loss_txt(logits_per_text, ground_truth)
146
+ total_loss = (image_loss + text_loss) / 2
147
+ total_loss.backward()
148
+
149
+ if step % 20 == 0:
150
+ print("\nStep : ", step)
151
+ print("Total Loss : ", total_loss.item())
152
+ val_loss = calculate_val_loss(model)
153
+ print("\nValidation Loss : ", val_loss.item())
154
+ print("\n")
155
+
156
+ convert_models_to_fp32(model)
157
+ optimizer.step()
158
+ clip.model.convert_weights(model)
159
+ step += 1
160
+ progress_bar.progress((batch_idx + 1) / len(dataloader), f"Model Training in progress... \nStep: {step}/{len(dataloader)} | {round((batch_idx + 1) / len(dataloader) * 100)}% Completed | Loss: {val_loss.item():.4f}")
161
+
162
+ st.toast("Training Completed!", icon="🎉")
163
+
164
+ with st.spinner("Saving Model..."):
165
+ finetuned_model = model.eval()
166
+ torch.save(finetuned_model.state_dict(), f"annotations/{dataset_path}/finetuned_model.pt")
167
+
168
+ st.success("Model Saved Successfully!")
model_finetuning/components/selection_component.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ import json
3
+ import pandas as pd
4
+ import streamlit as st
5
+ import torch
6
+ import time
7
+
8
+ from utils import get_local_files
9
+
10
+ def preference_selection():
11
+ annotation_projects = get_local_files("annotations/", get_details=True)
12
+ if not annotation_projects:
13
+ st.warning("No annotated data found.")
14
+ return
15
+
16
+ annotation_projects_df = pd.DataFrame(annotation_projects)
17
+ annotation_projects_df['file_created'] = annotation_projects_df['file_created'].dt.strftime("%Y-%m-%d %H:%M:%S")
18
+ annotation_projects_df['display_text'] = annotation_projects_df.apply(lambda x: f"ID: {x['file_name']} | Time Created: ({x['file_created']})", axis=1)
19
+
20
+ annotation_project = st.selectbox("Select Annotation Project", options=annotation_projects_df['display_text'].tolist())
21
+ annotation_project = annotation_projects_df[annotation_projects_df['display_text'] == annotation_project].iloc[0]
22
+ with open(f"annotations/{annotation_project['file_name']}/annotations.json", "r") as f:
23
+ annotations_dict: dict = json.load(f)
24
+
25
+ annotations_df = pd.DataFrame(annotations_dict.items(), columns=['image_path', 'annotation'])
26
+ annotations_df['image_path'] = annotations_df['image_path'].apply(lambda x: x.split('/')[-1])
27
+ cols = st.columns(5)
28
+ for i, row in annotations_df.head(4).iterrows():
29
+ with cols[i]:
30
+ st.image(f"images/{row['image_path']}", caption=row['annotation'])
31
+ if len(annotations_df) > 4:
32
+ with cols[4]:
33
+ st.info(f"and more {len(annotations_df) - 4} images...")
34
+
35
+ save_preference = st.button("Save Preferences")
36
+ if save_preference:
37
+ st.session_state['selected_dataset'] = annotation_project['file_name']
38
+ st.success("Preferences Saved Successfully.")
model_finetuning/model_finetuning_page.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import clip
3
+ import io
4
+ import json
5
+ import os
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import streamlit as st
9
+ import sys
10
+ import torch
11
+ import uuid
12
+
13
+ from utils import get_local_files
14
+ from model_finetuning.components import selection_component, model_training_component
15
+
16
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
17
+
18
+
19
+ def model_finetuning():
20
+ page = st.session_state.get("model_finetuning_page", 0)
21
+
22
+ pages = {
23
+ 0: "Preference Selection",
24
+ 1: "Model Training",
25
+ 2: "Model Evaluation"
26
+ }
27
+ st.title(pages[page])
28
+
29
+ if not torch.cuda.is_available():
30
+ st.warning("No GPUs detected. Model training should be done on a GPU machine or on remote instance.")
31
+
32
+ if page == 0:
33
+ selection_component.preference_selection()
34
+ elif page == 1:
35
+ model_training_component.model_training()
36
+ elif page == 2:
37
+ st.write("Model Evaluation")
38
+
39
+ col1, col2 = st.columns(2, gap="large")
40
+ if col1.button("⬅️ Back", disabled=page == 0, use_container_width=True):
41
+ st.session_state["model_finetuning_page"] = page - 1
42
+ st.rerun()
43
+ if col2.button("Next ➡️", disabled=page == 2, use_container_width=True):
44
+ st.session_state["model_finetuning_page"] = page + 1
45
+ st.rerun()
46
+
47
+
requirements.txt ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohappyeyeballs==2.4.4
2
+ aiohttp==3.11.11
3
+ aiosignal==1.3.2
4
+ altair==5.5.0
5
+ annotated-types==0.7.0
6
+ anyio==4.7.0
7
+ async-timeout==4.0.3
8
+ attrs==24.3.0
9
+ blinker==1.9.0
10
+ cachetools==5.5.0
11
+ certifi==2024.12.14
12
+ charset-normalizer==3.4.1
13
+ click==8.1.8
14
+ clip @ git+https://github.com/openai/CLIP.git@dcba3cb2e2827b402d2701e7e1c7d9fed8a20ef1
15
+ colorama==0.4.6
16
+ contourpy==1.3.1
17
+ cycler==0.12.1
18
+ dataclasses-json==0.6.7
19
+ datasets==3.2.0
20
+ dill==0.3.8
21
+ exceptiongroup==1.2.2
22
+ faiss-cpu==1.8.0
23
+ filelock==3.16.1
24
+ fonttools==4.55.3
25
+ frozenlist==1.5.0
26
+ fsspec==2024.9.0
27
+ ftfy==6.3.1
28
+ gitdb==4.0.11
29
+ GitPython==3.1.43
30
+ greenlet==3.1.1
31
+ h11==0.14.0
32
+ httpcore==1.0.7
33
+ httpx==0.28.1
34
+ httpx-sse==0.4.0
35
+ huggingface-hub==0.27.0
36
+ idna==3.10
37
+ Jinja2==3.1.5
38
+ joblib==1.4.2
39
+ jsonpatch==1.33
40
+ jsonpointer==3.0.0
41
+ jsonschema==4.23.0
42
+ jsonschema-specifications==2024.10.1
43
+ kiwisolver==1.4.8
44
+ langchain==0.3.13
45
+ langchain-community==0.3.13
46
+ langchain-core==0.3.28
47
+ langchain-experimental==0.3.4
48
+ langchain-text-splitters==0.3.4
49
+ langsmith==0.1.147
50
+ markdown-it-py==3.0.0
51
+ MarkupSafe==3.0.2
52
+ marshmallow==3.23.2
53
+ matplotlib==3.10.0
54
+ mdurl==0.1.2
55
+ mpmath==1.3.0
56
+ multidict==6.1.0
57
+ multiprocess==0.70.16
58
+ mypy-extensions==1.0.0
59
+ narwhals==1.19.1
60
+ networkx==3.4.2
61
+ numpy==1.26.4
62
+ open_clip_torch==2.29.0
63
+ orjson==3.10.12
64
+ packaging==24.2
65
+ pandas==2.2.3
66
+ pillow==11.0.0
67
+ propcache==0.2.1
68
+ protobuf==5.29.2
69
+ pyarrow==18.1.0
70
+ pydantic==2.10.4
71
+ pydantic-settings==2.7.0
72
+ pydantic_core==2.27.2
73
+ pydeck==0.9.1
74
+ Pygments==2.18.0
75
+ pyparsing==3.2.0
76
+ PyPDF2==3.0.1
77
+ python-dateutil==2.9.0.post0
78
+ python-dotenv==1.0.1
79
+ pytz==2024.2
80
+ PyYAML==6.0.2
81
+ referencing==0.35.1
82
+ regex==2024.11.6
83
+ requests==2.32.3
84
+ requests-toolbelt==1.0.0
85
+ rich==13.9.4
86
+ rpds-py==0.22.3
87
+ safetensors==0.4.5
88
+ scikit-learn==1.6.0
89
+ scipy==1.14.1
90
+ sentence-transformers==3.3.1
91
+ six==1.17.0
92
+ smmap==5.0.1
93
+ sniffio==1.3.1
94
+ SQLAlchemy==2.0.36
95
+ streamlit==1.41.1
96
+ streamlit-option-menu==0.4.0
97
+ sympy==1.13.1
98
+ tenacity==8.5.0
99
+ threadpoolctl==3.5.0
100
+ timm==1.0.12
101
+ tokenizers==0.21.0
102
+ toml==0.10.2
103
+ torch==2.5.1
104
+ torchvision==0.20.1
105
+ tornado==6.4.2
106
+ tqdm==4.67.1
107
+ transformers==4.47.1
108
+ typing-inspect==0.9.0
109
+ typing_extensions==4.12.2
110
+ tzdata==2024.2
111
+ urllib3==2.3.0
112
+ watchdog==6.0.0
113
+ wcwidth==0.2.13
114
+ xxhash==3.5.0
115
+ yarl==1.18.3
utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ from datetime import datetime
3
+ import faiss
4
+ import pandas as pd
5
+ import os
6
+ from sentence_transformers import SentenceTransformer
7
+ import streamlit as st
8
+ import torch
9
+
10
+ device = "cuda" if torch.cuda.is_available() else "cpu"
11
+
12
+ @st.cache_resource
13
+ def load_clip_model():
14
+ model, preprocess = clip.load("ViT-B/32", device=device)
15
+ return model, preprocess
16
+
17
+ @st.cache_resource
18
+ def load_text_embedding_model():
19
+ model = SentenceTransformer("all-MiniLM-L6-v2")
20
+ return model
21
+
22
+ def load_image_index():
23
+ index = faiss.read_index('./vectorstore/image_index.index')
24
+ data = pd.read_csv("./vectorstore/image_data.csv")
25
+ return index, data
26
+
27
+ def load_text_index():
28
+ index = faiss.read_index('./vectorstore/text_index.index')
29
+ data = pd.read_csv("./vectorstore/text_data.csv")
30
+ return index, data
31
+
32
+ def cosine_similarity(a, b):
33
+ return torch.cosine_similarity(a, b)
34
+
35
+
36
+ def get_local_files(directory: str, extensions: list = None, get_details: bool = False):
37
+ files = os.listdir(directory)
38
+ if not extensions:
39
+ if get_details:
40
+ return [{
41
+ "file_name": file,
42
+ "file_size": os.path.getsize(os.path.join(directory, file)),
43
+ "file_created": datetime.fromtimestamp(os.path.getctime(os.path.join(directory, file)))
44
+ } for file in files]
45
+ else:
46
+ return files
47
+ else:
48
+ if get_details:
49
+ filtered_files = []
50
+ for file in files:
51
+ file_extension = file.split(".")[-1]
52
+ if file_extension in extensions:
53
+ filtered_files.append({
54
+ "file_name": file,
55
+ "file_size": os.path.getsize(os.path.join(directory, file)),
56
+ "file_created": datetime.fromtimestamp(os.path.getctime(os.path.join(directory, file)))
57
+ })
58
+ return filtered_files
59
+ else:
60
+ return [file for file in files if file.endswith(extensions(extensions))]
vectordb.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ import clip.model
3
+ import faiss
4
+ import io
5
+ from langchain_text_splitters import CharacterTextSplitter
6
+ import os
7
+ import pandas as pd
8
+ from PyPDF2 import PdfReader
9
+ from PIL import Image
10
+ from sentence_transformers import SentenceTransformer
11
+ import streamlit as st
12
+ import torch
13
+ import time
14
+
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+ os.makedirs("./vectorstore", exist_ok=True)
18
+
19
+ def update_vectordb(index_path: str, embedding: torch.Tensor, image_path: str = None, text_content: str = None):
20
+ if not image_path and not text_content:
21
+ raise ValueError("Either image_path or text_content must be provided.")
22
+ if not os.path.exists(f"./vectorstore/{index_path}"):
23
+ if image_path:
24
+ index = faiss.IndexFlatL2(512)
25
+ else:
26
+ index = faiss.IndexFlatL2(384)
27
+ else:
28
+ index = faiss.read_index(f"./vectorstore/{index_path}")
29
+ try:
30
+ index.add(embedding.cpu().numpy())
31
+ except:
32
+ if len(embedding.shape) == 1:
33
+ embedding = torch.Tensor([embedding])
34
+ index.add(embedding)
35
+ faiss.write_index(index, f'./vectorstore/{index_path}')
36
+ if image_path:
37
+ if not os.path.exists("./vectorstore/image_data.csv"):
38
+ df = pd.DataFrame([{"path": image_path, "index": 0}]).reset_index(drop=True)
39
+ df.to_csv("./vectorstore/image_data.csv", index=False)
40
+ else:
41
+ df = pd.read_csv("./vectorstore/image_data.csv").reset_index(drop=True)
42
+ new_entry_df = pd.DataFrame({"path": image_path, "index": len(df)}, index=[0])
43
+ df = pd.concat([df, new_entry_df], ignore_index=True)
44
+ df.to_csv("./vectorstore/image_data.csv", index=False)
45
+ elif text_content:
46
+ if not os.path.exists("./vectorstore/text_data.csv"):
47
+ df = pd.DataFrame([{"content": text_content, "index": 0}]).reset_index(drop=True)
48
+ df.to_csv("./vectorstore/text_data.csv", index=False)
49
+ else:
50
+ df = pd.read_csv("./vectorstore/text_data.csv").reset_index(drop=True)
51
+ new_entry_df = pd.DataFrame({"content": text_content, "index": len(df)}, index=[0])
52
+ df = pd.concat([df, new_entry_df], ignore_index=True)
53
+ df.to_csv("./vectorstore/text_data.csv", index=False)
54
+ else:
55
+ raise ValueError("Either image_path or text_content must be provided.")
56
+ return index
57
+
58
+
59
+ def add_image_to_index(image, model: clip.model.CLIP, preprocess):
60
+ image_name = image.name
61
+ image_name = image_name.replace(" ", "_")
62
+ os.makedirs("./images", exist_ok=True)
63
+ os.makedirs("./vectorstore", exist_ok=True)
64
+ with open(f"./images/{image_name}", "wb") as f:
65
+ try:
66
+ f.write(image.read())
67
+ except:
68
+ image = io.BytesIO(image.data)
69
+ f.write(image.read())
70
+ image = Image.open(f"./images/{image_name}")
71
+ with torch.no_grad():
72
+ image = preprocess(image).unsqueeze(0).to(device)
73
+ image_features = model.encode_image(image)
74
+ index = update_vectordb(index_path="image_index.index", embedding=image_features, image_path=f"./images/{image_name}")
75
+ return index
76
+
77
+
78
+ def add_pdf_to_index(pdf, clip_model: clip.model.CLIP, preprocess, text_embedding_model: SentenceTransformer):
79
+ if not os.path.exists("./vectorstore/"):
80
+ os.makedirs("./vectorstore")
81
+ pdf_name = pdf.name
82
+ pdf_name = pdf_name.replace(" ", "_")
83
+ pdf_reader = PdfReader(pdf)
84
+ pdf_pages_data = []
85
+ pdf_texts = []
86
+ text_splitter = CharacterTextSplitter(
87
+ separator="\n",
88
+ chunk_size=1000,
89
+ chunk_overlap=200,
90
+ length_function=len,
91
+ is_separator_regex=False,
92
+ )
93
+ progress_bar = st.progress(0)
94
+ for page_num, page in enumerate(pdf_reader.pages):
95
+ try:
96
+ page_images = page.images
97
+ except:
98
+ page_images = []
99
+ st.error("Some images in the PDF are not readable. Please try another PDF.")
100
+ for image in page_images:
101
+ image.name = f"{time.time()}.png"
102
+ add_image_to_index(image, clip_model, preprocess)
103
+ pdf_pages_data.append({f"page_number": page_num, "content": image, "type": "image"})
104
+
105
+ page_text = page.extract_text()
106
+ pdf_texts.append(page_text)
107
+ if page_text != "" or page_text.strip() != "":
108
+ chunks = text_splitter.split_text(page_text)
109
+ text_embeddings: torch.Tensor = text_embedding_model.encode(chunks)
110
+ for i, chunk in enumerate(chunks):
111
+ update_vectordb(index_path="text_index.index", embedding=text_embeddings[i], text_content=chunk)
112
+ pdf_pages_data.append({f"page_number": page_num, "content": chunk, "type": "text"})
113
+ percent_complete = ((page_num + 1) / len(pdf_reader.pages))
114
+ progress_bar.progress(percent_complete, f"Processing Page {page_num + 1}/{len(pdf_reader.pages)}")
115
+ return pdf_pages_data
116
+
117
+
118
+ def search_image_index(text_input: str, index: faiss.IndexFlatL2, clip_model: clip.model.CLIP, k: int = 3):
119
+ with torch.no_grad():
120
+ text = clip.tokenize([text_input]).to(device)
121
+ text_features = clip_model.encode_text(text)
122
+ distances, indices = index.search(text_features.cpu().numpy(), k)
123
+ return indices
124
+
125
+ def search_text_index(text_input: str, index: faiss.IndexFlatL2, text_embedding_model: SentenceTransformer, k: int = 3):
126
+ text_embeddings = text_embedding_model.encode([text_input])
127
+ distances, indices = index.search(text_embeddings, k)
128
+ return indices