Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
from groq import Groq
|
5 |
+
import json
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
# Load environment variables
|
9 |
+
load_dotenv()
|
10 |
+
api_key = os.getenv("GROQ_API_KEY")
|
11 |
+
|
12 |
+
# Initialize Groq client
|
13 |
+
client = Groq(api_key=api_key)
|
14 |
+
|
15 |
+
# Initialize session state
|
16 |
+
if 'history' not in st.session_state:
|
17 |
+
st.session_state.history = []
|
18 |
+
if 'theme' not in st.session_state:
|
19 |
+
st.session_state.theme = 'light'
|
20 |
+
|
21 |
+
# Set page config
|
22 |
+
st.set_page_config(
|
23 |
+
page_title="Code Optimizer Pro",
|
24 |
+
layout="wide",
|
25 |
+
initial_sidebar_state="expanded"
|
26 |
+
)
|
27 |
+
|
28 |
+
# Apply light/dark theme
|
29 |
+
def apply_custom_css():
|
30 |
+
dark_theme = """<style> .stApp {background-color:#1E1E1E;color:#FFF;} ... </style>"""
|
31 |
+
light_theme = """<style> .stApp {background-color:#FFF;color:#000;} ... </style>"""
|
32 |
+
st.markdown(dark_theme if st.session_state.theme == 'dark' else light_theme, unsafe_allow_html=True)
|
33 |
+
|
34 |
+
# Optimization logic with system prompt
|
35 |
+
def optimize_code(code, language):
|
36 |
+
system_message = {
|
37 |
+
"role": "system",
|
38 |
+
"content": (
|
39 |
+
"You are a professional code optimizer. "
|
40 |
+
"Only answer questions related to code optimization. "
|
41 |
+
"If a question is irrelevant or not about code, respond politely that you're only here to help with code optimization."
|
42 |
+
)
|
43 |
+
}
|
44 |
+
|
45 |
+
user_prompt = (
|
46 |
+
f"""Analyze, optimize, and correct the following {language} code.
|
47 |
+
Provide the following in your response:
|
48 |
+
1. Optimized code
|
49 |
+
2. Explanation of improvements
|
50 |
+
3. Any potential bugs fixed
|
51 |
+
4. Performance improvements made
|
52 |
+
|
53 |
+
Here's the code:
|
54 |
+
{code}
|
55 |
+
"""
|
56 |
+
)
|
57 |
+
|
58 |
+
try:
|
59 |
+
chat_completion = client.chat.completions.create(
|
60 |
+
messages=[
|
61 |
+
system_message,
|
62 |
+
{"role": "user", "content": user_prompt}
|
63 |
+
],
|
64 |
+
model="llama3-70b-8192"
|
65 |
+
)
|
66 |
+
return chat_completion.choices[0].message.content
|
67 |
+
except Exception as e:
|
68 |
+
return f"Error: {str(e)}"
|
69 |
+
|
70 |
+
# Save to history
|
71 |
+
def save_to_history(code, language, result):
|
72 |
+
st.session_state.history.append({
|
73 |
+
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
74 |
+
'language': language,
|
75 |
+
'original_code': code,
|
76 |
+
'optimization_result': result
|
77 |
+
})
|
78 |
+
|
79 |
+
# Save history to JSON
|
80 |
+
def save_history_to_file():
|
81 |
+
try:
|
82 |
+
with open('optimization_history.json', 'w') as f:
|
83 |
+
json.dump(st.session_state.history, f, indent=4)
|
84 |
+
return True
|
85 |
+
except Exception:
|
86 |
+
return False
|
87 |
+
|
88 |
+
# Main App
|
89 |
+
def main():
|
90 |
+
apply_custom_css()
|
91 |
+
|
92 |
+
# Sidebar
|
93 |
+
with st.sidebar:
|
94 |
+
st.title("βοΈ Settings")
|
95 |
+
theme = st.radio("Choose Theme", ["light", "dark"])
|
96 |
+
if theme != st.session_state.theme:
|
97 |
+
st.session_state.theme = theme
|
98 |
+
st.rerun()
|
99 |
+
|
100 |
+
if st.button("πΎ Save History"):
|
101 |
+
st.success("History saved!" if save_history_to_file() else "Failed to save.")
|
102 |
+
|
103 |
+
if st.button("ποΈ Clear History"):
|
104 |
+
st.session_state.history = []
|
105 |
+
st.success("History cleared!")
|
106 |
+
|
107 |
+
# Main Area
|
108 |
+
st.title("π Code Optimizer Pro")
|
109 |
+
col1, col2 = st.columns([2, 1])
|
110 |
+
|
111 |
+
with col1:
|
112 |
+
languages = ["Python", "JavaScript", "Java", "C++", "Ruby", "Go", "PHP", "C#", "Swift", "Rust"]
|
113 |
+
selected_language = st.selectbox("π Select Programming Language", languages)
|
114 |
+
st.subheader("π» Enter Your Code")
|
115 |
+
user_code = st.text_area("Code Editor", height=300)
|
116 |
+
|
117 |
+
if st.button("β¨ Optimize Code"):
|
118 |
+
if user_code.strip():
|
119 |
+
with st.spinner("π Optimizing..."):
|
120 |
+
result = optimize_code(user_code, selected_language)
|
121 |
+
save_to_history(user_code, selected_language, result)
|
122 |
+
st.markdown("### π Optimization Results")
|
123 |
+
st.markdown(result)
|
124 |
+
else:
|
125 |
+
st.error("β οΈ Please enter code to optimize.")
|
126 |
+
|
127 |
+
with col2:
|
128 |
+
st.subheader("π Optimization History")
|
129 |
+
if st.session_state.history:
|
130 |
+
for idx, entry in enumerate(reversed(st.session_state.history)):
|
131 |
+
with st.expander(f"#{len(st.session_state.history)-idx}: {entry['language']} - {entry['timestamp']}"):
|
132 |
+
st.code(entry['original_code'], language=entry['language'].lower())
|
133 |
+
st.markdown("**Optimization Result:**")
|
134 |
+
st.markdown(entry['optimization_result'])
|
135 |
+
else:
|
136 |
+
st.info("No history yet.")
|
137 |
+
|
138 |
+
if __name__ == "__main__":
|
139 |
+
main()
|