FahimFBA commited on
Commit
eafe0e0
·
1 Parent(s): ba478c5

Configure for Hugging Face Spaces

Browse files
.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Python 3",
3
+ // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
4
+ "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bullseye",
5
+ "customizations": {
6
+ "codespaces": {
7
+ "openFiles": [
8
+ "README.md",
9
+ "app.py"
10
+ ]
11
+ },
12
+ "vscode": {
13
+ "settings": {},
14
+ "extensions": [
15
+ "ms-python.python",
16
+ "ms-python.vscode-pylance"
17
+ ]
18
+ }
19
+ },
20
+ "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y <packages.txt; [ -f requirements.txt ] && pip3 install --user -r requirements.txt; pip3 install --user streamlit; echo '✅ Packages installed and Requirements met'",
21
+ "postAttachCommand": {
22
+ "server": "streamlit run app.py --server.enableCORS false --server.enableXsrfProtection false"
23
+ },
24
+ "portsAttributes": {
25
+ "8501": {
26
+ "label": "Application",
27
+ "onAutoForward": "openPreview"
28
+ }
29
+ },
30
+ "forwardPorts": [
31
+ 8501
32
+ ]
33
+ }
.gitattributes CHANGED
@@ -1,35 +1,3 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.pt filter=lfs diff=lfs merge=lfs -text
2
+ *.png filter=lfs diff=lfs merge=lfs -text
3
+ *.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
Dockerfile CHANGED
@@ -1,20 +1,35 @@
1
- FROM python:3.13.5-slim
 
2
 
3
- WORKDIR /app
 
 
4
 
 
5
  RUN apt-get update && apt-get install -y \
6
- build-essential \
7
  curl \
8
- git \
 
 
 
 
 
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
- COPY requirements.txt ./
12
- COPY src/ ./src/
 
 
 
13
 
14
- RUN pip3 install -r requirements.txt
 
15
 
 
16
  EXPOSE 8501
17
 
18
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
 
19
 
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.9-slim
3
 
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE=1 \
6
+ PYTHONUNBUFFERED=1
7
 
8
+ # Install system dependencies
9
  RUN apt-get update && apt-get install -y \
 
10
  curl \
