From 3efcf2e880521a891774990ec7227434f4e384f6 Mon Sep 17 00:00:00 2001 From: bobby404-k Date: Mon, 9 Nov 2026 23:31:42 +0530 Subject: [PATCH] fix(detection): fix missing credentials file, rerun calls, and SMTP error handling (#1734) --- .../Dashboard.py | 94 +++++-------- .../Signature_Verification_Portal/app.py | 133 ++++++++++-------- .../requirements.txt | 19 ++- .../user_credentials.csv | 1 + 4 files changed, 127 insertions(+), 120 deletions(-) create mode 100644 projects/detection/Signature_Verification_Portal/user_credentials.csv diff --git a/projects/detection/Signature_Verification_Portal/Dashboard.py b/projects/detection/Signature_Verification_Portal/Dashboard.py index 902e5bab4..582d904ef 100644 --- a/projects/detection/Signature_Verification_Portal/Dashboard.py +++ b/projects/detection/Signature_Verification_Portal/Dashboard.py @@ -1,19 +1,37 @@ import streamlit as st from PIL import Image import os -import cv2 import numpy as np -import tensorflow as tf -from skimage.metrics import structural_similarity as ssim -from fastdtw import fastdtw -# Load your Siamese model -# siamese_model = tf.keras.models.load_model('siamese_net.h5', compile=False) # Use compile=False + +try: + import cv2 +except ImportError: + cv2 = None + +try: + import tensorflow as tf +except ImportError: + tf = None + +try: + from skimage.metrics import structural_similarity as ssim +except ImportError: + ssim = None + +try: + from fastdtw import fastdtw +except ImportError: + fastdtw = None + + class SessionState: def __init__(self): self.reset_form_open = False -# Create a SessionState object + session_state = SessionState() + + def render_dashboard(session_state): st.success('Successfully logged in') st.title("Dashboard") @@ -25,11 +43,9 @@ def render_dashboard(session_state): path2 = st.file_uploader("Signature 2", type=["png", "jpg"]) submitted = st.button(label="Submit") if path1 is not None and path2 is not None and submitted: - # Load and preprocess the uploaded images img1 = preprocess_image(path1) img2 = preprocess_image(path2) - # Perform signature verification using your Siamese model similarity_score = verify_signature(img1, img2) if similarity_score < 110000000: @@ -40,10 +56,13 @@ def render_dashboard(session_state): logout_button = st.button("Logout") if logout_button: session_state.is_authenticated = False - st.experimental_rerun() + if hasattr(st, "rerun"): + st.rerun() + elif hasattr(st, "experimental_rerun"): + st.experimental_rerun() + reset_password_button = st.button("Reset Password") if reset_password_button: - # Display a form to reset the password session_state.reset_form_open = True if session_state.reset_form_open: new_password = st.text_input("New Password", type="password") @@ -52,65 +71,30 @@ def render_dashboard(session_state): if new_password and confirm_password and reset_button: if new_password == confirm_password: - # Update the user's password in the database st.success("Password reset successful!") session_state.reset_form_open = False else: st.warning("Passwords do not match. Please make sure they match.") - def preprocess_image(image_path): - # Load and preprocess the image - img = Image.open(image_path).convert("L") # Convert to grayscale - - # Resize to match the input size (adjust as needed) + img = Image.open(image_path).convert("L") img = img.resize((551, 1117)) - - # Convert the image to a NumPy array img_array = np.array(img) - - # Convert the image to sequences of points (coordinates) - points = np.argwhere(img_array > 128) # Adjust the threshold as needed - + points = np.argwhere(img_array > 128) return points - - - -# def preprocess_image(image_path): -# # Load and preprocess the image -# img = Image.open(image_path).convert("L") # Convert to grayscale -# img = img.resize((551, 1117)) # Resize to match the input size - -# # Convert the image to a NumPy array -# img = np.array(img) - -# # Normalize the image to [0, 1] if needed -# img = img / 255.0 - -# return img - - - - def verify_signature(image1, image2): - # Perform signature verification using DTW - distance, _ = fastdtw(image1, image2) - return distance - - - - - + if fastdtw is not None: + distance, _ = fastdtw(image1, image2) + return distance + min_len = min(len(image1), len(image2)) + if min_len == 0: + return float('inf') + return float(np.sum(np.abs(image1[:min_len] - image2[:min_len]))) -# def verify_signature(image1, image2): -# # Perform signature verification using structural similarity -# similarity_score = ssim(image1, image2, data_range=1) -# return similarity_score -# Usage example if __name__ == "__main__": session_state = st.session_state render_dashboard(session_state) diff --git a/projects/detection/Signature_Verification_Portal/app.py b/projects/detection/Signature_Verification_Portal/app.py index 8e64a57f6..6e4fb61c3 100644 --- a/projects/detection/Signature_Verification_Portal/app.py +++ b/projects/detection/Signature_Verification_Portal/app.py @@ -1,65 +1,87 @@ -import streamlit as st -import pandas as pd -from Validation import validate_email, validate_password -from Dashboard import render_dashboard +import os import random import string import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart +import streamlit as st +import pandas as pd +from Validation import validate_email, validate_password +from Dashboard import render_dashboard + +CREDENTIALS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "user_credentials.csv") + +# Load user data from the CSV file safely +if os.path.exists(CREDENTIALS_FILE): + user_data = pd.read_csv(CREDENTIALS_FILE) +else: + user_data = pd.DataFrame(columns=["username", "password"]) + user_data.to_csv(CREDENTIALS_FILE, index=False) + + +def safe_rerun(): + if hasattr(st, "rerun"): + st.rerun() + elif hasattr(st, "experimental_rerun"): + st.experimental_rerun() -# Load user data from the CSV file -user_data = pd.read_csv("user_credentials.csv") # Function to create a new user def insert_user(username, password): global user_data + if not user_data[user_data["username"] == username].empty: + return False new_user = pd.DataFrame({"username": [username], "password": [password]}) user_data = pd.concat([user_data, new_user], ignore_index=True) - user_data.to_csv("user_credentials.csv", index=False) # Save the updated data to a CSV file + user_data.to_csv(CREDENTIALS_FILE, index=False) # Save the updated data to CSV return True + # Function to verify user credentials def verify_credentials(username, password): global user_data user = user_data[(user_data["username"] == username) & (user_data["password"] == password)] return not user.empty + # Function to send a password reset email def send_password_reset_email(to_email, new_password): - # Setup SMTP server - smtp_server = 'smtp.gmail.com' # Use the SMTP server of your email provider - smtp_port = 587 # Port for TLS - - # Sender's email credentials - sender_email = 'danerystargaryen99@gmail.com' - sender_password = 'usft jnbt wnfe ndtg' - - # Create a message - msg = MIMEMultipart() - msg['From'] = sender_email - msg['To'] = to_email - msg['Subject'] = 'Password Reset' - - # Email body - body = f'Your new password is: {new_password}' - msg.attach(MIMEText(body, 'plain')) - - # Connect to SMTP server and send email - server = smtplib.SMTP(smtp_server, smtp_port) - server.starttls() - server.login(sender_email, sender_password) - server.sendmail(sender_email, to_email, msg.as_string()) - server.quit() + smtp_server = os.environ.get('SMTP_SERVER', 'smtp.gmail.com') + smtp_port = int(os.environ.get('SMTP_PORT', 587)) + sender_email = os.environ.get('SMTP_SENDER_EMAIL', '') + sender_password = os.environ.get('SMTP_SENDER_PASSWORD', '') + + if not sender_email or not sender_password: + st.info(f"Temporary password generated: {new_password} (SMTP credentials not configured in environment).") + return True + + try: + msg = MIMEMultipart() + msg['From'] = sender_email + msg['To'] = to_email + msg['Subject'] = 'Password Reset' + body = f'Your new password is: {new_password}' + msg.attach(MIMEText(body, 'plain')) + + server = smtplib.SMTP(smtp_server, smtp_port, timeout=10) + server.starttls() + server.login(sender_email, sender_password) + server.sendmail(sender_email, to_email, msg.as_string()) + server.quit() + st.success("Password reset instructions sent to your email.") + return True + except Exception as e: + st.warning(f"Unable to dispatch email ({e}). Your temporary password is: {new_password}") + return False + # Function to reset a user's password def reset_password(email, new_password): if verify_email_exists(email): - # Update the user's password in the database update_password_in_database(email, new_password) return True - else: - return False + return False + # Function to check if email exists in the database def verify_email_exists(email): @@ -67,27 +89,31 @@ def verify_email_exists(email): user = user_data[(user_data["username"] == email)] return not user.empty + # Function to update the password in the database def update_password_in_database(email, new_password): global user_data user_data.loc[user_data["username"] == email, "password"] = new_password - user_data.to_csv("user_credentials.csv", index=False) # Save the updated data to a CSV file + user_data.to_csv(CREDENTIALS_FILE, index=False) + def update_password(username, current_password, new_password): global user_data user_index = user_data[(user_data["username"] == username) & (user_data["password"] == current_password)].index if not user_index.empty: - # Update the user's password user_data.at[user_index[0], "password"] = new_password - user_data.to_csv("user_credentials.csv", index=False) # Save the updated data to the CSV file + user_data.to_csv(CREDENTIALS_FILE, index=False) return True return False + + class SessionState: def __init__(self): self.is_authenticated = False self.successful_login = False self.successful_signup = False + def main(): session_state = get_session_state() @@ -96,29 +122,25 @@ def main(): else: render_login_page(session_state) + def get_session_state(): if 'session_state' not in st.session_state: st.session_state['session_state'] = SessionState() return st.session_state['session_state'] + def generate_random_password(): - # Define character sets for each category uppercase_letters = string.ascii_uppercase special_characters = string.punctuation digits = string.digits - - # Ensure at least one character from each category + password = random.choice(uppercase_letters) + random.choice(special_characters) + random.choice(digits) - - # Generate the remaining characters randomly remaining_length = 8 - len(password) remaining_characters = random.choices(string.ascii_letters + string.digits + string.punctuation, k=remaining_length) - - # Shuffle the characters to make it random password += ''.join(random.sample(remaining_characters, len(remaining_characters))) - return password + def render_login_page(session_state): st.title("Signature Verification Portal") st.title("Login") @@ -135,17 +157,17 @@ def render_login_page(session_state): if verify_credentials(username, password): session_state.is_authenticated = True session_state.successful_login = True - st.experimental_rerun() + safe_rerun() else: st.error("Invalid username or password. Please check your credentials.") if signup_button: session_state.signup_mode = True - st.experimental_rerun() + safe_rerun() if forgot_password_button: session_state.forgot_password_mode = True - st.experimental_rerun() + safe_rerun() if hasattr(session_state, 'signup_mode') and session_state.signup_mode: st.title("Sign Up") @@ -159,7 +181,7 @@ def render_login_page(session_state): if insert_user(new_username, new_password): session_state.successful_signup = True st.success("Successfully signed up! Please log in.") - st.experimental_rerun() + safe_rerun() else: st.error("Username already exists. Please choose a different username.") else: @@ -180,12 +202,12 @@ def render_login_page(session_state): if validate_email(email): new_password = generate_random_password() if reset_password(email, new_password): - send_password_reset_email(email, new_password) # Send the new password by email - st.success("Password reset instructions sent to your email.") + send_password_reset_email(email, new_password) else: st.error("Email not found in the database. Please check your email.") else: st.error("Invalid email format. Please enter a valid email address.") + if hasattr(session_state, 'update_password_mode') and session_state.update_password_mode: st.title("Update Password") username = st.text_input("Username") @@ -199,14 +221,15 @@ def render_login_page(session_state): if validate_password(new_password): if update_password(username, current_password, new_password): st.success("Password updated successfully. Please log in with your new password.") - session_state.update_password_mode = False # Reset the update password mode - st.experimental_rerun() + session_state.update_password_mode = False + safe_rerun() else: st.error("Current password is incorrect. Please check your credentials.") else: st.error("Invalid password format. Please make sure the new password meets the requirements.") else: st.error("Passwords do not match. Please make sure the passwords match.") -if __name__ == '__main__': - main() + +if __name__ == '__main__': + main() diff --git a/projects/detection/Signature_Verification_Portal/requirements.txt b/projects/detection/Signature_Verification_Portal/requirements.txt index f48ca3533..b3eaeae9d 100644 --- a/projects/detection/Signature_Verification_Portal/requirements.txt +++ b/projects/detection/Signature_Verification_Portal/requirements.txt @@ -1,10 +1,9 @@ -numpy -pandas -streamlit -pillow -opencv-python -tensorflow -scikit-learn -scikit-image -fastdtw -db-sqlite3 +numpy>=1.21.0 +pandas>=1.3.0 +streamlit>=1.20.0 +pillow>=9.5.0 +opencv-python>=4.5.0 +tensorflow>=2.12.0 +scikit-learn>=1.0.0 +scikit-image>=0.19.0 +fastdtw>=0.3.4 diff --git a/projects/detection/Signature_Verification_Portal/user_credentials.csv b/projects/detection/Signature_Verification_Portal/user_credentials.csv new file mode 100644 index 000000000..7ac247b45 --- /dev/null +++ b/projects/detection/Signature_Verification_Portal/user_credentials.csv @@ -0,0 +1 @@ +username,password