qli12's picture
Update app.py
e340e25
import random
import string
import torch
def txt_to_list(filename):
with open(filename, 'r') as file:
lines = file.readlines()
# Strip whitespace and return
return [line.strip() for line in lines]
commonpasswords_list = txt_to_list('10-million-password-list-top-1000000.txt')
englishwords_list = txt_to_list('words.txt')
#Remove any single alphabet letter
commonpasswords_list = [item for item in commonpasswords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]
englishwords_list = [item for item in englishwords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]
#Remove '', which would cause error
englishwords_list.remove('')
#Double check whether it works
any(elem in commonpasswords_list for elem in list(string.ascii_lowercase))
any(elem in englishwords_list for elem in list(string.ascii_lowercase))
topwords_list = txt_to_list('top-1000-nouns.txt')
#Remove any single alphabet letter
topwords_list = [item for item in topwords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]
#Remove '', which would cause error
#Double check whether it works
any(elem in topwords_list for elem in list(string.ascii_lowercase))
topwords_list[0] = 'time'
common_passwords = commonpasswords_list
dictionary_words = englishwords_list
def generate_password(length=12, use_uppercase=True, use_lowercase=True,
use_numbers=True, use_symbols=True, dictionary = True):
# Define the character sets
uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
numbers = string.digits
symbols = "!@#$%^&*()-_+=[]{}|:;<>,.?/"
# Build the character pool based on the user's requirements
character_pool = ""
if use_uppercase:
character_pool += uppercase
if use_lowercase:
character_pool += lowercase
if use_numbers:
character_pool += numbers
if use_symbols:
character_pool += symbols
# Check if character pool is empty
if not character_pool:
raise ValueError("No character sets selected!")
# Generate the password
while True:
password = ''.join(random.choice(character_pool) for _ in range(length))
# Check if password contains any common English word
if not any(word in password.lower() for word in common_passwords):
if dictionary:
if not any(word in password.lower() for word in dictionary_words):
return password
break
return password
break
# Load model directly
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("DunnBC22/codebert-base-Password_Strength_Classifier")
model = AutoModelForSequenceClassification.from_pretrained("DunnBC22/codebert-base-Password_Strength_Classifier")
# Put the model in evaluation mode
#The model classifies passwords as one of the following:0.Weak 1.Medium 2.Strong
model.eval()
# Input the password you generate, you could also manually input
text = generate_password(12)
#text = input()
# Tokenize input text
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)
# Get logits
with torch.no_grad():
logits = model(**inputs).logits
# Get predictions
predictions = torch.argmax(logits, dim=1)
def strength_indicator(value):
# Define a mapping of index to label
index_to_label = {
0: "Weak",
1: "Medium",
2: "Strong"
}
# Check if the input value is within the valid range
if value not in index_to_label:
raise ValueError("Input should be an integer ranging from 0 to 2.")
# Return the corresponding label
return index_to_label[value]
strength_indicator(predictions.item())
##This is just a python function and no user interface
def AssessYourPassword(manual=True):
model.eval()
# Input the password you generate, you could also manually input
if manual:
text = input()
else:
print('Please input the length of your password:')
n = input()
text = generate_password(int(n))
# Tokenize input text
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)
# Get logits
with torch.no_grad():
logits = model(**inputs).logits
# Get predictions
predictions = torch.argmax(logits, dim=1)
strength = strength_indicator(predictions.item())
if not manual:
print(f'This is the generated password: {text}')
return print(f'Password Strength: {strength}')
import gradio as gr
import random
import string
import torch
model.eval()
def generate_password(length=12, use_uppercase=True, use_lowercase=True,
use_numbers=True, use_symbols=True, dictionary=True, easy_mode=False):
if easy_mode:
numbers = "1234567890"
special_chars = "!@#$%^&*"
chosen_words = [random.choice(topwords_list) for _ in range(2)]
chosen_words = [word.capitalize() if random.choice([True, False]) else word for word in chosen_words]
chosen_numbers = "".join(random.choice(numbers) for _ in range(3))
chosen_special_char = random.choice(special_chars)
components = chosen_words + [chosen_numbers, chosen_special_char]
random.shuffle(components)
password = "".join(components)
else:
uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
numbers = string.digits
symbols = "!@#$%^&*()-_+=[]{}|:;<>,.?/"
character_pool = ""
if use_uppercase:
character_pool += uppercase
if use_lowercase:
character_pool += lowercase
if use_numbers:
character_pool += numbers
if use_symbols:
character_pool += symbols
if not character_pool:
raise ValueError("No character sets selected!")
password = ''.join(random.choice(character_pool) for _ in range(length))
return password
def AssessYourPassword_UI_v2(option, length, use_uppercase, use_lowercase,
use_numbers, use_symbols, dictionary_allowed, text_input):
model.eval()
if option == "Manual":
text = text_input
elif option == "Easy Mode":
text = generate_password(easy_mode=True)
else:
text = generate_password(length, use_uppercase, use_lowercase,
use_numbers, use_symbols, not dictionary_allowed)
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)
with torch.no_grad():
logits = model(**inputs).logits
predictions = torch.argmax(logits, dim=1)
strength = strength_indicator(predictions.item())
if option == "Manual":
output_password = "You provided: " + text
else:
output_password = "Generated: " + text
return output_password, f'Password Strength: {strength}'
iface_v2 = gr.Interface(
fn=AssessYourPassword_UI_v2,
inputs=[
gr.Radio(["Manual", "Generated", "Easy Mode"], label="Password Input Method"),
gr.Slider(minimum=6, maximum=24, default=12, step=1, label="Password Length"),
gr.Checkbox(label="Use Uppercase Letters", default=True),
gr.Checkbox(label="Use Lowercase Letters", default=True),
gr.Checkbox(label="Use Numbers", default=True),
gr.Checkbox(label="Use Symbols", default=True),
gr.Checkbox(label="Allow Dictionary Words", default=False),
gr.Textbox(default="Type password or length here", label="Input")
],
outputs=[
"text",
"text"
]
)
iface_v2.launch(share=True, debug=True)