deepugaur commited on
Commit
92203ec
·
verified ·
1 Parent(s): 2e2b62c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -56
app.py CHANGED
@@ -1,63 +1,75 @@
1
 
2
 
3
-
4
-
5
  import streamlit as st
6
- import tensorflow as tf
7
  import numpy as np
8
- import pickle
9
-
10
- # Set page title and header
11
- st.set_page_config(page_title="Prompt Injection Detection and Prevention")
12
- st.title("Prompt Injection Detection and Prevention")
13
- st.subheader("Classify prompts as malicious or valid and understand predictions using LIME.")
 
14
 
15
  # Load the trained model
16
  @st.cache_resource
17
- def load_model(model_path):
18
- try:
19
- return tf.keras.models.load_model(model_path)
20
- except Exception as e:
21
- st.error(f"Error loading model: {e}")
22
- return None
23
-
24
- # Load the tokenizer
25
- @st.cache_resource
26
- def load_tokenizer(tokenizer_path):
27
- try:
28
- with open(tokenizer_path, "rb") as f:
29
- return pickle.load(f)
30
- except Exception as e:
31
- st.error(f"Error loading tokenizer: {e}")
32
- return None
33
-
34
- # Paths to your files (these should be present in your Hugging Face repository)
35
- MODEL_PATH = "model.h5"
36
- TOKENIZER_PATH = "tokenizer.pkl"
37
-
38
- # Load model and tokenizer
39
- model = load_model(MODEL_PATH)
40
- tokenizer = load_tokenizer(TOKENIZER_PATH)
41
-
42
- if model and tokenizer:
43
- st.success("Model and tokenizer loaded successfully!")
44
-
45
- # User input for prompt classification
46
- st.write("## Classify a Prompt")
47
- user_input = st.text_area("Enter a prompt for classification:")
48
- if st.button("Classify"):
49
- if user_input:
50
- # Preprocess the user input
51
- sequence = tokenizer.texts_to_sequences([user_input])
52
- padded_sequence = tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=50)
53
-
54
- # Make prediction
55
- prediction = model.predict(padded_sequence)
56
- label = "Malicious" if prediction[0] > 0.5 else "Valid"
57
- st.write(f"Prediction: **{label}** (Confidence: {prediction[0][0]:.2f})")
58
- else:
59
- st.error("Please enter a prompt for classification.")
60
-
61
- # Footer
62
- st.write("---")
63
- st.caption("Developed for detecting and preventing prompt injection attacks.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
 
 
 
3
  import streamlit as st
 
4
  import numpy as np
5
+ import pandas as pd
6
+ from tensorflow.keras.preprocessing.text import Tokenizer
7
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
8
+ from tensorflow.keras.models import load_model
9
+ from lime.lime_text import LimeTextExplainer
10
+ import matplotlib.pyplot as plt
11
+ import seaborn as sns
12
 
13
  # Load the trained model
14
  @st.cache_resource
15
+ def load_trained_model():
16
+ model = load_model("deep_learning_model.h5")
17
+ return model
18
+
19
+ model = load_trained_model()
20
+
21
+ # Tokenizer setup
22
+ tokenizer = Tokenizer(num_words=5000)
23
+ max_length = 100
24
+
25
+ # Load Data
26
+ @st.cache_data
27
+ def load_data():
28
+ data = pd.read_csv("train prompt.csv", sep=',', quoting=3, encoding='ISO-8859-1', on_bad_lines='skip', engine='python')
29
+ data['label'] = data['label'].replace({'valid': 0, 'malicious': 1})
30
+ return data
31
+
32
+ data = load_data()
33
+ tokenizer.fit_on_texts(data['input'].values)
34
+
35
+ # Preprocessing functions
36
+ def preprocess_prompt(prompt, tokenizer, max_length):
37
+ sequence = tokenizer.texts_to_sequences([prompt])
38
+ padded_sequence = pad_sequences(sequence, maxlen=max_length)
39
+ return padded_sequence
40
+
41
+ def detect_prompt(prompt, model, tokenizer, max_length):
42
+ processed_prompt = preprocess_prompt(prompt, tokenizer, max_length)
43
+ prediction = model.predict(processed_prompt)[0][0]
44
+ class_label = 'Malicious' if prediction >= 0.5 else 'Valid'
45
+ confidence_score = prediction * 100 if prediction >= 0.5 else (1 - prediction) * 100
46
+ return class_label, confidence_score
47
+
48
+ # Load model
49
+ model = load_trained_model()
50
+
51
+ # Streamlit app
52
+ st.title("Prompt Injection Attack Detection")
53
+ st.write("This application detects malicious prompts to prevent injection attacks.")
54
+
55
+ prompt = st.text_input("Enter a prompt to analyze:")
56
+
57
+ if prompt:
58
+ class_label, confidence = detect_prompt(prompt, model, tokenizer, max_length)
59
+ st.write(f"### Prediction: {class_label}")
60
+ st.write(f"Confidence: {confidence:.2f}%")
61
+
62
+ # LIME explanation
63
+ st.write("Generating LIME Explanation...")
64
+ explainer = LimeTextExplainer(class_names=["Valid", "Malicious"])
65
+
66
+ def predict_fn(prompts):
67
+ sequences = tokenizer.texts_to_sequences(prompts)
68
+ padded_sequences = pad_sequences(sequences, maxlen=max_length)
69
+ predictions = model.predict(padded_sequences)
70
+ return np.hstack([1 - predictions, predictions])
71
+
72
+ explanation = explainer.explain_instance(prompt, predict_fn, num_features=10)
73
+ fig = explanation.as_pyplot_figure()
74
+ st.pyplot(fig)
75
+