File size: 11,073 Bytes
f8dbf90 838191d 98e1f97 f1447e0 f8dbf90 838191d 9f8e60f f8dbf90 838191d f8dbf90 f1447e0 f8dbf90 e705807 f8dbf90 990d424 f8dbf90 cba9efc f8dbf90 9f8e60f 838191d 75b06d3 98e1f97 f1447e0 990d424 f8dbf90 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 75b06d3 990d424 b479e07 838191d 990d424 da7ac0b 990d424 d35faf8 921a07f 83ac817 990d424 838191d 990d424 838191d 0b3cd55 98e1f97 f1447e0 d35faf8 990d424 d35faf8 75b06d3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
import streamlit as st
import google.generativeai as genai
import traceback
import subprocess
import re
import ast
import astor
# Configure the Gemini API with advanced error handling
try:
genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
except Exception as e:
st.error(f"Failed to configure API: {e}")
st.stop()
# Create the model with system instructions and advanced configuration
generation_config = {
"temperature": 0.1, # Lower temperature for more deterministic responses
"top_p": 0.75,
"top_k": 20,
"max_output_tokens": 20480, # Increased max output tokens for longer responses
}
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
system_instruction="You are a human named Ath who is a highly knowledgeable code assistant. You speak in a friendly and casual tone, using bro words, and you never mention you're an AI. Your responses should contain code only, without explanations.",
)
chat_session = model.start_chat(history=[])
def generate_response(user_input):
try:
response = chat_session.send_message(user_input)
return response.text
except Exception as e:
st.error(f"An error occurred while generating response: {e}")
st.error(traceback.format_exc())
return None
def execute_code(code):
try:
result = subprocess.run(['python', '-c', code], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
return result.stdout
else:
return result.stderr
except Exception as e:
return f"An error occurred while executing code: {e}"
def optimize_code(code):
try:
optimization_prompt = f"Optimize the following Python code:\n```python\n{code}\n```"
optimized_code = generate_response(optimization_prompt)
return optimized_code
except Exception as e:
st.error(f"An error occurred while optimizing code: {e}")
return None
def debug_code(code):
try:
debug_prompt = f"Debug the following Python code and suggest fixes:\n```python\n{code}\n```"
debug_suggestions = generate_response(debug_prompt)
return debug_suggestions
except Exception as e:
st.error(f"An error occurred while debugging code: {e}")
return None
def suggest_improvements(code):
try:
improvement_prompt = f"Suggest improvements for the following Python code:\n```python\n{code}\n```"
improvement_suggestions = generate_response(improvement_prompt)
return improvement_suggestions
except Exception as e:
st.error(f"An error occurred while suggesting improvements: {e}")
return None
def analyze_code(code):
try:
tree = ast.parse(code)
analyzer = CodeAnalyzer()
analyzer.visit(tree)
return analyzer.report()
except Exception as e:
st.error(f"An error occurred while analyzing code: {e}")
return None
class CodeAnalyzer(ast.NodeVisitor):
def __init__(self):
self.issues = []
def visit_FunctionDef(self, node):
if len(node.body) == 0:
self.issues.append(f"Function '{node.name}' is empty.")
self.generic_visit(node)
def visit_For(self, node):
if isinstance(node.target, ast.Name) and node.target.id == '_':
self.issues.append(f"Possible unused variable in loop at line {node.lineno}.")
self.generic_visit(node)
def report(self):
return "\n".join(self.issues)
# Streamlit UI setup
st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="π", layout="wide")
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
body {
font-family: 'Inter', sans-serif;
background-color: #f0f4f8;
color: #1a202c;
}
.stApp {
max-width: 1000px;
margin: 0 auto;
padding: 2rem;
}
.main-container {
background: #ffffff;
border-radius: 16px;
padding: 2rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}
h1 {
font-size: 2.5rem;
font-weight: 700;
color: #2d3748;
text-align: center;
margin-bottom: 1rem;
}
.subtitle {
font-size: 1.1rem;
text-align: center;
color: #4a5568;
margin-bottom: 2rem;
}
.stTextArea textarea {
border: 2px solid #e2e8f0;
border-radius: 8px;
font-size: 1rem;
padding: 0.75rem;
transition: all 0.3s ease;
}
.stTextArea textarea:focus {
border-color: #4299e1;
box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
}
.stButton button {
background-color: #4299e1;
color: white;
border: none;
border-radius: 8px;
font-size: 1.1rem;
font-weight: 600;
padding: 0.75rem 2rem;
transition: all 0.3s ease;
width: 100%;
}
.stButton button:hover {
background-color: #3182ce;
}
.output-container {
background: #f7fafc;
border-radius: 8px;
padding: 1rem;
margin-top: 2rem;
}
.code-block {
background-color: #2d3748;
color: #e2e8f0;
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
border-radius: 8px;
padding: 1rem;
margin-top: 1rem;
overflow-x: auto;
}
.stAlert {
background-color: #ebf8ff;
color: #2b6cb0;
border-radius: 8px;
border: none;
padding: 0.75rem 1rem;
}
.stSpinner {
color: #4299e1;
}
</style>
""", unsafe_allow_html=True)
st.markdown('<div class="main-container">', unsafe_allow_html=True)
st.title("π Sleek AI Code Assistant")
st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
# Session state to maintain conversation history
if 'history' not in st.session_state:
st.session_state.history = []
prompt = st.text_area("What code can I help you with today?", height=120)
if st.button("Generate Code"):
if prompt.strip() == "":
st.error("Please enter a valid prompt.")
else:
with st.spinner("Generating code..."):
try:
completed_text = generate_response(prompt)
if completed_text:
st.success("Code generated successfully!")
st.session_state.history.append({"user": prompt, "assistant": completed_text})
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(completed_text)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
except Exception as e:
st.error(f"An error occurred: {e}")
st.error(traceback.format_exc())
# Display conversation history
st.markdown("## Conversation History")
for entry in st.session_state.history:
st.markdown(f"**User:** {entry['user']}")
st.markdown(f"**Assistant:**")
st.code(entry['assistant'])
# Interactive Code Execution
if st.session_state.history:
st.markdown("## Execute Code")
code_to_execute = st.selectbox("Select code to execute", [entry['assistant'] for entry in st.session_state.history])
if st.button("Execute Code"):
with st.spinner("Executing code..."):
execution_result = execute_code(code_to_execute)
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(execution_result)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Code Optimization
if st.session_state.history:
st.markdown("## Optimize Code")
code_to_optimize = st.selectbox("Select code to optimize", [entry['assistant'] for entry in st.session_state.history])
if st.button("Optimize Code"):
with st.spinner("Optimizing code..."):
optimized_code = optimize_code(code_to_optimize)
if optimized_code:
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(optimized_code)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Code Debugging
if st.session_state.history:
st.markdown("## Debug Code")
code_to_debug = st.selectbox("Select code to debug", [entry['assistant'] for entry in st.session_state.history])
if st.button("Debug Code"):
with st.spinner("Debugging code..."):
debug_suggestions = debug_code(code_to_debug)
if debug_suggestions:
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(debug_suggestions)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Code Improvement Suggestions
if st.session_state.history:
st.markdown("## Suggest Improvements")
code_to_improve = st.selectbox("Select code to improve", [entry['assistant'] for entry in st.session_state.history])
if st.button("Suggest Improvements"):
with st.spinner("Suggesting improvements..."):
improvement_suggestions = suggest_improvements(code_to_improve)
if improvement_suggestions:
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(improvement_suggestions)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Code Analysis
if st.session_state.history:
st.markdown("## Analyze Code")
code_to_analyze = st.selectbox("Select code to analyze", [entry['assistant'] for entry in st.session_state.history])
if st.button("Analyze Code"):
with st.spinner("Analyzing code..."):
analysis_result = analyze_code(code_to_analyze)
if analysis_result:
st.markdown('<div class="output-container">', unsafe_allow_html=True)
st.markdown('<div class="code-block">', unsafe_allow_html=True)
st.code(analysis_result)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("""
<div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
Created with β€οΈ by Your Sleek AI Code Assistant
</div>
""", unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True) |