Added app.py
Browse files
app.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
from transformers import RobertaTokenizer, T5ForConditionalGeneration
|
4 |
+
import pickle
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
from torch.serialization import safe_globals, add_safe_globals
|
8 |
+
|
9 |
+
add_safe_globals([
|
10 |
+
"transformers.models.t5.modeling_t5.T5ForConditionalGeneration"
|
11 |
+
])
|
12 |
+
|
13 |
+
# Set page configuration
|
14 |
+
st.set_page_config(
|
15 |
+
page_title="CodeT5 Query Generator",
|
16 |
+
page_icon="🤖",
|
17 |
+
layout="wide",
|
18 |
+
)
|
19 |
+
|
20 |
+
# CSS styling
|
21 |
+
st.markdown("""
|
22 |
+
<style>
|
23 |
+
.main-header {
|
24 |
+
font-size: 2.5rem;
|
25 |
+
color: #4527A0;
|
26 |
+
text-align: center;
|
27 |
+
margin-bottom: 1rem;
|
28 |
+
}
|
29 |
+
.sub-header {
|
30 |
+
font-size: 1.5rem;
|
31 |
+
color: #5E35B1;
|
32 |
+
margin-bottom: 1rem;
|
33 |
+
}
|
34 |
+
.response-container {
|
35 |
+
background-color: #f0f2f6;
|
36 |
+
border-radius: 10px;
|
37 |
+
padding: 20px;
|
38 |
+
margin-top: 20px;
|
39 |
+
}
|
40 |
+
.stButton>button {
|
41 |
+
background-color: #673AB7;
|
42 |
+
color: white;
|
43 |
+
}
|
44 |
+
.stButton>button:hover {
|
45 |
+
background-color: #5E35B1;
|
46 |
+
color: white;
|
47 |
+
}
|
48 |
+
.footer {
|
49 |
+
text-align: center;
|
50 |
+
margin-top: 3rem;
|
51 |
+
color: #9575CD;
|
52 |
+
}
|
53 |
+
</style>
|
54 |
+
""", unsafe_allow_html=True)
|
55 |
+
|
56 |
+
# App header
|
57 |
+
st.markdown("<h1 class='main-header'>Network Query Generator</h1>", unsafe_allow_html=True)
|
58 |
+
st.markdown("<h2 class='sub-header'>Ask questions and get specialized network related queries</h2>", unsafe_allow_html=True)
|
59 |
+
|
60 |
+
# Sidebar for model information and settings
|
61 |
+
with st.sidebar:
|
62 |
+
st.title("About")
|
63 |
+
st.info("This app uses a fine-tuned CodeT5 model to generate specialized queries from natural language questions.")
|
64 |
+
|
65 |
+
st.title("Model Settings")
|
66 |
+
max_length = st.slider("Maximum output length", 32, 256, 128)
|
67 |
+
num_beams = st.slider("Number of beams", 1, 10, 4)
|
68 |
+
temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
|
69 |
+
|
70 |
+
st.title("Model Info")
|
71 |
+
st.markdown("**Base model:** Salesforce/codet5-small")
|
72 |
+
st.markdown("**Fine-tuned on:** Custom dataset")
|
73 |
+
|
74 |
+
MODEL_PATH = "finetuned_codet5_small.pkl"
|
75 |
+
|
76 |
+
# Function to load the model
|
77 |
+
@st.cache_resource
|
78 |
+
def load_model(file_path):
|
79 |
+
"""Load the tokenizer and model using a safe approach"""
|
80 |
+
model_name = "Salesforce/codet5-small"
|
81 |
+
tokenizer = RobertaTokenizer.from_pretrained(model_name)
|
82 |
+
|
83 |
+
try:
|
84 |
+
with safe_globals(["transformers.models.t5.modeling_t5.T5ForConditionalGeneration"]):
|
85 |
+
model = torch.load(file_path, map_location=torch.device("cuda" if torch.cuda.is_available() else "cpu"), weights_only=False)
|
86 |
+
|
87 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
88 |
+
model = model.to(device)
|
89 |
+
model.eval()
|
90 |
+
return tokenizer, model, device, None
|
91 |
+
except Exception as e:
|
92 |
+
try:
|
93 |
+
# Initialize base model
|
94 |
+
base_model = T5ForConditionalGeneration.from_pretrained(model_name)
|
95 |
+
|
96 |
+
# Load state dict
|
97 |
+
with safe_globals(["transformers.models.t5.modeling_t5.T5ForConditionalGeneration"]):
|
98 |
+
state_dict = torch.load(file_path, map_location="cpu")
|
99 |
+
|
100 |
+
# If the loaded object is already a model, extract just the state dict
|
101 |
+
if hasattr(state_dict, 'state_dict'):
|
102 |
+
state_dict = state_dict.state_dict()
|
103 |
+
|
104 |
+
# Load the state dict into the base model
|
105 |
+
base_model.load_state_dict(state_dict)
|
106 |
+
|
107 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
108 |
+
base_model = base_model.to(device)
|
109 |
+
base_model.eval()
|
110 |
+
return tokenizer, base_model, device, None
|
111 |
+
except Exception as e2:
|
112 |
+
return None, None, None, f"Error loading model: {e2}"
|
113 |
+
|
114 |
+
# Function to generate query
|
115 |
+
def generate_query(question, tokenizer, model, device, max_length=128, num_beams=4, temperature=0.7):
|
116 |
+
"""Generate a query based on the user's question"""
|
117 |
+
inputs = tokenizer(question, return_tensors="pt", padding=True, truncation=True, max_length=128)
|
118 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
119 |
+
|
120 |
+
with torch.no_grad():
|
121 |
+
generated_ids = model.generate(
|
122 |
+
input_ids=inputs["input_ids"],
|
123 |
+
attention_mask=inputs["attention_mask"],
|
124 |
+
max_length=max_length,
|
125 |
+
num_beams=num_beams,
|
126 |
+
temperature=temperature,
|
127 |
+
early_stopping=True
|
128 |
+
)
|
129 |
+
|
130 |
+
generated_query = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
|
131 |
+
return generated_query
|
132 |
+
|
133 |
+
# Load the model at startup
|
134 |
+
with st.spinner("Loading model... (this may take a moment)"):
|
135 |
+
tokenizer, model, device, error_message = load_model(MODEL_PATH)
|
136 |
+
|
137 |
+
if model is not None:
|
138 |
+
st.sidebar.success(f"Model loaded successfully!")
|
139 |
+
else:
|
140 |
+
st.sidebar.error(f"Failed to load model: {error_message}")
|
141 |
+
|
142 |
+
# Main app area
|
143 |
+
question = st.text_area("Enter your question here:", height=100, placeholder="Example: How can I secure my network against DDoS attacks?")
|
144 |
+
|
145 |
+
# a button to generate the response
|
146 |
+
col1, col2, col3 = st.columns([1, 1, 1])
|
147 |
+
with col2:
|
148 |
+
generate_button = st.button("Generate Query", use_container_width=True)
|
149 |
+
|
150 |
+
# Display generation result
|
151 |
+
if generate_button and question:
|
152 |
+
if model is not None and tokenizer is not None:
|
153 |
+
with st.spinner("Generating response..."):
|
154 |
+
# Add a slight delay for user experience
|
155 |
+
time.sleep(0.5)
|
156 |
+
response = generate_query(
|
157 |
+
question,
|
158 |
+
tokenizer,
|
159 |
+
model,
|
160 |
+
device,
|
161 |
+
max_length=max_length,
|
162 |
+
num_beams=num_beams,
|
163 |
+
temperature=temperature
|
164 |
+
)
|
165 |
+
|
166 |
+
st.markdown("<div class='response-container'>", unsafe_allow_html=True)
|
167 |
+
st.markdown("### Generated Query:")
|
168 |
+
st.code(response, language="sql")
|
169 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
170 |
+
else:
|
171 |
+
st.error("Model could not be loaded. Please check if the model file exists at the correct path.")
|
172 |
+
|
173 |
+
# Example questions
|
174 |
+
with st.expander("Example Questions"):
|
175 |
+
example_questions = [
|
176 |
+
"Show me the current configuration of the router.",
|
177 |
+
"Get the total number of ['firewall', 'router', 'switch', 'server', 'access_point'] with high CPU usage.",
|
178 |
+
"Get the total bandwidth usage of access_point FW1.",
|
179 |
+
"Get the total uptime of all ['firewall', 'router', 'switch', 'server', 'access_point'].",
|
180 |
+
"Get the total number of ['firewall', 'router', 'switch', 'server', 'access_point']."
|
181 |
+
]
|
182 |
+
|
183 |
+
for i in range(len(example_questions)):
|
184 |
+
st.write(example_questions[i])
|
185 |
+
|
186 |
+
# Footer
|
187 |
+
st.markdown("<p class='footer'>Powered by CodeT5 - Fine-tuned for specialized queries</p>", unsafe_allow_html=True)
|