CoolFace
Apppublic

4darsh-Dev/dark_pattern_detector_app

sourceHugging Facemitupdated 2y agoView on Hugging Face
1likes
app.py123 linesDownload Raw Back to root
1import streamlit as st2import torch3from transformers import BertTokenizer, BertForSequenceClassification4 5from tqdm import tqdm  # Import tqdm for progress bar6 7import time # for time taken calc8 9# Load pre-trained model10label_dict = {"Urgency": 0, "Not Dark Pattern": 1, "Scarcity": 2, "Misdirection": 3, "Social Proof": 4, "Obstruction": 5, "Sneaking": 6, "Forced Action": 7}11model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=len(label_dict))12 13# Load fine-tuned weights14fine_tuned_model_path = "models/finetuned_BERT_5k_epoch_5.model"15model.load_state_dict(torch.load(fine_tuned_model_path, map_location=torch.device('cpu')))16 17# Preprocess the new text18tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)19 20# Function to map numeric label to dark pattern name21def get_dark_pattern_name(label):22    reverse_label_dict = {v: k for k, v in label_dict.items()}23    return reverse_label_dict[label]24 25def find_dark_pattern(text_predict):26    encoded_text = tokenizer.encode_plus(27        text_predict,28        add_special_tokens=True,29        return_attention_mask=True,30        pad_to_max_length=True,31        max_length=256,32        return_tensors='pt'33    )34 35    # Making the predictions36    model.eval()37 38    with torch.no_grad():39        inputs = {40            'input_ids': encoded_text['input_ids'],41            'attention_mask': encoded_text['attention_mask']42        }43        outputs = model(**inputs)44 45    predictions = outputs.logits46 47    # Post-process the predictions48    probabilities = torch.nn.functional.softmax(predictions, dim=1)49    predicted_label = torch.argmax(probabilities, dim=1).item()50 51    return get_dark_pattern_name(predicted_label)52 53# Streamlit app54def main():55 56    # navigation57    st.page_link("app.py", label="Home", icon="🏠")58    st.page_link("pages/page_1.py", label="Training Metrics", icon="1️⃣")59    # st.page_link("pages/page_2.py", label="Page 2", icon="2️⃣")60    st.page_link("https://github.com/4darsh-Dev/CogniGaurd", label="GitHub", icon="🌎")61    # Set page title62    st.title("Dark Pattern Detector")63 64    # Display welcome message65    st.write("Welcome to Dark Pattern Detector powered by CogniGuard")66    67    #68    st.write("#### Built with Fine-Tuned BERT and Hugging Face Transformers")69    70 71    # Get user input72    text_to_predict = st.text_input("Enter the text to find Dark Pattern")73 74    if st.button("Predict"):75        # Record the start time76        start_time = time.time()77 78        # Add a simple progress message79        st.write("Predicting Dark Pattern...")80 81 82        progress_bar = st.progress(0)83 84        for i in tqdm(range(10), desc="Predicting", unit="prediction"):85            predicted_darkp = find_dark_pattern(text_to_predict)86            progress_bar.progress((i + 1) * 10)87            time.sleep(0.5)  # Simulate some processing time88 89        # Record the end time90        end_time = time.time()91 92        # Calculate the total time taken93        total_time = end_time - start_time94 95        # Display the predicted dark pattern and total time taken96        st.write(f"Result: {predicted_darkp}")97        st.write(f"Total Time Taken: {total_time:.2f} seconds")98 99        100 101 102    # Add footer103    st.markdown('<p style="text-align:center;">Made with ❤️ by <a href="https://www.adarshmaurya.onionreads.com">Adarsh Maurya</a></p>', unsafe_allow_html=True)104 105    # Add page visit count106    with open("assets/counter.txt", "r") as f:107        pVisit = int(f.read())108 109    pVisit += 1110 111    with open("assets/counter.txt", "w") as f:112        f.write(str(pVisit))113 114 115    # Display page visit count116    st.markdown(f'<p style="text-align:center;">Page Visits: {pVisit}</p>', unsafe_allow_html=True)117 118 119# Run the app120if __name__ == "__main__":121    main()122 123