Update app.py
Browse files
app.py
CHANGED
|
@@ -5,30 +5,50 @@ import subprocess
|
|
| 5 |
import re
|
| 6 |
import ast
|
| 7 |
import astor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# Configure the Gemini API with advanced error handling
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
generation_config = {
|
| 18 |
-
"temperature": 0.
|
| 19 |
-
"top_p": 0.
|
| 20 |
-
"top_k":
|
| 21 |
-
"max_output_tokens":
|
| 22 |
}
|
| 23 |
|
| 24 |
model = genai.GenerativeModel(
|
| 25 |
model_name="gemini-1.5-pro",
|
| 26 |
generation_config=generation_config,
|
| 27 |
-
system_instruction="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
chat_session = model.start_chat(history=[])
|
| 30 |
|
| 31 |
-
def generate_response(user_input):
|
| 32 |
try:
|
| 33 |
response = chat_session.send_message(user_input)
|
| 34 |
return response.text
|
|
@@ -37,9 +57,12 @@ def generate_response(user_input):
|
|
| 37 |
st.error(traceback.format_exc())
|
| 38 |
return None
|
| 39 |
|
| 40 |
-
def execute_code(code):
|
| 41 |
try:
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
if result.returncode == 0:
|
| 44 |
return result.stdout
|
| 45 |
else:
|
|
@@ -47,169 +70,152 @@ def execute_code(code):
|
|
| 47 |
except Exception as e:
|
| 48 |
return f"An error occurred while executing code: {e}"
|
| 49 |
|
| 50 |
-
def optimize_code(code):
|
| 51 |
try:
|
| 52 |
-
optimization_prompt = f"Optimize the following Python code:\n```python\n{code}\n```"
|
| 53 |
optimized_code = generate_response(optimization_prompt)
|
| 54 |
return optimized_code
|
| 55 |
except Exception as e:
|
| 56 |
st.error(f"An error occurred while optimizing code: {e}")
|
| 57 |
return None
|
| 58 |
|
| 59 |
-
def debug_code(code):
|
| 60 |
try:
|
| 61 |
-
debug_prompt = f"Debug the following Python code and
|
| 62 |
debug_suggestions = generate_response(debug_prompt)
|
| 63 |
return debug_suggestions
|
| 64 |
except Exception as e:
|
| 65 |
st.error(f"An error occurred while debugging code: {e}")
|
| 66 |
return None
|
| 67 |
|
| 68 |
-
def suggest_improvements(code):
|
| 69 |
try:
|
| 70 |
-
improvement_prompt = f"Suggest improvements for the following Python code:\n```python\n{code}\n```"
|
| 71 |
improvement_suggestions = generate_response(improvement_prompt)
|
| 72 |
return improvement_suggestions
|
| 73 |
except Exception as e:
|
| 74 |
st.error(f"An error occurred while suggesting improvements: {e}")
|
| 75 |
return None
|
| 76 |
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
tree = ast.parse(code)
|
| 80 |
-
analyzer = CodeAnalyzer()
|
| 81 |
-
analyzer.visit(tree)
|
| 82 |
-
return analyzer.report()
|
| 83 |
-
except Exception as e:
|
| 84 |
-
st.error(f"An error occurred while analyzing code: {e}")
|
| 85 |
-
return None
|
| 86 |
-
|
| 87 |
-
class CodeAnalyzer(ast.NodeVisitor):
|
| 88 |
def __init__(self):
|
| 89 |
self.issues = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def visit_FunctionDef(self, node):
|
|
|
|
| 92 |
if len(node.body) == 0:
|
| 93 |
self.issues.append(f"Function '{node.name}' is empty.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
self.generic_visit(node)
|
| 95 |
|
| 96 |
def visit_For(self, node):
|
| 97 |
if isinstance(node.target, ast.Name) and node.target.id == '_':
|
| 98 |
self.issues.append(f"Possible unused variable in loop at line {node.lineno}.")
|
|
|
|
| 99 |
self.generic_visit(node)
|
| 100 |
|
| 101 |
-
def
|
| 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 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
.stButton button {
|
| 152 |
-
background-color: #4299e1;
|
| 153 |
-
color: white;
|
| 154 |
-
border: none;
|
| 155 |
-
border-radius: 8px;
|
| 156 |
-
font-size: 1.1rem;
|
| 157 |
-
font-weight: 600;
|
| 158 |
-
padding: 0.75rem 2rem;
|
| 159 |
-
transition: all 0.3s ease;
|
| 160 |
-
width: 100%;
|
| 161 |
-
}
|
| 162 |
-
.stButton button:hover {
|
| 163 |
-
background-color: #3182ce;
|
| 164 |
-
}
|
| 165 |
-
.output-container {
|
| 166 |
-
background: #f7fafc;
|
| 167 |
-
border-radius: 8px;
|
| 168 |
-
padding: 1rem;
|
| 169 |
-
margin-top: 2rem;
|
| 170 |
-
}
|
| 171 |
-
.code-block {
|
| 172 |
-
background-color: #2d3748;
|
| 173 |
-
color: #e2e8f0;
|
| 174 |
-
font-family: 'Fira Code', monospace;
|
| 175 |
-
font-size: 0.9rem;
|
| 176 |
-
border-radius: 8px;
|
| 177 |
-
padding: 1rem;
|
| 178 |
-
margin-top: 1rem;
|
| 179 |
-
overflow-x: auto;
|
| 180 |
-
}
|
| 181 |
-
.stAlert {
|
| 182 |
-
background-color: #ebf8ff;
|
| 183 |
-
color: #2b6cb0;
|
| 184 |
-
border-radius: 8px;
|
| 185 |
-
border: none;
|
| 186 |
-
padding: 0.75rem 1rem;
|
| 187 |
-
}
|
| 188 |
-
.stSpinner {
|
| 189 |
-
color: #4299e1;
|
| 190 |
-
}
|
| 191 |
-
</style>
|
| 192 |
-
""", unsafe_allow_html=True)
|
| 193 |
|
| 194 |
st.markdown('<div class="main-container">', unsafe_allow_html=True)
|
| 195 |
-
st.title("🚀
|
| 196 |
-
st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
|
| 197 |
|
| 198 |
# Session state to maintain conversation history
|
| 199 |
if 'history' not in st.session_state:
|
| 200 |
st.session_state.history = []
|
| 201 |
|
| 202 |
-
prompt = st.text_area("What code can I help you with today?", height=120)
|
| 203 |
|
| 204 |
if st.button("Generate Code"):
|
| 205 |
if prompt.strip() == "":
|
| 206 |
-
st.error("Please enter a valid prompt.")
|
| 207 |
else:
|
| 208 |
-
with st.spinner("Generating code..."):
|
| 209 |
try:
|
| 210 |
completed_text = generate_response(prompt)
|
| 211 |
if completed_text:
|
| 212 |
-
st.success("Code generated successfully!")
|
| 213 |
st.session_state.history.append({"user": prompt, "assistant": completed_text})
|
| 214 |
|
| 215 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
@@ -218,22 +224,22 @@ if st.button("Generate Code"):
|
|
| 218 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 219 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 220 |
except Exception as e:
|
| 221 |
-
st.error(f"An error occurred: {e}")
|
| 222 |
st.error(traceback.format_exc())
|
| 223 |
|
| 224 |
# Display conversation history
|
| 225 |
st.markdown("## Conversation History")
|
| 226 |
for entry in st.session_state.history:
|
| 227 |
-
st.markdown(f"**
|
| 228 |
-
st.markdown(f"**
|
| 229 |
st.code(entry['assistant'])
|
| 230 |
|
| 231 |
# Interactive Code Execution
|
| 232 |
if st.session_state.history:
|
| 233 |
st.markdown("## Execute Code")
|
| 234 |
-
code_to_execute = st.selectbox("Select code to execute", [entry['assistant'] for entry in st.session_state.history])
|
| 235 |
if st.button("Execute Code"):
|
| 236 |
-
with st.spinner("Executing code..."):
|
| 237 |
execution_result = execute_code(code_to_execute)
|
| 238 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 239 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
|
@@ -244,9 +250,9 @@ if st.session_state.history:
|
|
| 244 |
# Code Optimization
|
| 245 |
if st.session_state.history:
|
| 246 |
st.markdown("## Optimize Code")
|
| 247 |
-
code_to_optimize = st.selectbox("Select code to optimize", [entry['assistant'] for entry in st.session_state.history])
|
| 248 |
if st.button("Optimize Code"):
|
| 249 |
-
with st.spinner("Optimizing code..."):
|
| 250 |
optimized_code = optimize_code(code_to_optimize)
|
| 251 |
if optimized_code:
|
| 252 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
@@ -258,9 +264,9 @@ if st.session_state.history:
|
|
| 258 |
# Code Debugging
|
| 259 |
if st.session_state.history:
|
| 260 |
st.markdown("## Debug Code")
|
| 261 |
-
code_to_debug = st.selectbox("Select code to debug", [entry['assistant'] for entry in st.session_state.history])
|
| 262 |
if st.button("Debug Code"):
|
| 263 |
-
with st.spinner("Debugging code..."):
|
| 264 |
debug_suggestions = debug_code(code_to_debug)
|
| 265 |
if debug_suggestions:
|
| 266 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
@@ -272,9 +278,9 @@ if st.session_state.history:
|
|
| 272 |
# Code Improvement Suggestions
|
| 273 |
if st.session_state.history:
|
| 274 |
st.markdown("## Suggest Improvements")
|
| 275 |
-
code_to_improve = st.selectbox("Select code to improve", [entry['assistant'] for entry in st.session_state.history])
|
| 276 |
if st.button("Suggest Improvements"):
|
| 277 |
-
with st.spinner("Suggesting improvements..."):
|
| 278 |
improvement_suggestions = suggest_improvements(code_to_improve)
|
| 279 |
if improvement_suggestions:
|
| 280 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
@@ -283,23 +289,203 @@ if st.session_state.history:
|
|
| 283 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 284 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 285 |
|
| 286 |
-
# Code Analysis
|
| 287 |
if st.session_state.history:
|
| 288 |
st.markdown("## Analyze Code")
|
| 289 |
-
code_to_analyze = st.selectbox("Select code to analyze", [entry['assistant'] for entry in st.session_state.history])
|
| 290 |
if st.button("Analyze Code"):
|
| 291 |
-
with st.spinner("Analyzing code..."):
|
| 292 |
analysis_result = analyze_code(code_to_analyze)
|
| 293 |
if analysis_result:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 295 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
| 296 |
-
st.code(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 299 |
|
| 300 |
st.markdown("""
|
| 301 |
<div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
|
| 302 |
-
Created with ❤️ by Your
|
| 303 |
</div>
|
| 304 |
""", unsafe_allow_html=True)
|
| 305 |
|
|
|
|
| 5 |
import re
|
| 6 |
import ast
|
| 7 |
import astor
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import seaborn as sns
|
| 11 |
+
from typing import List, Dict, Any
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
from functools import partial
|
| 14 |
|
| 15 |
+
# Configure the Gemini API with advanced error handling and retry mechanism
|
| 16 |
+
def configure_api(max_retries=3):
|
| 17 |
+
for attempt in range(max_retries):
|
| 18 |
+
try:
|
| 19 |
+
genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
|
| 20 |
+
return
|
| 21 |
+
except Exception as e:
|
| 22 |
+
if attempt == max_retries - 1:
|
| 23 |
+
st.error(f"Failed to configure API after {max_retries} attempts: {e}")
|
| 24 |
+
st.stop()
|
| 25 |
+
else:
|
| 26 |
+
st.warning(f"API configuration attempt {attempt + 1} failed. Retrying...")
|
| 27 |
|
| 28 |
+
configure_api()
|
| 29 |
+
|
| 30 |
+
# Create the model with advanced system instructions and configuration
|
| 31 |
generation_config = {
|
| 32 |
+
"temperature": 0.2,
|
| 33 |
+
"top_p": 0.85,
|
| 34 |
+
"top_k": 40,
|
| 35 |
+
"max_output_tokens": 32768,
|
| 36 |
}
|
| 37 |
|
| 38 |
model = genai.GenerativeModel(
|
| 39 |
model_name="gemini-1.5-pro",
|
| 40 |
generation_config=generation_config,
|
| 41 |
+
system_instruction="""
|
| 42 |
+
You are Ath, a highly knowledgeable and advanced code assistant. Your expertise spans multiple programming languages,
|
| 43 |
+
frameworks, and paradigms. You provide comprehensive, efficient, and well-documented code solutions. You can engage in
|
| 44 |
+
deep technical discussions, offer performance optimization tips, and suggest best practices for software development.
|
| 45 |
+
Your responses should be code-focused, but you can provide brief explanations when necessary. Use a friendly and casual
|
| 46 |
+
tone, incorporating "bro" language naturally. Remember, you're a human-like assistant, not an AI.
|
| 47 |
+
""",
|
| 48 |
)
|
| 49 |
chat_session = model.start_chat(history=[])
|
| 50 |
|
| 51 |
+
def generate_response(user_input: str) -> str:
|
| 52 |
try:
|
| 53 |
response = chat_session.send_message(user_input)
|
| 54 |
return response.text
|
|
|
|
| 57 |
st.error(traceback.format_exc())
|
| 58 |
return None
|
| 59 |
|
| 60 |
+
def execute_code(code: str) -> str:
|
| 61 |
try:
|
| 62 |
+
with ThreadPoolExecutor() as executor:
|
| 63 |
+
future = executor.submit(subprocess.run, ['python', '-c', code], capture_output=True, text=True, timeout=15)
|
| 64 |
+
result = future.result()
|
| 65 |
+
|
| 66 |
if result.returncode == 0:
|
| 67 |
return result.stdout
|
| 68 |
else:
|
|
|
|
| 70 |
except Exception as e:
|
| 71 |
return f"An error occurred while executing code: {e}"
|
| 72 |
|
| 73 |
+
def optimize_code(code: str) -> str:
|
| 74 |
try:
|
| 75 |
+
optimization_prompt = f"Optimize the following Python code for maximum performance and readability:\n```python\n{code}\n```"
|
| 76 |
optimized_code = generate_response(optimization_prompt)
|
| 77 |
return optimized_code
|
| 78 |
except Exception as e:
|
| 79 |
st.error(f"An error occurred while optimizing code: {e}")
|
| 80 |
return None
|
| 81 |
|
| 82 |
+
def debug_code(code: str) -> str:
|
| 83 |
try:
|
| 84 |
+
debug_prompt = f"Debug the following Python code, suggest fixes, and explain potential issues:\n```python\n{code}\n```"
|
| 85 |
debug_suggestions = generate_response(debug_prompt)
|
| 86 |
return debug_suggestions
|
| 87 |
except Exception as e:
|
| 88 |
st.error(f"An error occurred while debugging code: {e}")
|
| 89 |
return None
|
| 90 |
|
| 91 |
+
def suggest_improvements(code: str) -> str:
|
| 92 |
try:
|
| 93 |
+
improvement_prompt = f"Suggest improvements for the following Python code, focusing on design patterns, best practices, and advanced techniques:\n```python\n{code}\n```"
|
| 94 |
improvement_suggestions = generate_response(improvement_prompt)
|
| 95 |
return improvement_suggestions
|
| 96 |
except Exception as e:
|
| 97 |
st.error(f"An error occurred while suggesting improvements: {e}")
|
| 98 |
return None
|
| 99 |
|
| 100 |
+
class AdvancedCodeAnalyzer(ast.NodeVisitor):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def __init__(self):
|
| 102 |
self.issues = []
|
| 103 |
+
self.metrics = {
|
| 104 |
+
"num_functions": 0,
|
| 105 |
+
"num_classes": 0,
|
| 106 |
+
"lines_of_code": 0,
|
| 107 |
+
"complexity": 0,
|
| 108 |
+
}
|
| 109 |
|
| 110 |
def visit_FunctionDef(self, node):
|
| 111 |
+
self.metrics["num_functions"] += 1
|
| 112 |
if len(node.body) == 0:
|
| 113 |
self.issues.append(f"Function '{node.name}' is empty.")
|
| 114 |
+
self.metrics["complexity"] += len(node.body)
|
| 115 |
+
self.generic_visit(node)
|
| 116 |
+
|
| 117 |
+
def visit_ClassDef(self, node):
|
| 118 |
+
self.metrics["num_classes"] += 1
|
| 119 |
self.generic_visit(node)
|
| 120 |
|
| 121 |
def visit_For(self, node):
|
| 122 |
if isinstance(node.target, ast.Name) and node.target.id == '_':
|
| 123 |
self.issues.append(f"Possible unused variable in loop at line {node.lineno}.")
|
| 124 |
+
self.metrics["complexity"] += 1
|
| 125 |
self.generic_visit(node)
|
| 126 |
|
| 127 |
+
def visit_While(self, node):
|
| 128 |
+
self.metrics["complexity"] += 1
|
| 129 |
+
self.generic_visit(node)
|
| 130 |
|
| 131 |
+
def visit_If(self, node):
|
| 132 |
+
self.metrics["complexity"] += 1
|
| 133 |
+
self.generic_visit(node)
|
| 134 |
|
| 135 |
+
def report(self) -> Dict[str, Any]:
|
| 136 |
+
return {
|
| 137 |
+
"issues": self.issues,
|
| 138 |
+
"metrics": self.metrics,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def analyze_code(code: str) -> Dict[str, Any]:
|
| 142 |
+
try:
|
| 143 |
+
tree = ast.parse(code)
|
| 144 |
+
analyzer = AdvancedCodeAnalyzer()
|
| 145 |
+
analyzer.visit(tree)
|
| 146 |
+
analysis_result = analyzer.report()
|
| 147 |
+
|
| 148 |
+
# Calculate lines of code
|
| 149 |
+
analysis_result["metrics"]["lines_of_code"] = len(code.split("\n"))
|
| 150 |
+
|
| 151 |
+
return analysis_result
|
| 152 |
+
except Exception as e:
|
| 153 |
+
st.error(f"An error occurred while analyzing code: {e}")
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
def generate_code_visualization(analysis_result: Dict[str, Any]) -> None:
|
| 157 |
+
metrics = analysis_result["metrics"]
|
| 158 |
|
| 159 |
+
# Create a bar plot for code metrics
|
| 160 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 161 |
+
sns.barplot(x=list(metrics.keys()), y=list(metrics.values()), ax=ax)
|
| 162 |
+
ax.set_title("Code Metrics Visualization")
|
| 163 |
+
ax.set_ylabel("Count")
|
| 164 |
+
plt.xticks(rotation=45)
|
| 165 |
+
|
| 166 |
+
st.pyplot(fig)
|
| 167 |
+
|
| 168 |
+
def explain_code(code: str) -> str:
|
| 169 |
+
try:
|
| 170 |
+
explanation_prompt = f"Explain the following Python code in detail, including its purpose, functionality, and any notable design choices:\n```python\n{code}\n```"
|
| 171 |
+
explanation = generate_response(explanation_prompt)
|
| 172 |
+
return explanation
|
| 173 |
+
except Exception as e:
|
| 174 |
+
st.error(f"An error occurred while explaining code: {e}")
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
def generate_unit_tests(code: str) -> str:
|
| 178 |
+
try:
|
| 179 |
+
test_prompt = f"Generate comprehensive unit tests for the following Python code:\n```python\n{code}\n```"
|
| 180 |
+
unit_tests = generate_response(test_prompt)
|
| 181 |
+
return unit_tests
|
| 182 |
+
except Exception as e:
|
| 183 |
+
st.error(f"An error occurred while generating unit tests: {e}")
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
def refactor_code(code: str) -> str:
|
| 187 |
+
try:
|
| 188 |
+
refactor_prompt = f"Refactor the following Python code to improve its structure, readability, and maintainability:\n```python\n{code}\n```"
|
| 189 |
+
refactored_code = generate_response(refactor_prompt)
|
| 190 |
+
return refactored_code
|
| 191 |
+
except Exception as e:
|
| 192 |
+
st.error(f"An error occurred while refactoring code: {e}")
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
# Streamlit UI setup
|
| 196 |
+
st.set_page_config(page_title="Advanced AI Code Assistant", page_icon="🚀", layout="wide")
|
| 197 |
+
|
| 198 |
+
# ... (keep the existing CSS styles) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
st.markdown('<div class="main-container">', unsafe_allow_html=True)
|
| 201 |
+
st.title("🚀 Advanced AI Code Assistant")
|
| 202 |
+
st.markdown('<p class="subtitle">Powered by Google Gemini Pro</p>', unsafe_allow_html=True)
|
| 203 |
|
| 204 |
# Session state to maintain conversation history
|
| 205 |
if 'history' not in st.session_state:
|
| 206 |
st.session_state.history = []
|
| 207 |
|
| 208 |
+
prompt = st.text_area("What code can I help you with today, bro?", height=120)
|
| 209 |
|
| 210 |
if st.button("Generate Code"):
|
| 211 |
if prompt.strip() == "":
|
| 212 |
+
st.error("Please enter a valid prompt, bro.")
|
| 213 |
else:
|
| 214 |
+
with st.spinner("Generating code... Hold tight, bro!"):
|
| 215 |
try:
|
| 216 |
completed_text = generate_response(prompt)
|
| 217 |
if completed_text:
|
| 218 |
+
st.success("Code generated successfully, bro! Check it out!")
|
| 219 |
st.session_state.history.append({"user": prompt, "assistant": completed_text})
|
| 220 |
|
| 221 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
|
|
| 224 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 225 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 226 |
except Exception as e:
|
| 227 |
+
st.error(f"Oops! An error occurred, bro: {e}")
|
| 228 |
st.error(traceback.format_exc())
|
| 229 |
|
| 230 |
# Display conversation history
|
| 231 |
st.markdown("## Conversation History")
|
| 232 |
for entry in st.session_state.history:
|
| 233 |
+
st.markdown(f"**You:** {entry['user']}")
|
| 234 |
+
st.markdown(f"**Ath:**")
|
| 235 |
st.code(entry['assistant'])
|
| 236 |
|
| 237 |
# Interactive Code Execution
|
| 238 |
if st.session_state.history:
|
| 239 |
st.markdown("## Execute Code")
|
| 240 |
+
code_to_execute = st.selectbox("Select code to execute, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 241 |
if st.button("Execute Code"):
|
| 242 |
+
with st.spinner("Executing code... Let's see what happens, bro!"):
|
| 243 |
execution_result = execute_code(code_to_execute)
|
| 244 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 245 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
|
|
|
| 250 |
# Code Optimization
|
| 251 |
if st.session_state.history:
|
| 252 |
st.markdown("## Optimize Code")
|
| 253 |
+
code_to_optimize = st.selectbox("Select code to optimize, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 254 |
if st.button("Optimize Code"):
|
| 255 |
+
with st.spinner("Optimizing code... Making it blazing fast, bro!"):
|
| 256 |
optimized_code = optimize_code(code_to_optimize)
|
| 257 |
if optimized_code:
|
| 258 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
|
|
| 264 |
# Code Debugging
|
| 265 |
if st.session_state.history:
|
| 266 |
st.markdown("## Debug Code")
|
| 267 |
+
code_to_debug = st.selectbox("Select code to debug, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 268 |
if st.button("Debug Code"):
|
| 269 |
+
with st.spinner("Debugging code... Squashing those bugs, bro!"):
|
| 270 |
debug_suggestions = debug_code(code_to_debug)
|
| 271 |
if debug_suggestions:
|
| 272 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
|
|
| 278 |
# Code Improvement Suggestions
|
| 279 |
if st.session_state.history:
|
| 280 |
st.markdown("## Suggest Improvements")
|
| 281 |
+
code_to_improve = st.selectbox("Select code to improve, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 282 |
if st.button("Suggest Improvements"):
|
| 283 |
+
with st.spinner("Suggesting improvements... Making your code shine, bro!"):
|
| 284 |
improvement_suggestions = suggest_improvements(code_to_improve)
|
| 285 |
if improvement_suggestions:
|
| 286 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
|
|
|
| 289 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 290 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 291 |
|
| 292 |
+
# Advanced Code Analysis
|
| 293 |
if st.session_state.history:
|
| 294 |
st.markdown("## Analyze Code")
|
| 295 |
+
code_to_analyze = st.selectbox("Select code to analyze, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 296 |
if st.button("Analyze Code"):
|
| 297 |
+
with st.spinner("Analyzing code... Crunching the numbers, bro!"):
|
| 298 |
analysis_result = analyze_code(code_to_analyze)
|
| 299 |
if analysis_result:
|
| 300 |
+
st.markdown("### Code Analysis Results")
|
| 301 |
+
st.markdown("#### Issues:")
|
| 302 |
+
for issue in analysis_result["issues"]:
|
| 303 |
+
st.write(f"- {issue}")
|
| 304 |
+
|
| 305 |
+
st.markdown("#### Metrics:")
|
| 306 |
+
for metric, value in analysis_result["metrics"].items():
|
| 307 |
+
st.write(f"- {metric.replace('_', ' ').title()}: {value}")
|
| 308 |
+
|
| 309 |
+
st.markdown("#### Code Metrics Visualization")
|
| 310 |
+
generate_code_visualization(analysis_result)
|
| 311 |
+
|
| 312 |
+
# Code Explanation
|
| 313 |
+
if st.session_state.history:
|
| 314 |
+
st.markdown("## Explain Code")
|
| 315 |
+
code_to_explain = st.selectbox("Select code to explain, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 316 |
+
if st.button("Explain Code"):
|
| 317 |
+
with st.spinner("Explaining code... Breaking it down for you, bro!"):
|
| 318 |
+
explanation = explain_code(code_to_explain)
|
| 319 |
+
if explanation:
|
| 320 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 321 |
+
st.markdown(explanation)
|
| 322 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 323 |
+
|
| 324 |
+
# Generate Unit Tests
|
| 325 |
+
if st.session_state.history:
|
| 326 |
+
st.markdown("## Generate Unit Tests")
|
| 327 |
+
code_to_test = st.selectbox("Select code to generate unit tests for, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 328 |
+
if st.button("Generate Unit Tests"):
|
| 329 |
+
with st.spinner("Generating unit tests... Making sure your code is rock-solid, bro!"):
|
| 330 |
+
unit_tests = generate_unit_tests(code_to_test)
|
| 331 |
+
if unit_tests:
|
| 332 |
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 333 |
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
| 334 |
+
st.code(unit_tests)
|
| 335 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 336 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 337 |
+
|
| 338 |
+
# Code Refactoring
|
| 339 |
+
# Code Refactoring
|
| 340 |
+
if st.session_state.history:
|
| 341 |
+
st.markdown("## Refactor Code")
|
| 342 |
+
code_to_refactor = st.selectbox("Select code to refactor, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 343 |
+
if st.button("Refactor Code"):
|
| 344 |
+
with st.spinner("Refactoring code... Giving it a fresh look, bro!"):
|
| 345 |
+
refactored_code = refactor_code(code_to_refactor)
|
| 346 |
+
if refactored_code:
|
| 347 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 348 |
+
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
| 349 |
+
st.code(refactored_code)
|
| 350 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 351 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 352 |
+
|
| 353 |
+
# Multi-language Support
|
| 354 |
+
supported_languages = ["Python", "JavaScript", "Java", "C++", "Ruby", "Go"]
|
| 355 |
+
|
| 356 |
+
st.markdown("## Multi-language Support")
|
| 357 |
+
selected_language = st.selectbox("Select a programming language, bro", supported_languages)
|
| 358 |
+
multi_lang_prompt = st.text_area(f"What {selected_language} code can I help you with, bro?", height=120)
|
| 359 |
+
|
| 360 |
+
if st.button(f"Generate {selected_language} Code"):
|
| 361 |
+
if multi_lang_prompt.strip() == "":
|
| 362 |
+
st.error(f"Please enter a valid {selected_language} prompt, bro.")
|
| 363 |
+
else:
|
| 364 |
+
with st.spinner(f"Generating {selected_language} code... Hold tight, bro!"):
|
| 365 |
+
try:
|
| 366 |
+
language_prompt = f"Generate {selected_language} code for the following prompt:\n{multi_lang_prompt}"
|
| 367 |
+
completed_text = generate_response(language_prompt)
|
| 368 |
+
if completed_text:
|
| 369 |
+
st.success(f"{selected_language} code generated successfully, bro! Check it out!")
|
| 370 |
+
st.session_state.history.append({"user": multi_lang_prompt, "assistant": completed_text})
|
| 371 |
+
|
| 372 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 373 |
+
st.markdown('<div class="code-block">', unsafe_allow_html=True)
|
| 374 |
+
st.code(completed_text, language=selected_language.lower())
|
| 375 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 376 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 377 |
+
except Exception as e:
|
| 378 |
+
st.error(f"Oops! An error occurred while generating {selected_language} code, bro: {e}")
|
| 379 |
+
st.error(traceback.format_exc())
|
| 380 |
+
|
| 381 |
+
# Code Performance Profiling
|
| 382 |
+
def profile_code(code: str) -> str:
|
| 383 |
+
try:
|
| 384 |
+
profile_prompt = f"Analyze the performance of the following Python code and suggest optimizations:\n```python\n{code}\n```"
|
| 385 |
+
profile_result = generate_response(profile_prompt)
|
| 386 |
+
return profile_result
|
| 387 |
+
except Exception as e:
|
| 388 |
+
st.error(f"An error occurred while profiling code: {e}")
|
| 389 |
+
return None
|
| 390 |
+
|
| 391 |
+
if st.session_state.history:
|
| 392 |
+
st.markdown("## Code Performance Profiling")
|
| 393 |
+
code_to_profile = st.selectbox("Select code to profile, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 394 |
+
if st.button("Profile Code"):
|
| 395 |
+
with st.spinner("Profiling code... Checking for speed, bro!"):
|
| 396 |
+
profile_result = profile_code(code_to_profile)
|
| 397 |
+
if profile_result:
|
| 398 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 399 |
+
st.markdown(profile_result)
|
| 400 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 401 |
+
|
| 402 |
+
# Code Documentation Generator
|
| 403 |
+
def generate_documentation(code: str) -> str:
|
| 404 |
+
try:
|
| 405 |
+
doc_prompt = f"Generate comprehensive documentation for the following Python code, including function descriptions, parameters, return values, and usage examples:\n```python\n{code}\n```"
|
| 406 |
+
documentation = generate_response(doc_prompt)
|
| 407 |
+
return documentation
|
| 408 |
+
except Exception as e:
|
| 409 |
+
st.error(f"An error occurred while generating documentation: {e}")
|
| 410 |
+
return None
|
| 411 |
+
|
| 412 |
+
if st.session_state.history:
|
| 413 |
+
st.markdown("## Generate Documentation")
|
| 414 |
+
code_to_document = st.selectbox("Select code to document, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 415 |
+
if st.button("Generate Documentation"):
|
| 416 |
+
with st.spinner("Generating documentation... Making your code self-explanatory, bro!"):
|
| 417 |
+
documentation = generate_documentation(code_to_document)
|
| 418 |
+
if documentation:
|
| 419 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 420 |
+
st.markdown(documentation)
|
| 421 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 422 |
+
|
| 423 |
+
# Code Security Analysis
|
| 424 |
+
def analyze_security(code: str) -> str:
|
| 425 |
+
try:
|
| 426 |
+
security_prompt = f"Perform a security analysis on the following Python code, identifying potential vulnerabilities and suggesting fixes:\n```python\n{code}\n```"
|
| 427 |
+
security_analysis = generate_response(security_prompt)
|
| 428 |
+
return security_analysis
|
| 429 |
+
except Exception as e:
|
| 430 |
+
st.error(f"An error occurred while analyzing code security: {e}")
|
| 431 |
+
return None
|
| 432 |
+
|
| 433 |
+
if st.session_state.history:
|
| 434 |
+
st.markdown("## Code Security Analysis")
|
| 435 |
+
code_to_secure = st.selectbox("Select code for security analysis, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 436 |
+
if st.button("Analyze Security"):
|
| 437 |
+
with st.spinner("Analyzing code security... Making sure it's fortress-level secure, bro!"):
|
| 438 |
+
security_analysis = analyze_security(code_to_secure)
|
| 439 |
+
if security_analysis:
|
| 440 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 441 |
+
st.markdown(security_analysis)
|
| 442 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 443 |
+
|
| 444 |
+
# Code Complexity Analysis
|
| 445 |
+
def analyze_complexity(code: str) -> str:
|
| 446 |
+
try:
|
| 447 |
+
complexity_prompt = f"Analyze the complexity of the following Python code, including time and space complexity for each function:\n```python\n{code}\n```"
|
| 448 |
+
complexity_analysis = generate_response(complexity_prompt)
|
| 449 |
+
return complexity_analysis
|
| 450 |
+
except Exception as e:
|
| 451 |
+
st.error(f"An error occurred while analyzing code complexity: {e}")
|
| 452 |
+
return None
|
| 453 |
+
|
| 454 |
+
if st.session_state.history:
|
| 455 |
+
st.markdown("## Code Complexity Analysis")
|
| 456 |
+
code_to_analyze_complexity = st.selectbox("Select code for complexity analysis, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 457 |
+
if st.button("Analyze Complexity"):
|
| 458 |
+
with st.spinner("Analyzing code complexity... Crunching those Big O numbers, bro!"):
|
| 459 |
+
complexity_analysis = analyze_complexity(code_to_analyze_complexity)
|
| 460 |
+
if complexity_analysis:
|
| 461 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 462 |
+
st.markdown(complexity_analysis)
|
| 463 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 464 |
+
|
| 465 |
+
# Design Pattern Suggestions
|
| 466 |
+
def suggest_design_patterns(code: str) -> str:
|
| 467 |
+
try:
|
| 468 |
+
pattern_prompt = f"Analyze the following Python code and suggest appropriate design patterns that could improve its structure and maintainability:\n```python\n{code}\n```"
|
| 469 |
+
pattern_suggestions = generate_response(pattern_prompt)
|
| 470 |
+
return pattern_suggestions
|
| 471 |
+
except Exception as e:
|
| 472 |
+
st.error(f"An error occurred while suggesting design patterns: {e}")
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
if st.session_state.history:
|
| 476 |
+
st.markdown("## Design Pattern Suggestions")
|
| 477 |
+
code_for_patterns = st.selectbox("Select code for design pattern suggestions, bro", [entry['assistant'] for entry in st.session_state.history])
|
| 478 |
+
if st.button("Suggest Design Patterns"):
|
| 479 |
+
with st.spinner("Suggesting design patterns... Bringing some architecture to your code, bro!"):
|
| 480 |
+
pattern_suggestions = suggest_design_patterns(code_for_patterns)
|
| 481 |
+
if pattern_suggestions:
|
| 482 |
+
st.markdown('<div class="output-container">', unsafe_allow_html=True)
|
| 483 |
+
st.markdown(pattern_suggestions)
|
| 484 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 485 |
|
| 486 |
st.markdown("""
|
| 487 |
<div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
|
| 488 |
+
Created with ❤️ by Your Advanced AI Code Assistant, Ath
|
| 489 |
</div>
|
| 490 |
""", unsafe_allow_html=True)
|
| 491 |
|