Skip to content
Snippets Groups Projects

Latest version of Agent

Merged asifr requested to merge aneesh into main
3 files
+ 257
108
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 78
67
import streamlit as st
import base64
import streamlit_shadcn_ui as ui
from agent_functions import *
from db_manager import DatabaseHandler
import time
import asyncio
import streamlit.components.v1 as components
# theme = st.selectbox("Choose theme:", ["Light", "Dark"])
# def add_video_bg_from_local(video_file):
# video_html = f"""
# <style>
# .video-bg {{
# position: fixed;
# width: 100%;
# height: 100%;
# margin-left: -635px;
# margin-up: -30px;
# object-fit: cover;
# overflow: hidden;
# }}
# </style>
# <video class="video-bg" autoplay muted loop>
# <source src="data:video/mp4;base64,{base64.b64encode(open(video_file, "rb").read()).decode()}" type="video/mp4">
# Your browser does not support the video tag.
# </video>
# """
# st.markdown(video_html, unsafe_allow_html=True)
import base64
import streamlit_shadcn_ui as ui
from db_manager import DatabaseHandler
def add_bg_from_local(image_file):
with open(image_file, "rb") as image_file:
@@ -141,6 +120,24 @@ st.markdown(
# Initialize database handler
db = DatabaseHandler()
def create_error_message(error: str) -> str:
"""Create a formatted error message for display"""
return f"""
```python
# An error occurred during code execution
# {error}
```
"""
st.markdown(
"""
<style>
header {visibility: hidden;}
</style>
""",
unsafe_allow_html=True
)
# Initialize session state
if 'current_conversation_id' not in st.session_state:
st.session_state.current_conversation_id = None
@@ -151,10 +148,11 @@ if 'viewing_history' not in st.session_state:
with st.sidebar:
st.markdown("""
<h1 style='color: white;'>Chat History</h1>
""", unsafe_allow_html=True)
""", unsafe_allow_html=True)
# Button to start new conversation/optimization
col1, col2 = st.columns([2, 1])
col1, col2 = st.columns([2, 1])
with col1:
if st.button("New Optimization", use_container_width=True, type="primary"):
st.session_state.viewing_history = False
@@ -162,7 +160,7 @@ with st.sidebar:
st.rerun()
with col2:
if st.button("Clear All", type="primary", use_container_width=True):
if st.button("Clear All", type="secondary", use_container_width=True):
if st.session_state.current_conversation_id:
st.session_state.current_conversation_id = None
st.session_state.viewing_history = False
@@ -189,7 +187,7 @@ with st.sidebar:
st.rerun()
with col2:
if st.button("", key=f"del_{conv['id']}", use_container_width=True):
if st.button("X", key=f"del_{conv['id']}", use_container_width=True):
db.delete_conversation(conv['id'])
if conv['id'] == st.session_state.current_conversation_id:
st.session_state.current_conversation_id = None
@@ -199,15 +197,13 @@ with st.sidebar:
# Main content area
st.title("Code Optimizer")
st.markdown("This tool takes your code and applies various optimization techniques to improve performance.")
# Show input controls only when not viewing history
if not st.session_state.viewing_history:
user_code = st.text_area("Enter your Python code here:", height=200)
number_times = st.slider("Number of improvement techniques:", min_value=1, max_value=5, value=3)
async def process_optimization():
if st.session_state.current_conversation_id is None:
if st.session_state.current_conversation_id is None:
title = f"Optimization {time.strftime('%Y-%m-%d %H:%M:%S')}"
conversation_id = db.create_conversation(title)
st.session_state.current_conversation_id = conversation_id
@@ -243,38 +239,53 @@ if not st.session_state.viewing_history:
st.warning("Please enter some Python code to improve.")
# Display conversation history if a conversation is selected
if st.session_state.current_conversation_id:
entries = db.get_conversation_entries(st.session_state.current_conversation_id)
if entries: # Only show entries if they exist
for entry in entries:
with st.container():
st.markdown("#### Original Code")
st.code(entry['original_code'], language="python")
results = db.get_entry_results(entry['id'])
if results: # Only create tabs if there are results
# Create tabs for all results
tabs = st.tabs([f"Version {i+1}" for i in range(len(results))])
# Display results in tabs
execution_times = []
techniques_applied = []
for i, (tab, result) in enumerate(zip(tabs, results)):
with tab:
st.subheader(f"Techniques Applied: {result['techniques_applied']}")
st.code(result['improved_code'], language="python")
st.write("Output:")
st.code(result['output'])
st.write(f"Time taken: {result['execution_time']:.4f} seconds")
execution_times.append(result['execution_time'])
techniques_applied.append(result['techniques_applied'])
# Display performance comparison
performance_data = prepare_performance_data(execution_times, techniques_applied)
st.subheader("Performance Comparison")
st.dataframe(performance_data)
elif not st.session_state.viewing_history:
st.info("Enter your code above and click 'Improve Code' to start optimization.")
\ No newline at end of file
try:
if st.session_state.current_conversation_id:
entries = db.get_conversation_entries(st.session_state.current_conversation_id)
if entries:
for entry in entries:
with st.container():
st.markdown("#### Original Code")
st.code(entry['original_code'], language="python")
results = db.get_entry_results(entry['id'])
if results:
tabs = st.tabs([f"Version {i+1}" for i in range(len(results))])
execution_times = []
memory_usages = []
techniques_applied = []
for i, (tab, result) in enumerate(zip(tabs, results)):
with tab:
try:
st.subheader(f"Techniques Applied: {result['techniques']}")
st.code(result['improved_code'], language="python")
st.write("Output:")
if "Error:" in result['output']:
st.error(result['output'])
else:
st.code(result['output'])
st.write(f"Time taken: {result['execution_time']:.4f} seconds")
st.write(f"Memory Usage: {result['memory_usage']:.2f} MB")
execution_times.append(result['execution_time'])
memory_usages.append(result['memory_usage'])
techniques_applied.append(result['techniques'])
except Exception as e:
st.error(f"Error displaying result: {str(e)}")
if execution_times:
performance_data = prepare_performance_data(
execution_times,
memory_usages,
techniques_applied
)
st.subheader("Performance Comparison")
st.dataframe(performance_data)
except Exception as e:
st.error(f"An error occurred: {str(e)}")
if st.button("Reset Application"):
st.session_state.clear()
st.rerun()
\ No newline at end of file
Loading