#!/usr/bin/env python3
"""
Optimized Matrix Code Analyzer with CodeT5+
This integrates the optimized CodeT5+ analyzer into your existing
Matrix-themed Streamlit application with speed optimizations.
Author: AI Code Analyzer Project
Date: 2025
"""
import streamlit as st
import time
import torch
from optimized_code_analyzer import OptimizedCodeAnalyzer
# Page configuration
st.set_page_config(
page_title="AI Code Analyzer - Optimized",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for Matrix theme
st.markdown("""
""", unsafe_allow_html=True)
@st.cache_resource
def load_analyzer():
"""
Load the optimized analyzer (cached for performance).
"""
return OptimizedCodeAnalyzer()
def main():
"""
Main Streamlit application.
"""
# Header
st.markdown("""
""", unsafe_allow_html=True)
# Load analyzer
with st.spinner("🚀 Loading optimized CodeT5+ model..."):
analyzer = load_analyzer()
# Sidebar
st.sidebar.markdown("## ⚙️ Analysis Options")
analysis_mode = st.sidebar.selectbox(
"Analysis Mode",
["Streaming (Interactive)", "Fast (Batch)"],
help="Streaming shows progress, Fast is optimized for speed"
)
show_progress = st.sidebar.checkbox(
"Show Progress Indicators",
value=True,
help="Display progress bars and timing information"
)
# Main content
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("## 📝 Code Input")
# Code input
code_input = st.text_area(
"Enter your code:",
height=300,
placeholder="def hello():\n print('Hello, World!')",
help="Paste your code here for analysis"
)
# Analysis button
analyze_button = st.button(
"🔍 Analyze Code",
type="primary",
use_container_width=True
)
with col2:
st.markdown("## 📊 Analysis Results")
if analyze_button and code_input.strip():
# Perform analysis
start_time = time.time()
if analysis_mode == "Streaming (Interactive)":
# Streaming analysis
st.markdown("### 🔄 Streaming Analysis")
# Create placeholder for streaming results
result_placeholder = st.empty()
progress_placeholder = st.empty()
# Show progress
if show_progress:
progress_bar = progress_placeholder.progress(0)
status_text = st.empty()
try:
# Stream analysis
analysis_text = ""
for partial_result in analyzer.analyze_code_streaming(code_input, show_progress):
analysis_text = partial_result
# Update progress
if show_progress:
progress_bar.progress(50)
status_text.text("🔍 Analyzing code...")
# Complete analysis
if show_progress:
progress_bar.progress(100)
status_text.text("✅ Analysis complete!")
# Display results
result_placeholder.markdown(f"""
📄 Analysis Results:
{analysis_text}
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"❌ Analysis failed: {str(e)}")
else:
# Fast analysis
st.markdown("### ⚡ Fast Analysis")
if show_progress:
progress_bar = st.progress(0)
status_text = st.empty()
progress_bar.progress(25)
status_text.text("🚀 Loading model...")
try:
# Perform fast analysis
result = analyzer.analyze_code_fast(code_input)
if show_progress:
progress_bar.progress(100)
status_text.text("✅ Analysis complete!")
# Display results
st.markdown(f"""
📄 Analysis Results:
{result['analysis']}
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"❌ Analysis failed: {str(e)}")
# Show performance metrics
total_time = time.time() - start_time
st.markdown(f"""
⚡ Performance Metrics:
Total Time: {total_time:.2f}s
Analysis Mode: {analysis_mode}
Model: CodeT5+ (Optimized)
""", unsafe_allow_html=True)
elif analyze_button and not code_input.strip():
st.warning("⚠️ Please enter some code to analyze!")
else:
st.info("👆 Enter code and click 'Analyze Code' to get started!")
# Model information
st.markdown("## 📊 Model Information")
model_info = analyzer.get_model_info()
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Model Parameters", f"{model_info['parameters']:,}")
with col2:
st.metric("Cache Size", f"{model_info['cache_size']} analyses")
with col3:
st.metric("Device", str(model_info['device']))
# Cache information
st.markdown("""
💾 Cache Information:
• Cached analyses are reused for identical code
• Cache improves speed for repeated analyses
• Cache is automatically managed
""", unsafe_allow_html=True)
# Footer
st.markdown("---")
st.markdown("""
🚀 Optimized AI Code Analyzer | Powered by CodeT5+ | Matrix Theme
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()