11
+ libglib2.0-0 \
12
+ libsm6 \
13
+ libxrender1 \
14
+ libxext6 \
15
+ libfontconfig1 \
16
+ libgl1-mesa-glx \
17
  && rm -rf /var/lib/apt/lists/*
18
 
19
+ # Set the working directory in the container
20
+ WORKDIR /app
21
+
22
+ # Copy the current directory contents into the container at /app
23
+ COPY . /app
24
 
25
+ # Install any needed packages specified in requirements.txt
26
+ RUN pip install --no-cache-dir -r requirements.txt
27
 
28
+ # Make port 8501 available to the world outside this container
29
  EXPOSE 8501
30
 
31
+ # Healthcheck to verify the application is running
32
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health || exit 1
33
 
34
+ # Run app.py when the container launches
35
+ CMD ["streamlit", "run", "--server.address", "0.0.0.0", "app.py"]
Dockerfile.gpu ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use NVIDIA CUDA base image
2
+ FROM nvidia/cuda:11.6.2-cudnn8-runtime-ubuntu20.04
3
+
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE=1 \
6
+ PYTHONUNBUFFERED=1 \
7
+ DEBIAN_FRONTEND=noninteractive
8
+
9
+ # Install system dependencies
10
+ RUN apt-get update && apt-get install -y \
11
+ python3-pip \
12
+ python3-dev \
13
+ curl \
14
+ libglib2.0-0 \
15
+ libsm6 \
16
+ libxrender1 \
17
+ libxext6 \
18
+ libfontconfig1 \
19
+ libgl1-mesa-glx \
20
+ && rm -rf /var/lib/apt/lists/*
21
+
22
+ # Set the working directory in the container
23
+ WORKDIR /app
24
+
25
+ # Copy the current directory contents into the container at /app
26
+ COPY . /app
27
+
28
+ # Install any needed packages specified in requirements.txt
29
+ RUN pip3 install --no-cache-dir -r requirements.txt
30
+
31
+ # Install PyTorch with CUDA support
32
+ RUN pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116
33
+
34
+ # Make port 8501 available to the world outside this container
35
+ EXPOSE 8501
36
+
37
+ # Healthcheck to verify the application is running
38
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health || exit 1
39
+
40
+ # Run app.py when the container launches
41
+ CMD ["streamlit", "run", "--server.address", "0.0.0.0", "app.py"]
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
@@ -1,20 +1,171 @@
1
  ---
2
  title: SafeLicensing
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
  pinned: false
11
- short_description: Streamlit template space
12
  license: apache-2.0
13
  ---
14
 
15
- # Welcome to Streamlit!
16
 
17
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
18
 
19
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: SafeLicensing
3
+ emoji: 🛡️
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: streamlit
7
+ sdk_version: 1.31.0
8
+ app_file: app.py
 
9
  pinned: false
 
10
  license: apache-2.0
11
  ---
12
 
13
+ # SafeLicensing
14
 
15
+ This project demonstrates a pipeline for detecting license plates in images using YOLOv8 and encrypting the detected regions with a Chaotic Logistic Map encryption algorithm. It provides a user-friendly interface built with Streamlit.
16
 
17
+ >[!TIP]
18
+ > You can directly test the application on the web using the following link: [![Open in Streamlit](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://share.streamlit.io/fahimfba/safelicensing/main/app.py)
19
+
20
+ ## Features
21
+
22
+ - **License Plate Detection**: Uses the YOLOv8 model to detect license plates in uploaded images.
23
+ - **Chaotic Encryption**: Encrypts the detected license plate regions using a two-layer XOR-based chaotic logistic map algorithm.
24
+ - **Streamlit Web App**: A simple interface to upload images, detect license plates, encrypt them, and download the results.
25
+
26
+ ## Installation
27
+
28
+ 1. Clone the repository:
29
+ ```bash
30
+ git clone https://github.com/FahimFBA/SafeLicensing.git
31
+ cd SafeLicensing
32
+ ```
33
+
34
+ 2. Install `ffmpeg` for video processing (Linux):
35
+ ```bash
36
+ sudo apt-get install ffmpeg
37
+ ```
38
+
39
+ or, for macOS:
40
+ ```bash
41
+ brew install ffmpeg
42
+ ```
43
+
44
+ 3. Install the required dependencies:
45
+ ```bash
46
+ pip install -r requirements.txt
47
+ ```
48
+
49
+ 4. Download the YOLOv8 weights file (`best.pt`) and place it in the root directory of the project. You can train your own model or use a pre-trained one. This repository already have our model from [SEncrypt](https://github.com/IsratIJK/SEncrypt) located in [best.pt](./best.pt) file.
50
+
51
+ ## Usage
52
+
53
+ 1. Run the Streamlit app:
54
+ ```bash
55
+ streamlit run app.py
56
+ ```
57
+
58
+ 2. Open the app in your browser (typically at `http://localhost:8501`).
59
+
60
+ 3. Follow the steps:
61
+ - Upload an image or provide a URL.
62
+ - Adjust the encryption key seed using the slider.
63
+ - Click the "Detect & Encrypt" button to process the image.
64
+
65
+ 4. Download the encrypted image directly from the app.
66
+
67
+ ## Docker Usage
68
+
69
+ You can run this application using Docker. There are two options: CPU-only and GPU-enabled.
70
+
71
+ ### CPU Version
72
+
73
+ 1. Build the Docker image:
74
+ ```bash
75
+ docker build -t safelicensing .
76
+ ```
77
+
78
+ 2. Run the Docker container:
79
+ ```bash
80
+ docker run -d -p 8501:8501 --name safelicensing_container safelicensing
81
+ ```
82
+
83
+ ### GPU Version (for NVIDIA GPU users)
84
+
85
+ 1. Ensure you have the NVIDIA Container Toolkit installed. If not, follow the [official installation guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html).
86
+
87
+ 2. Build the GPU-enabled Docker image:
88
+ ```bash
89
+ docker build -f Dockerfile.gpu -t safelicensing-gpu .
90
+ ```
91
+
92
+ 3. Run the GPU-enabled Docker container:
93
+ ```bash
94
+ docker run -d -p 8501:8501 --gpus all --name safelicensing_gpu_container safelicensing-gpu
95
+ ```
96
+
97
+ ### Common Steps
98
+
99
+ 4. Check if the container is running:
100
+ ```bash
101
+ docker ps
102
+ ```
103
+ You should see a container named `safelicensing_container` or `safelicensing_gpu_container` in the list.
104
+
105
+ 5. View the container logs:
106
+ ```bash
107
+ docker logs safelicensing_container # or safelicensing_gpu_container for GPU version
108
+ ```
109
+ This will show you the Streamlit startup logs and any errors if they occur.
110
+
111
+ 6. Open the app in your browser by navigating to `http://localhost:8501`.
112
+
113
+ If you encounter any issues:
114
+ - Ensure that port 8501 is not being used by another application.
115
+ - Check the container logs for any error messages.
116
+ - If needed, you can stop and remove the container using:
117
+ ```bash
118
+ docker stop safelicensing_container # or safelicensing_gpu_container
119
+ docker rm safelicensing_container # or safelicensing_gpu_container
120
+ ```
121
+ Then, try running the container again.
122
+
123
+ Note: The GPU version requires an NVIDIA GPU and proper drivers. If you don't have a compatible GPU, use the CPU version instead.
124
+
125
+ ## Workflow
126
+
127
+ 1. **License Plate Detection**:
128
+ - The YOLOv8 model is used to detect license plates in the input image. The model has been taken from [SEncrypt](https://github.com/IsratIJK/SEncrypt).
129
+ - Detected regions are highlighted with bounding boxes.
130
+
131
+ 2. **Chaotic Logistic Map Encryption**:
132
+ - A chaotic logistic map generates two XOR-based encryption keys.
133
+ - Pixels in the license plate regions are shuffled and encrypted in two stages.
134
+ - The encrypted region replaces the original plate in the image.
135
+
136
+ 3. **Visualization and Download**:
137
+ - The original, detected, and encrypted images are displayed in the app.
138
+ - Encrypted images can be downloaded as PNG files.
139
+
140
+ ## Files
141
+
142
+ - `app.py`: The main Streamlit app file.
143
+ - `requirements.txt`: Python dependencies for the project.
144
+ - `best.pt`: YOLOv8 weights file (not included, add your own).
145
+
146
+ ## Key Parameters
147
+
148
+ - **Encryption Key Seed**: A slider in the app adjusts the seed value for the chaotic logistic map, affecting the encryption's randomness.
149
+
150
+ ## Example Screenshots
151
+
152
+ ### Original Image
153
+
154
+ ![Original Image](./img/lpr-tesla-license-plate-recognition-1910x1000.jpg)
155
+
156
+ ### Encrypted Image
157
+
158
+ ![Encrypted Image](./img/encrypted_plate.png)
159
+
160
+ ## License
161
+
162
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
163
+
164
+ ## Contact
165
+
166
+ For any queries, feel free to reach out:
167
+
168
+ - **Author**: Md. Fahim Bin Amin
169
+ - **GitHub**: [FahimFBA](https://github.com/FahimFBA)
170
+
171
+ - **Other Authors**: [Rafid Mehda](https://github.com/rafid29mehda), [Israt Jahan Khan](https://github.com/IsratIJK)
app.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import requests
4
+ import numpy as np
5
+ from PIL import Image, ImageDraw
6
+ import io
7
+ import random
8
+ from ultralytics import YOLO
9
+ import time
10
+ import cv2
11
+ from moviepy.editor import VideoFileClip, ImageSequenceClip
12
+
13
+ ###############################################################################
14
+ # 1. Chaotic Logistic Map Encryption Functions
15
+ ###############################################################################
16
+
17
+ def logistic_map(r, x):
18
+ return r * x * (1 - x)
19
+
20
+ def generate_key(seed, n):
21
+ """
22
+ Generate a chaotic key (array of size n) using a logistic map and the given seed.
23
+ """
24
+ key = []
25
+ x = seed
26
+ for _ in range(n):
27
+ x = logistic_map(3.9, x)
28
+ key.append(int(x * 255) % 256) # map float to 0-255
29
+ return np.array(key, dtype=np.uint8)
30
+
31
+ def shuffle_pixels(img_array, seed):
32
+ """
33
+ Shuffle the pixels in img_array based on a random sequence seeded by 'seed'.
34
+ """
35
+ h, w, c = img_array.shape
36
+ num_pixels = h * w
37
+ flattened = img_array.reshape(-1, c)
38
+ indices = np.arange(num_pixels)
39
+ random.seed(seed)
40
+ random.shuffle(indices)
41
+ shuffled = flattened[indices]
42
+ return shuffled.reshape(h, w, c), indices
43
+
44
+ def encrypt_image(img_array, seed):
45
+ """
46
+ Encrypt the given image array using a two-layer XOR + pixel shuffling approach.
47
+ """
48
+ h, w, c = img_array.shape
49
+ flat_image = img_array.flatten()
50
+ # First chaotic key
51
+ chaotic_key_1 = generate_key(seed, len(flat_image))
52
+ # XOR-based encryption (first layer)
53
+ encrypted_flat_1 = [p ^ chaotic_key_1[i] for i, p in enumerate(flat_image)]
54
+ encrypted_array_1 = np.array(
55
+ encrypted_flat_1, dtype=np.uint8).reshape(h, w, c)
56
+ # Shuffle
57
+ shuffled_array, _ = shuffle_pixels(encrypted_array_1, seed)
58
+ # Second chaotic key
59
+ chaotic_key_2 = generate_key(seed * 1.1, len(flat_image))
60
+ shuffled_flat = shuffled_array.flatten()
61
+ encrypted_flat_2 = [p ^ chaotic_key_2[i]
62
+ for i, p in enumerate(shuffled_flat)]
63
+ doubly_encrypted_array = np.array(
64
+ encrypted_flat_2, dtype=np.uint8).reshape(h, w, c)
65
+ return doubly_encrypted_array
66
+
67
+ ###############################################################################
68
+ # 2. YOLOv8 License Plate Detection
69
+ ###############################################################################
70
+
71
+ @st.cache_resource(show_spinner=False)
72
+ def load_model(weights_path: str):
73
+ """
74
+ Loads the YOLOv8 model from local .pt weights.
75
+ """
76
+ model = YOLO(weights_path)
77
+ return model
78
+
79
+ def detect_license_plates(model, pil_image):
80
+ """
81
+ Runs YOLOv8 detection on the PIL image.
82
+ Returns:
83
+ - image_with_boxes: PIL image with bounding boxes drawn
84
+ - bboxes: list of (x1, y1, x2, y2) for detected license plates
85
+ """
86
+ np_image = np.array(pil_image)
87
+ results = model.predict(np_image)
88
+ if not results or len(results) == 0:
89
+ return pil_image, []
90
+ result = results[0]
91
+ if not hasattr(result, 'boxes') or result.boxes is None or len(result.boxes) == 0:
92
+ return pil_image, []
93
+ bboxes = []
94
+ draw = ImageDraw.Draw(pil_image)
95
+ for box in result.boxes:
96
+ coords = box.xyxy[0].tolist() # [x1, y1, x2, y2]
97
+ cls_id = int(box.cls[0].item())
98
+ cls_name = model.names.get(cls_id, "Unknown")
99
+ if cls_name.lower() == "licenseplate" or cls_id == 0:
100
+ x1, y1, x2, y2 = map(int, coords)
101
+ bboxes.append((x1, y1, x2, y2))
102
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
103
+ return pil_image, bboxes
104
+
105
+ ###############################################################################
106
+ # 3. Video Processing Functions
107
+ ###############################################################################
108
+
109
+ def process_video(video_path, model, key_seed):
110
+ """
111
+ Process video frame by frame, detect license plates, and encrypt them.
112
+ """
113
+ cap = cv2.VideoCapture(video_path)
114
+ fps = cap.get(cv2.CAP_PROP_FPS)
115
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
116
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
117
+
118
+ processed_frames = []
119
+
120
+ while cap.isOpened():
121
+ ret, frame = cap.read()
122
+ if not ret:
123
+ break
124
+
125
+ pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
126
+ _, bboxes = detect_license_plates(model, pil_image)
127
+
128
+ if bboxes:
129
+ for (x1, y1, x2, y2) in bboxes:
130
+ plate_region = frame[y1:y2, x1:x2]
131
+ encrypted_region = encrypt_image(plate_region, key_seed)
132
+ frame[y1:y2, x1:x2] = encrypted_region
133
+
134
+ processed_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
135
+
136
+ cap.release()
137
+ return processed_frames, fps, (width, height)
138
+
139
+ def create_video_from_frames(frames, fps, size, output_path, audio_path=None):
140
+ """
141
+ Create a video from processed frames and optionally add audio.
142
+ """
143
+ clip = ImageSequenceClip(frames, fps=fps)
144
+
145
+ if audio_path:
146
+ audio = VideoFileClip(audio_path).audio
147
+ clip = clip.set_audio(audio)
148
+
149
+ clip.write_videofile(output_path, codec='libx264')
150
+
151
+ ###############################################################################
152
+ # 4. Streamlit App
153
+ ###############################################################################
154
+
155
+ def main():
156
+ st.title("YOLOv8 + Chaotic Encryption for Images and Videos")
157
+ st.write(
158
+ """
159
+ **Instructions**:
160
+ 1. Provide an image or video (URL or file upload).
161
+ 2. If a license plate is detected, only that region will be **encrypted** using Chaotic Logistic Map.
162
+ 3. Download the final result (image or video).
163
+ """
164
+ )
165
+ default_model_path = "best.pt"
166
+ model_path = st.sidebar.text_input(
167
+ "YOLOv8 Weights (.pt)", value=default_model_path)
168
+ if not os.path.isfile(model_path):
169
+ st.warning(
170
+ f"Model file '{model_path}' not found. Please upload or provide a correct path.")
171
+ st.stop()
172
+ with st.spinner("Loading YOLOv8 model..."):
173
+ model = load_model(model_path)
174
+ st.success("Model loaded successfully!")
175
+
176
+ st.subheader("Input")
177
+ input_type = st.radio("Select input type", ["Image", "Video"])
178
+
179
+ if input_type == "Image":
180
+ image_url = st.text_input("Image URL (optional)")
181
+ uploaded_file = st.file_uploader("Or upload an image file", type=["jpg", "jpeg", "png"])
182
+ else:
183
+ video_url = st.text_input("Video URL (optional)")
184
+ uploaded_file = st.file_uploader("Or upload a video file", type=["mp4", "avi", "mov"])
185
+
186
+ key_seed = st.slider("Encryption Key Seed (0 < seed < 1)", 0.001, 0.999, 0.5, step=0.001)
187
+
188
+ if st.button("Detect & Encrypt"):
189
+ if input_type == "Image":
190
+ if image_url and not uploaded_file:
191
+ try:
192
+ response = requests.get(image_url, timeout=10)
193
+ response.raise_for_status()
194
+ image_bytes = io.BytesIO(response.content)
195
+ pil_image = Image.open(image_bytes).convert("RGB")
196
+ except Exception as e:
197
+ st.error(f"Failed to load image from URL. Error: {str(e)}")
198
+ return
199
+ elif uploaded_file:
200
+ try:
201
+ pil_image = Image.open(uploaded_file).convert("RGB")
202
+ except Exception as e:
203
+ st.error(f"Failed to open uploaded image. Error: {str(e)}")
204
+ return
205
+ else:
206
+ st.warning("Please either paste a valid URL or upload an image.")
207
+ return
208
+
209
+ st.image(pil_image, caption="Original Image", use_container_width=True)
210
+ start_time = time.time()
211
+
212
+ with st.spinner("Detecting license plates..."):
213
+ image_with_boxes, bboxes = detect_license_plates(model, pil_image.copy())
214
+
215
+ st.image(image_with_boxes, caption="Detected Plate(s)", use_container_width=True)
216
+
217
+ if not bboxes:
218
+ st.warning("No license plates detected.")
219
+ return
220
+
221
+ with st.spinner("Encrypting license plates..."):
222
+ np_img = np.array(pil_image)
223
+ encrypted_np = np_img.copy()
224
+ for (x1, y1, x2, y2) in bboxes:
225
+ x1 = max(x1, 0)
226
+ y1 = max(y1, 0)
227
+ x2 = min(x2, encrypted_np.shape[1])
228
+ y2 = min(y2, encrypted_np.shape[0])
229
+ plate_region = encrypted_np[y1:y2, x1:x2]
230
+ if plate_region.size == 0:
231
+ st.warning(f"Detected plate region ({x1}, {y1}, {x2}, {y2}) is invalid or empty.")
232
+ continue
233
+ encrypted_region = encrypt_image(plate_region, key_seed)
234
+ encrypted_np[y1:y2, x1:x2] = encrypted_region
235
+ encrypted_image = Image.fromarray(encrypted_np)
236
+
237
+ elapsed_time = time.time() - start_time
238
+ st.write(f"Total time taken for detection and encryption: **{elapsed_time:.2f} seconds**")
239
+ st.image(encrypted_image, caption="Encrypted Image", use_container_width=True)
240
+
241
+ buf = io.BytesIO()
242
+ encrypted_image.save(buf, format="PNG")
243
+ buf.seek(0)
244
+ st.download_button(
245
+ label="Download Encrypted Image",
246
+ data=buf,
247
+ file_name="encrypted_plate.png",
248
+ mime="image/png"
249
+ )
250
+
251
+ else: # Video processing
252
+ if video_url and not uploaded_file:
253
+ try:
254
+ response = requests.get(video_url, timeout=10)
255
+ response.raise_for_status()
256
+ video_bytes = io.BytesIO(response.content)
257
+ with open("temp_video.mp4", "wb") as f:
258
+ f.write(video_bytes.getvalue())
259
+ video_path = "temp_video.mp4"
260
+ except Exception as e:
261
+ st.error(f"Failed to load video from URL. Error: {str(e)}")
262
+ return
263
+ elif uploaded_file:
264
+ video_path = "temp_video.mp4"
265
+ with open(video_path, "wb") as f:
266
+ f.write(uploaded_file.getvalue())
267
+ else:
268
+ st.warning("Please either paste a valid video URL or upload a video file.")
269
+ return
270
+
271
+ with st.spinner("Processing video..."):
272
+ start_time = time.time()
273
+ processed_frames, fps, size = process_video(video_path, model, key_seed)
274
+ create_video_from_frames(processed_frames, fps, size, "encrypted_video.mp4", video_path)
275
+ elapsed_time = time.time() - start_time
276
+
277
+ st.write(f"Total time taken for video processing: **{elapsed_time:.2f} seconds**")
278
+ st.video("encrypted_video.mp4")
279
+
280
+ with open("encrypted_video.mp4", "rb") as f:
281
+ st.download_button(
282
+ label="Download Encrypted Video",
283
+ data=f,
284
+ file_name="encrypted_video.mp4",
285
+ mime="video/mp4"
286
+ )
287
+
288
+ # Clean up temporary files
289
+ os.remove("temp_video.mp4")
290
+ os.remove("encrypted_video.mp4")
291
+
292
+ if __name__ == "__main__":
293
+ main()
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13fe46504f4609387768cfa4270624a6d386c42efa496f1805df6305c14e597f
3
+ size 6256803
img/encrypted_plate.png ADDED

Git LFS Details

  • SHA256: 4edfd223196c4c42fc35a30ea0263212946d327d5d572949f4f16bf56dbcce92
  • Pointer size: 132 Bytes
  • Size of remote file: 2.14 MB
img/lpr-tesla-license-plate-recognition-1910x1000.jpg ADDED

Git LFS Details

  • SHA256: 73a0723662a8af916fc79d3fc5f37b9c65410ca24de6050033bb71bee92832bd
  • Pointer size: 131 Bytes
  • Size of remote file: 295 kB
packages.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ libglib2.0-0
2
+ libsm6
3
+ libxrender1
4
+ libxext6
5
+ libfontconfig1
6
+ libgl1-mesa-glx
7
+ ffmpeg
requirements.txt CHANGED
@@ -1,3 +1,11 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ torch
3
+ torchvision
4
+ pillow
5
+ opencv-python-headless
6
+ numpy
7
+ requests
8
+ ultralytics
9
+ omegaconf
10
+ moviepy==1.0.3
11
+ imageio-ffmpeg