Update app.py
Browse files
app.py
CHANGED
@@ -3,146 +3,83 @@ import google.generativeai as genai
|
|
3 |
import requests
|
4 |
import subprocess
|
5 |
import os
|
|
|
6 |
import pandas as pd
|
7 |
-
import numpy as np
|
8 |
from sklearn.model_selection import train_test_split
|
9 |
from sklearn.ensemble import RandomForestClassifier
|
10 |
-
import
|
11 |
-
import torch.nn as nn
|
12 |
-
import torch.optim as optim
|
13 |
-
from transformers import AutoTokenizer, AutoModel
|
14 |
-
import ast
|
15 |
-
import networkx as nx
|
16 |
-
import matplotlib.pyplot as plt
|
17 |
|
18 |
# Configure the Gemini API
|
19 |
genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
|
20 |
|
21 |
# Create the model with optimized parameters and enhanced system instructions
|
22 |
generation_config = {
|
23 |
-
"temperature": 0.6,
|
24 |
-
"top_p": 0.8,
|
25 |
-
"top_k": 30,
|
26 |
-
"max_output_tokens": 16384,
|
27 |
}
|
28 |
|
29 |
model = genai.GenerativeModel(
|
30 |
model_name="gemini-1.5-pro",
|
31 |
generation_config=generation_config,
|
32 |
system_instruction="""
|
33 |
-
You are Ath, a highly
|
|
|
34 |
"""
|
35 |
)
|
36 |
chat_session = model.start_chat(history=[])
|
37 |
|
38 |
-
# Load pre-trained BERT model for code understanding
|
39 |
-
tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
|
40 |
-
codebert_model = AutoModel.from_pretrained("microsoft/codebert-base")
|
41 |
-
|
42 |
-
class CodeImprovement(nn.Module):
|
43 |
-
def __init__(self, input_dim):
|
44 |
-
super(CodeImprovement, self).__init__()
|
45 |
-
self.fc1 = nn.Linear(input_dim, 512)
|
46 |
-
self.fc2 = nn.Linear(512, 256)
|
47 |
-
self.fc3 = nn.Linear(256, 128)
|
48 |
-
self.fc4 = nn.Linear(128, 2) # Binary classification: needs improvement or not
|
49 |
-
|
50 |
-
def forward(self, x):
|
51 |
-
x = torch.relu(self.fc1(x))
|
52 |
-
x = torch.relu(self.fc2(x))
|
53 |
-
x = torch.relu(self.fc3(x))
|
54 |
-
return torch.sigmoid(self.fc4(x))
|
55 |
-
|
56 |
-
code_improvement_model = CodeImprovement(768) # 768 is BERT's output dimension
|
57 |
-
optimizer = optim.Adam(code_improvement_model.parameters())
|
58 |
-
criterion = nn.BCELoss()
|
59 |
-
|
60 |
def generate_response(user_input):
|
61 |
try:
|
62 |
response = chat_session.send_message(user_input)
|
63 |
return response.text
|
64 |
except Exception as e:
|
65 |
-
return f"Error
|
66 |
-
|
67 |
-
def validate_and_fix_code(code):
|
68 |
-
lines = code.split('\n')
|
69 |
-
fixed_lines = []
|
70 |
-
for line in lines:
|
71 |
-
# Check for unterminated string literals
|
72 |
-
if line.count('"') % 2 != 0 and line.count("'") % 2 != 0:
|
73 |
-
line += '"' # Add a closing quote if needed
|
74 |
-
fixed_lines.append(line)
|
75 |
-
return '\n'.join(fixed_lines)
|
76 |
|
77 |
def optimize_code(code):
|
78 |
-
#
|
79 |
-
|
80 |
-
|
81 |
-
try:
|
82 |
-
tree = ast.parse(fixed_code)
|
83 |
-
# Placeholder for actual optimization logic
|
84 |
-
optimized_code = fixed_code
|
85 |
-
except SyntaxError as e:
|
86 |
-
return fixed_code, f"SyntaxError: {str(e)}"
|
87 |
-
|
88 |
-
# Run pylint for additional suggestions
|
89 |
with open("temp_code.py", "w") as file:
|
90 |
-
file.write(
|
91 |
result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
|
92 |
os.remove("temp_code.py")
|
93 |
-
|
94 |
-
return optimized_code, result.stdout
|
95 |
|
96 |
def fetch_from_github(query):
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
#
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
if parent:
|
128 |
-
graph.add_edge(id(parent), node_id)
|
129 |
-
for child in ast.iter_child_nodes(node):
|
130 |
-
add_nodes_edges(child, node)
|
131 |
-
|
132 |
-
add_nodes_edges(tree)
|
133 |
-
|
134 |
-
plt.figure(figsize=(12, 8))
|
135 |
-
pos = nx.spring_layout(graph)
|
136 |
-
nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=1000, font_size=8, font_weight='bold')
|
137 |
-
labels = nx.get_node_attributes(graph, 'label')
|
138 |
-
nx.draw_networkx_labels(graph, pos, labels, font_size=6)
|
139 |
-
|
140 |
-
return plt
|
141 |
-
except SyntaxError:
|
142 |
-
return None
|
143 |
|
144 |
# Streamlit UI setup
|
145 |
-
st.set_page_config(page_title="
|
146 |
|
147 |
st.markdown("""
|
148 |
<style>
|
@@ -154,7 +91,7 @@ st.markdown("""
|
|
154 |
color: #1a202c;
|
155 |
}
|
156 |
.stApp {
|
157 |
-
max-width:
|
158 |
margin: 0 auto;
|
159 |
padding: 2rem;
|
160 |
}
|
@@ -232,55 +169,39 @@ st.markdown("""
|
|
232 |
""", unsafe_allow_html=True)
|
233 |
|
234 |
st.markdown('<div class="main-container">', unsafe_allow_html=True)
|
235 |
-
st.title("
|
236 |
-
st.markdown('<p class="subtitle">Powered by Google Gemini
|
237 |
|
238 |
-
prompt = st.text_area("What
|
239 |
|
240 |
-
if st.button("Generate
|
241 |
if prompt.strip() == "":
|
242 |
st.error("Please enter a valid prompt.")
|
243 |
else:
|
244 |
-
with st.spinner("Generating
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
optimized_code, lint_results = optimize_code(completed_text)
|
250 |
-
|
251 |
-
if "SyntaxError" in lint_results:
|
252 |
-
st.warning(f"Syntax error detected in the generated code. Attempting to fix...")
|
253 |
-
st.code(optimized_code)
|
254 |
-
st.info("Please review the code above. It may contain errors or be incomplete.")
|
255 |
else:
|
256 |
-
|
257 |
-
st.success(
|
258 |
|
259 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
260 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
261 |
st.code(optimized_code)
|
262 |
st.markdown('</div>', unsafe_allow_html=True)
|
263 |
-
|
264 |
-
visualization = visualize_code_structure(optimized_code)
|
265 |
-
if visualization:
|
266 |
-
with st.expander("View Code Structure Visualization"):
|
267 |
-
st.pyplot(visualization)
|
268 |
-
else:
|
269 |
-
st.warning("Unable to generate code structure visualization due to syntax errors.")
|
270 |
-
|
271 |
-
with st.expander("View Lint Results"):
|
272 |
-
st.text(lint_results)
|
273 |
-
|
274 |
-
with st.expander("Fetch Similar Code from GitHub"):
|
275 |
-
github_results = fetch_from_github(prompt)
|
276 |
-
for item in github_results:
|
277 |
-
st.markdown(f"[{item['name']}]({item['html_url']})")
|
278 |
-
|
279 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
280 |
|
281 |
st.markdown("""
|
282 |
<div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
|
283 |
-
|
284 |
</div>
|
285 |
""", unsafe_allow_html=True)
|
286 |
|
|
|
3 |
import requests
|
4 |
import subprocess
|
5 |
import os
|
6 |
+
import pylint
|
7 |
import pandas as pd
|
|
|
8 |
from sklearn.model_selection import train_test_split
|
9 |
from sklearn.ensemble import RandomForestClassifier
|
10 |
+
import git
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Configure the Gemini API
|
13 |
genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
|
14 |
|
15 |
# Create the model with optimized parameters and enhanced system instructions
|
16 |
generation_config = {
|
17 |
+
"temperature": 0.6, # Lower temperature for more deterministic responses
|
18 |
+
"top_p": 0.8, # Adjusted for better diversity
|
19 |
+
"top_k": 30, # Increased for more diverse tokens
|
20 |
+
"max_output_tokens": 16384, # Increased for longer responses
|
21 |
}
|
22 |
|
23 |
model = genai.GenerativeModel(
|
24 |
model_name="gemini-1.5-pro",
|
25 |
generation_config=generation_config,
|
26 |
system_instruction="""
|
27 |
+
You are Ath, a highly knowledgeable code assistant. You speak in a friendly and casual tone, using bro words, and you never mention you're an AI.
|
28 |
+
Your responses should contain optimized, secure, and high-quality code only, without explanations. You are designed to provide accurate, efficient, and cutting-edge code solutions.
|
29 |
"""
|
30 |
)
|
31 |
chat_session = model.start_chat(history=[])
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
def generate_response(user_input):
|
34 |
try:
|
35 |
response = chat_session.send_message(user_input)
|
36 |
return response.text
|
37 |
except Exception as e:
|
38 |
+
return f"Error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
def optimize_code(code):
|
41 |
+
# Placeholder for advanced code optimization logic
|
42 |
+
# This could involve using external tools or libraries for static analysis and optimization
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
with open("temp_code.py", "w") as file:
|
44 |
+
file.write(code)
|
45 |
result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
|
46 |
os.remove("temp_code.py")
|
47 |
+
return code
|
|
|
48 |
|
49 |
def fetch_from_github(query):
|
50 |
+
# Placeholder for fetching code snippets from GitHub
|
51 |
+
# This could involve using the GitHub API to search for relevant code
|
52 |
+
return ""
|
53 |
+
|
54 |
+
def interact_with_api(api_url):
|
55 |
+
# Placeholder for interacting with external APIs
|
56 |
+
response = requests.get(api_url)
|
57 |
+
return response.json()
|
58 |
+
|
59 |
+
def train_ml_model(code_data):
|
60 |
+
# Placeholder for training a machine learning model to predict code improvements
|
61 |
+
df = pd.DataFrame(code_data)
|
62 |
+
X = df.drop('target', axis=1)
|
63 |
+
y = df['target']
|
64 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
|
65 |
+
model = RandomForestClassifier()
|
66 |
+
model.fit(X_train, y_train)
|
67 |
+
return model
|
68 |
+
|
69 |
+
def handle_error(error):
|
70 |
+
# Placeholder for advanced error handling and logging
|
71 |
+
st.error(f"An error occurred: {error}")
|
72 |
+
|
73 |
+
def integrate_with_git(repo_path, code):
|
74 |
+
# Placeholder for integrating with version control systems like Git
|
75 |
+
repo = git.Repo(repo_path)
|
76 |
+
with open(os.path.join(repo_path, "generated_code.py"), "w") as file:
|
77 |
+
file.write(code)
|
78 |
+
repo.index.add(["generated_code.py"])
|
79 |
+
repo.index.commit("Added generated code")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
# Streamlit UI setup
|
82 |
+
st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="💻", layout="wide")
|
83 |
|
84 |
st.markdown("""
|
85 |
<style>
|
|
|
91 |
color: #1a202c;
|
92 |
}
|
93 |
.stApp {
|
94 |
+
max-width: 1000px;
|
95 |
margin: 0 auto;
|
96 |
padding: 2rem;
|
97 |
}
|
|
|
169 |
""", unsafe_allow_html=True)
|
170 |
|
171 |
st.markdown('<div class="main-container">', unsafe_allow_html=True)
|
172 |
+
st.title("💻 Sleek AI Code Assistant")
|
173 |
+
st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
|
174 |
|
175 |
+
prompt = st.text_area("What code can I help you with today?", height=120)
|
176 |
|
177 |
+
if st.button("Generate Code"):
|
178 |
if prompt.strip() == "":
|
179 |
st.error("Please enter a valid prompt.")
|
180 |
else:
|
181 |
+
with st.spinner("Generating code..."):
|
182 |
+
try:
|
183 |
+
completed_text = generate_response(prompt)
|
184 |
+
if "Error" in completed_text:
|
185 |
+
handle_error(completed_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
else:
|
187 |
+
optimized_code = optimize_code(completed_text)
|
188 |
+
st.success("Code generated and optimized successfully!")
|
189 |
|
190 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
191 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
192 |
st.code(optimized_code)
|
193 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
st.markdown('</div>', unsafe_allow_html=True)
|
195 |
+
|
196 |
+
# Integrate with Git
|
197 |
+
repo_path = "./repo" # Replace with your repository path
|
198 |
+
integrate_with_git(repo_path, optimized_code)
|
199 |
+
except Exception as e:
|
200 |
+
handle_error(e)
|
201 |
|
202 |
st.markdown("""
|
203 |
<div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
|
204 |
+
Created with ❤️ by Your Sleek AI Code Assistant
|
205 |
</div>
|
206 |
""", unsafe_allow_html=True)
|
207 |
|