Spaces:
Sleeping
Sleeping
File size: 4,575 Bytes
8e14315 |
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 |
import streamlit as st
import os
from dotenv import load_dotenv
from groq import Groq
import json
from datetime import datetime
# Load environment variables
load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
# Initialize Groq client
client = Groq(api_key=api_key)
# Initialize session state
if 'history' not in st.session_state:
st.session_state.history = []
if 'theme' not in st.session_state:
st.session_state.theme = 'light'
# Set page config
st.set_page_config(
page_title="Code Optimizer Pro",
layout="wide",
initial_sidebar_state="expanded"
)
# Apply light/dark theme
def apply_custom_css():
dark_theme = """<style> .stApp {background-color:#1E1E1E;color:#FFF;} ... </style>"""
light_theme = """<style> .stApp {background-color:#FFF;color:#000;} ... </style>"""
st.markdown(dark_theme if st.session_state.theme == 'dark' else light_theme, unsafe_allow_html=True)
# Optimization logic with system prompt
def optimize_code(code, language):
system_message = {
"role": "system",
"content": (
"You are a professional code optimizer. "
"Only answer questions related to code optimization. "
"If a question is irrelevant or not about code, respond politely that you're only here to help with code optimization."
)
}
user_prompt = (
f"""Analyze, optimize, and correct the following {language} code.
Provide the following in your response:
1. Optimized code
2. Explanation of improvements
3. Any potential bugs fixed
4. Performance improvements made
Here's the code:
{code}
"""
)
try:
chat_completion = client.chat.completions.create(
messages=[
system_message,
{"role": "user", "content": user_prompt}
],
model="llama3-70b-8192"
)
return chat_completion.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
# Save to history
def save_to_history(code, language, result):
st.session_state.history.append({
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'language': language,
'original_code': code,
'optimization_result': result
})
# Save history to JSON
def save_history_to_file():
try:
with open('optimization_history.json', 'w') as f:
json.dump(st.session_state.history, f, indent=4)
return True
except Exception:
return False
# Main App
def main():
apply_custom_css()
# Sidebar
with st.sidebar:
st.title("βοΈ Settings")
theme = st.radio("Choose Theme", ["light", "dark"])
if theme != st.session_state.theme:
st.session_state.theme = theme
st.rerun()
if st.button("πΎ Save History"):
st.success("History saved!" if save_history_to_file() else "Failed to save.")
if st.button("ποΈ Clear History"):
st.session_state.history = []
st.success("History cleared!")
# Main Area
st.title("π Code Optimizer Pro")
col1, col2 = st.columns([2, 1])
with col1:
languages = ["Python", "JavaScript", "Java", "C++", "Ruby", "Go", "PHP", "C#", "Swift", "Rust"]
selected_language = st.selectbox("π Select Programming Language", languages)
st.subheader("π» Enter Your Code")
user_code = st.text_area("Code Editor", height=300)
if st.button("β¨ Optimize Code"):
if user_code.strip():
with st.spinner("π Optimizing..."):
result = optimize_code(user_code, selected_language)
save_to_history(user_code, selected_language, result)
st.markdown("### π Optimization Results")
st.markdown(result)
else:
st.error("β οΈ Please enter code to optimize.")
with col2:
st.subheader("π Optimization History")
if st.session_state.history:
for idx, entry in enumerate(reversed(st.session_state.history)):
with st.expander(f"#{len(st.session_state.history)-idx}: {entry['language']} - {entry['timestamp']}"):
st.code(entry['original_code'], language=entry['language'].lower())
st.markdown("**Optimization Result:**")
st.markdown(entry['optimization_result'])
else:
st.info("No history yet.")
if __name__ == "__main__":
main()
|