RafidMehda commited on
Commit
0efc9c2
·
verified ·
1 Parent(s): 331f009

Upload 6 files

Browse files
Files changed (6) hide show
  1. LICENSE +201 -0
  2. README.md +102 -12
  3. app.py +293 -0
  4. best.pt +3 -0
  5. packages.txt +6 -0
  6. requirements.txt +12 -0
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,12 +1,102 @@
1
- ---
2
- title: SafeLicensing
3
- emoji: 📊
4
- colorFrom: blue
5
- colorTo: pink
6
- sdk: streamlit
7
- sdk_version: 1.42.2
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SafeLicensing
2
+
3
+ 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.
4
+
5
+ >[!TIP]
6
+ > 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)
7
+
8
+ ## Features
9
+
10
+ - **License Plate Detection**: Uses the YOLOv8 model to detect license plates in uploaded images.
11
+ - **Chaotic Encryption**: Encrypts the detected license plate regions using a two-layer XOR-based chaotic logistic map algorithm.
12
+ - **Streamlit Web App**: A simple interface to upload images, detect license plates, encrypt them, and download the results.
13
+
14
+ ## Installation
15
+
16
+ 1. Clone the repository:
17
+ ```bash
18
+ git clone https://github.com/FahimFBA/SafeLicensing.git
19
+ cd SafeLicensing
20
+ ```
21
+
22
+ 2. Install `ffmpeg` for video processing (Linux):
23
+ ```bash
24
+ sudo apt-get install ffmpeg
25
+ ```
26
+
27
+ or, for macOS:
28
+ ```bash
29
+ brew install ffmpeg
30
+ ```
31
+
32
+ 3. Install the required dependencies:
33
+ ```bash
34
+ pip install -r requirements.txt
35
+ ```
36
+
37
+ 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.
38
+
39
+ ## Usage
40
+
41
+ 1. Run the Streamlit app:
42
+ ```bash
43
+ streamlit run app.py
44
+ ```
45
+
46
+ 2. Open the app in your browser (typically at `http://localhost:8501`).
47
+
48
+ 3. Follow the steps:
49
+ - Upload an image or provide a URL.
50
+ - Adjust the encryption key seed using the slider.
51
+ - Click the "Detect & Encrypt" button to process the image.
52
+
53
+ 4. Download the encrypted image directly from the app.
54
+
55
+ ## Workflow
56
+
57
+ 1. **License Plate Detection**:
58
+ - 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).
59
+ - Detected regions are highlighted with bounding boxes.
60
+
61
+ 2. **Chaotic Logistic Map Encryption**:
62
+ - A chaotic logistic map generates two XOR-based encryption keys.
63
+ - Pixels in the license plate regions are shuffled and encrypted in two stages.
64
+ - The encrypted region replaces the original plate in the image.
65
+
66
+ 3. **Visualization and Download**:
67
+ - The original, detected, and encrypted images are displayed in the app.
68
+ - Encrypted images can be downloaded as PNG files.
69
+
70
+ ## Files
71
+
72
+ - `app.py`: The main Streamlit app file.
73
+ - `requirements.txt`: Python dependencies for the project.
74
+ - `best.pt`: YOLOv8 weights file (not included, add your own).
75
+
76
+ ## Key Parameters
77
+
78
+ - **Encryption Key Seed**: A slider in the app adjusts the seed value for the chaotic logistic map, affecting the encryption's randomness.
79
+
80
+ ## Example Screenshots
81
+
82
+ ### Original Image
83
+
84
+ ![Original Image](./img/lpr-tesla-license-plate-recognition-1910x1000.jpg)
85
+
86
+ ### Encrypted Image
87
+
88
+ ![Encrypted Image](./img/encrypted_plate.png)
89
+
90
+ ## License
91
+
92
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
93
+
94
+ ## Contact
95
+
96
+ For any queries, feel free to reach out:
97
+
98
+ - **Author**: Md. Fahim Bin Amin
99
+ - **GitHub**: [FahimFBA](https://github.com/FahimFBA)
100
+
101
+ - **Other Authors**: [Rafid Mehda](https://github.com/rafid29mehda), [Israt Jahan Khan](https://github.com/IsratIJK)
102
+
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
packages.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ libglib2.0-0
2
+ libsm6
3
+ libxrender1
4
+ libxext6
5
+ libfontconfig1
6
+ libgl1-mesa-glx
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ torch
3
+ torchvision
4
+ pillow
5
+ opencv-python
6
+ numpy
7
+ requests
8
+ ultralytics
9
+ omegaconf
10
+ opencv-python-headless
11
+ moviepy==1.0.3
12
+ imageio-ffmpeg