-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1290 lines (1077 loc) · 52.9 KB
/
app.py
File metadata and controls
1290 lines (1077 loc) · 52.9 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import google.generativeai as genai
import os
import tempfile
import zipfile
import subprocess
import json
import time
import ast
import re
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import shutil
# Page config
st.set_page_config(
page_title="Singularity-AI",
page_icon="♾️",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for Singularity-AI theme
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@300;400;600&display=swap');
.main {
padding-top: 1rem;
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 25%, #16213e 50%, #0f0f23 75%, #000000 100%);
color: #ffffff;
}
.stApp {
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 25%, #16213e 50%, #0f0f23 75%, #000000 100%);
}
/* Header styling */
h1 {
font-family: 'Orbitron', monospace !important;
font-weight: 900 !important;
background: linear-gradient(45deg, #00d4ff, #ff00ff, #00ff88);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
font-size: 3.5rem !important;
margin-bottom: 0.5rem !important;
text-shadow: 0 0 20px rgba(0, 212, 255, 0.5);
}
.subtitle {
font-family: 'Rajdhani', sans-serif;
text-align: center;
font-size: 1.2rem;
color: #00d4ff;
margin-bottom: 2rem;
font-weight: 300;
}
/* Sidebar styling */
.css-1d391kg {
background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
border-right: 2px solid #00d4ff;
}
.css-1d391kg .stSelectbox, .css-1d391kg .stTextInput {
color: #ffffff;
}
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
gap: 12px;
background: rgba(26, 26, 46, 0.8);
padding: 10px;
border-radius: 15px;
border: 1px solid #00d4ff;
}
.stTabs [data-baseweb="tab"] {
height: 55px;
background: linear-gradient(135deg, #1a1a2e, #16213e);
border-radius: 12px;
color: #00d4ff;
border: 2px solid transparent;
font-family: 'Rajdhani', sans-serif;
font-weight: 600;
transition: all 0.3s ease;
}
.stTabs [data-baseweb="tab"]:hover {
background: linear-gradient(135deg, #00d4ff, #0099cc);
color: #000000;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 212, 255, 0.4);
}
.stTabs [data-baseweb="tab"][aria-selected="true"] {
background: linear-gradient(135deg, #00d4ff, #6b1cb0);
color: #000000;
border: 2px solid #ff00ff;
}
/* Button styling */
.stButton > button {
background: linear-gradient(135deg, #00d4ff, #0099cc);
color: #000000;
border: none;
border-radius: 10px;
font-family: 'Rajdhani', sans-serif;
font-weight: 600;
padding: 0.5rem 1rem;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}
.stButton > button:hover {
background: linear-gradient(135deg, #005461, #002d7a);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 255, 136, 0.4);
}
.stButton > button[kind="primary"] {
background: linear-gradient(135deg, #ff00ff, #cc00cc);
color: #ffffff;
}
.stButton > button[kind="primary"]:hover {
background: linear-gradient(135deg, #ff44ff, #ff00cc);
}
/* Success/Error/Info boxes */
.success-box {
background: linear-gradient(135deg, #00ff88, #00cc6a);
color: #000000;
border-left: 5px solid #ffffff;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
font-family: 'Rajdhani', sans-serif;
font-weight: 600;
box-shadow: 0 4px 15px rgba(0, 255, 136, 0.3);
}
.error-box {
background: linear-gradient(135deg, #ff4444, #cc3333);
color: #ffffff;
border-left: 5px solid #ffffff;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
font-family: 'Rajdhani', sans-serif;
font-weight: 600;
box-shadow: 0 4px 15px rgba(255, 68, 68, 0.3);
}
.info-box {
background: linear-gradient(135deg, #00d4ff, #0099cc);
color: #000000;
border-left: 5px solid #ffffff;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
font-family: 'Rajdhani', sans-serif;
font-weight: 600;
box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}
/* Form styling */
.stTextArea textarea, .stTextInput input, .stSelectbox select {
background: rgba(26, 26, 46, 0.8);
color: #ffffff;
border: 2px solid #00d4ff;
border-radius: 8px;
font-family: 'Rajdhani', sans-serif;
}
/* Metric styling */
.css-1xarl3l {
background: linear-gradient(135deg, rgba(0, 212, 255, 0.1), rgba(255, 0, 255, 0.1));
border: 2px solid #00d4ff;
border-radius: 10px;
padding: 1rem;
}
/* Code blocks */
.stCode {
background: rgba(0, 0, 0, 0.8) !important;
border: 1px solid #00d4ff;
border-radius: 8px;
}
/* Infinity symbol animation */
.infinity {
display: inline-block;
animation: rotate 3s linear infinite;
color: #00ff88;
font-size: 1.2em;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Glowing effects */
.glow {
text-shadow: 0 0 10px currentColor;
}
/* Dataframe styling */
.stDataFrame {
background: rgba(26, 26, 46, 0.8);
border: 1px solid #00d4ff;
border-radius: 8px;
}
</style>
""", unsafe_allow_html=True)
class CodeOracle:
def __init__(self, api_key: str):
self.api_key = api_key
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel('gemini-2.5-flash')
self.projects = {}
def generate_project(self, prompt: str, language: str, architecture: str = "standard") -> Dict:
"""Generate a complete project from natural language prompt"""
system_prompt = f"""
You are CodeOracle, an expert software engineer. Generate a complete, production-ready {language} project based on the user's requirements.
CRITICAL REQUIREMENTS:
1. Create a multi-file project structure with proper organization
2. Include all necessary files: source code, tests, README.md, requirements/package files, .gitignore
3. Write actual working code, not pseudocode or placeholders
4. Include comprehensive error handling and logging
5. Follow {language} best practices and conventions
6. Make the code modular and well-documented
7. Include unit tests and integration tests
8. Add security considerations where applicable
Project Requirements: {prompt}
Target Language: {language}
Architecture Pattern: {architecture}
Return the response as a JSON object with this exact structure:
{{
"project_name": "project-name",
"description": "Brief project description",
"files": {{
"filename1.ext": "file content here",
"filename2.ext": "file content here",
"tests/test_file.ext": "test content here",
"README.md": "comprehensive readme",
".gitignore": "appropriate gitignore for {language}"
}},
"dependencies": ["list", "of", "dependencies"],
"build_commands": ["command1", "command2"],
"run_commands": ["command1", "command2"],
"test_commands": ["test command"],
"architecture_notes": "explanation of the chosen architecture"
}}
"""
try:
response = self.model.generate_content(system_prompt)
# Parse JSON response
json_start = response.text.find('{')
json_end = response.text.rfind('}') + 1
json_str = response.text[json_start:json_end]
project_data = json.loads(json_str)
return project_data
except Exception as e:
st.error(f"Generation failed: {str(e)}")
return None
def run_tests(self, project_path: str, language: str, test_commands: List[str]) -> Dict:
"""Run automated tests and return results"""
results = {
"success": False,
"output": "",
"errors": "",
"coverage": 0,
"failed_tests": []
}
try:
os.chdir(project_path)
for cmd in test_commands:
process = subprocess.run(
cmd.split(),
capture_output=True,
text=True,
timeout=30
)
results["output"] += f"Command: {cmd}\n"
results["output"] += process.stdout
if process.returncode != 0:
results["errors"] += process.stderr
results["failed_tests"].append(cmd)
else:
results["success"] = True
except subprocess.TimeoutExpired:
results["errors"] = "Test execution timed out"
except Exception as e:
results["errors"] = str(e)
return results
def debug_and_fix(self, project_data: Dict, test_results: Dict, max_iterations: int = 3) -> Dict:
"""Autonomous debugging loop"""
debug_prompt = f"""
The following project has failing tests. Analyze the errors and fix the code:
Project Structure: {list(project_data['files'].keys())}
Test Errors: {test_results['errors']}
Failed Commands: {test_results['failed_tests']}
Current Code Files:
{json.dumps(project_data['files'], indent=2)}
Fix the issues and return the corrected files in the same JSON structure.
Focus on:
1. Syntax errors
2. Import/dependency issues
3. Logic errors causing test failures
4. Missing error handling
Return only the corrected files that need changes in this format:
{{
"fixed_files": {{
"filename": "corrected content"
}},
"fix_explanation": "What was fixed and why"
}}
"""
try:
response = self.model.generate_content(debug_prompt)
json_start = response.text.find('{')
json_end = response.text.rfind('}') + 1
json_str = response.text[json_start:json_end]
fix_data = json.loads(json_str)
# Apply fixes
for filename, content in fix_data.get("fixed_files", {}).items():
project_data["files"][filename] = content
return {
"success": True,
"explanation": fix_data.get("fix_explanation", ""),
"updated_project": project_data
}
except Exception as e:
return {"success": False, "error": str(e)}
def refactor_code(self, project_data: Dict, refactor_type: str) -> Dict:
"""Refactor code for different objectives"""
refactor_prompts = {
"readability": "Refactor for maximum readability and maintainability",
"performance": "Optimize for performance and efficiency",
"size": "Minimize code size and bundle size",
"security": "Enhance security and add security best practices"
}
prompt = f"""
{refactor_prompts[refactor_type]} for this project:
{json.dumps(project_data['files'], indent=2)}
Return the refactored files in JSON format with explanations.
"""
try:
response = self.model.generate_content(prompt)
# Parse and return refactored code
return {"success": True, "refactored": response.text}
except Exception as e:
return {"success": False, "error": str(e)}
def explain_code(self, code: str, language: str) -> str:
"""Provide detailed code explanation"""
prompt = f"""
Explain this {language} code line by line with:
1. What each function/class does
2. Time/space complexity analysis
3. Alternative approaches
4. How a senior developer would improve it
5. Potential issues or edge cases
Code:
{code}
"""
try:
response = self.model.generate_content(prompt)
return response.text
except Exception as e:
return f"Explanation failed: {str(e)}"
def security_scan(self, project_data: Dict, language: str) -> Dict:
"""Perform security analysis"""
prompt = f"""
Perform a comprehensive security analysis of this {language} project using OWASP guidelines:
{json.dumps(project_data['files'], indent=2)}
Identify:
1. Security vulnerabilities
2. Input validation issues
3. Authentication/authorization flaws
4. Data exposure risks
5. Dependency vulnerabilities
Return findings with severity levels and suggested fixes.
"""
try:
response = self.model.generate_content(prompt)
return {"success": True, "report": response.text}
except Exception as e:
return {"success": False, "error": str(e)}
def generate_cicd(self, project_data: Dict, language: str, platform: str) -> str:
"""Generate CI/CD configuration"""
prompt = f"""
Generate {platform} CI/CD configuration for this {language} project:
Project: {project_data['project_name']}
Dependencies: {project_data['dependencies']}
Build Commands: {project_data['build_commands']}
Test Commands: {project_data['test_commands']}
Include:
1. Build pipeline
2. Test automation
3. Security scanning
4. Deployment steps
5. Environment management
Platform: {platform}
"""
try:
response = self.model.generate_content(prompt)
return response.text
except Exception as e:
return f"CI/CD generation failed: {str(e)}"
def create_project_files(project_data: Dict, base_path: str):
"""Create actual files from project data"""
# Ensure base directory exists
os.makedirs(base_path, exist_ok=True)
for filename, content in project_data["files"].items():
file_path = os.path.join(base_path, filename)
# Create directory if filename contains subdirectories
file_dir = os.path.dirname(file_path)
if file_dir and file_dir != base_path:
os.makedirs(file_dir, exist_ok=True)
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
except Exception as e:
st.error(f"Failed to create file {filename}: {str(e)}")
continue
def create_zip_download(project_data: Dict) -> bytes:
"""Create downloadable zip file"""
zip_buffer = tempfile.NamedTemporaryFile(delete=False, suffix='.zip')
with zipfile.ZipFile(zip_buffer.name, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for filename, content in project_data["files"].items():
zip_file.writestr(filename, content)
with open(zip_buffer.name, 'rb') as f:
zip_data = f.read()
os.unlink(zip_buffer.name)
return zip_data
# Initialize session state variables to prevent reruns
def init_session_state():
"""Initialize all session state variables"""
if 'oracle' not in st.session_state:
st.session_state.oracle = None
if 'current_project' not in st.session_state:
st.session_state.current_project = None
if 'test_results' not in st.session_state:
st.session_state.test_results = None
if 'generation_status' not in st.session_state:
st.session_state.generation_status = None
if 'build_output' not in st.session_state:
st.session_state.build_output = None
if 'security_report' not in st.session_state:
st.session_state.security_report = None
if 'cicd_configs' not in st.session_state:
st.session_state.cicd_configs = {}
if 'refactor_results' not in st.session_state:
st.session_state.refactor_results = {}
if 'explanations' not in st.session_state:
st.session_state.explanations = {}
if 'project_metrics' not in st.session_state:
st.session_state.project_metrics = {}
# New authentication states for Singularity-AI app
if "singularity_app_authenticated" not in st.session_state:
st.session_state.singularity_app_authenticated = False
if "singularity_app_login_attempts" not in st.session_state:
st.session_state.singularity_app_login_attempts = 0
def main():
# Initialize session state
init_session_state()
# --- START: INITIAL APP PASSWORD PROTECTION ---
# Define the maximum number of allowed attempts
MAX_APP_ATTEMPTS = 3
try:
# The password should be set in your Streamlit secrets
# e.g., in .streamlit/secrets.toml
# singularity_app_password = "your_secret_password"
correct_app_password = st.secrets["singularity_app_password"]
except KeyError:
st.error("`singularity_app_password` not found in secrets.toml. Please set it to run the app.")
st.stop()
# If not authenticated for initial app access, show the login screen.
if not st.session_state.singularity_app_authenticated:
# Check if the user is locked out
if st.session_state.singularity_app_login_attempts >= MAX_APP_ATTEMPTS:
st.markdown('<div style="text-align: center; margin-top: 100px;">', unsafe_allow_html=True)
st.error("🚫 **Access Blocked**")
st.warning("Too many incorrect password attempts. Please close and reopen the app to try again.")
st.markdown('</div>', unsafe_allow_html=True)
st.stop()
# Display the login form
st.markdown('<div style="text-align: center; margin-top: 100px;">', unsafe_allow_html=True)
st.markdown("<h2 style='color: #00d4ff;'>Singularity-AI Login</h2>", unsafe_allow_html=True) # Use theme color
password_input = st.text_input(
"Enter Password",
type="password",
key="singularity_app_password_input_field",
label_visibility="collapsed",
placeholder="Enter app password to unlock Singularity-AI"
)
if st.button("Unlock App", use_container_width=True):
if password_input == correct_app_password:
st.session_state.singularity_app_authenticated = True
st.session_state.singularity_app_login_attempts = 0 # Reset on success
st.rerun()
else:
st.session_state.singularity_app_login_attempts += 1
attempts_left = MAX_APP_ATTEMPTS - st.session_state.singularity_app_login_attempts
st.error(f"Incorrect password. You have {attempts_left} attempt(s) left.")
st.rerun() # Rerun to update the UI and check the lockout condition
st.markdown('</div>', unsafe_allow_html=True)
st.stop()
# --- END: INITIAL APP PASSWORD PROTECTION ---
# Title and header with new theme
st.markdown('<h1>♾️ Singularity-AI</h1>', unsafe_allow_html=True)
st.markdown('<div class="subtitle">Where AI meets infinity <span class="infinity">♾️</span></div>', unsafe_allow_html=True)
# Sidebar configuration
with st.sidebar:
st.markdown("### ⚙️ Configuration")
# --- Load API Key from secrets (after successful app authentication) ---
try:
api_key = st.secrets["GEMINI_API_KEY"]
except KeyError:
st.error("`GEMINI_API_KEY` not found in secrets.toml. Please set it to run the app.")
st.stop()
# Display a confirmation that API key is loaded (optional, for user feedback)
st.success("🔑 Gemini API Key loaded from secrets.")
# --- END API Key Loading ---
# Initialize CodeOracle only once
if st.session_state.oracle is None:
st.session_state.oracle = CodeOracle(api_key)
st.success("✅ Singularity-AI Initialized!")
# Language selection
language = st.selectbox(
"💻 Programming Language",
["Python", "JavaScript", "TypeScript", "Go", "Rust", "Java", "Kotlin", "C++"],
key="language_select"
)
# Architecture pattern
architecture = st.selectbox(
"🏗️ Architecture Pattern",
["Standard", "MVC", "Microservices", "Serverless", "Clean Architecture", "Hexagonal"],
key="architecture_select"
)
# Advanced settings
st.markdown("### 🔬 Advanced Settings")
max_debug_iterations = st.slider("Max Debug Iterations", 1, 10, 3, key="debug_iter")
auto_test = st.checkbox("Auto-run tests", value=True, key="auto_test")
auto_debug = st.checkbox("Auto-debug failures", value=True, key="auto_debug")
# Main interface tabs
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
"✨ Generate", "🔧 Build & Test", "🔍 Analysis", "📊 Dashboard", "🛡️ Security", "🎉 Deploy"
])
with tab1:
st.markdown("### 🎯 Project Generator")
# Project generation form
col1, col2 = st.columns([3, 1])
with col1:
prompt = st.text_area(
"📝 Describe your project:",
#value=default_prompt,
placeholder="Build a REST API for a todo app with user authentication, SQLite database, and CRUD operations",
height=120,
key="project_prompt"
)
with col2:
template = st.selectbox(
"⚡ Quick Templates",
["Custom", "Web App + Auth", "REST API", "ML Service", "CLI Tool", "Microservice"],
key="template_select"
)
# Template auto-fill
# Template auto-fill - set default value based on template
template_prompts = {
"Custom": "",
"Web App + Auth": "Create a modern web application with user authentication, responsive design, and database integration",
"REST API": "Build a RESTful API with CRUD operations, authentication, and comprehensive documentation",
"ML Service": "Create a machine learning inference service with model loading, prediction endpoints, and monitoring",
"CLI Tool": "Build a command-line tool with argument parsing, configuration management, and user-friendly output",
"Microservice": "Create a microservice with health checks, logging, metrics, and containerization"
}
# Set the default prompt value based on template selection
default_prompt = template_prompts.get(template, "")
col1, col2 = st.columns(2)
with col1:
if st.button("🧙♂️ Generate Project", type="primary", key="generate_btn"):
if prompt:
with st.spinner("🔮 Singularity-AI is crafting your project..."):
project_data = st.session_state.oracle.generate_project(prompt, language, architecture)
if project_data:
st.session_state.current_project = project_data
st.session_state.generation_status = "success"
# Calculate initial metrics
total_lines = sum(len(content.split('\n')) for content in project_data['files'].values())
st.session_state.project_metrics = {
'total_files': len(project_data['files']),
'total_lines': total_lines,
'avg_lines_per_file': round(total_lines/len(project_data['files'])),
'dependencies': len(project_data.get('dependencies', []))
}
else:
st.session_state.generation_status = "error"
else:
st.error("⚠️ Please provide a project description")
# Display project overview (persistent)
if st.session_state.current_project and st.session_state.generation_status == "success":
project = st.session_state.current_project
st.markdown('<div class="success-box">✨ Project generated successfully!</div>', unsafe_allow_html=True)
st.markdown("### 📋 Project Overview")
col1, col2 = st.columns(2)
with col1:
st.markdown(f"**🏷️ Name:** `{project['project_name']}`")
st.markdown(f"**💻 Language:** `{language}`")
st.markdown(f"**📁 Files:** `{st.session_state.project_metrics['total_files']}`")
with col2:
st.markdown(f"**📦 Dependencies:** `{st.session_state.project_metrics['dependencies']}`")
st.markdown(f"**🏗️ Architecture:** `{architecture}`")
st.markdown(f"**📏 Lines:** `{st.session_state.project_metrics['total_lines']}`")
st.markdown(f"**📝 Description:** {project['description']}")
# File browser
st.markdown("### 📁 Generated Files")
selected_file = st.selectbox(
"View file:",
list(project['files'].keys()),
key="file_browser"
)
if selected_file:
file_ext = selected_file.split('.')[-1] if '.' in selected_file else 'text'
st.code(project['files'][selected_file], language=file_ext)
# Download button
col1, col2 = st.columns(2)
with col1:
zip_data = create_zip_download(project)
st.download_button(
label="📦 Download Project ZIP",
data=zip_data,
file_name=f"{project['project_name']}.zip",
mime="application/zip",
key="download_zip"
)
with tab2:
st.markdown("### 🔧 Build & Test Pipeline")
if not st.session_state.current_project:
st.markdown('<div class="info-box">ℹ️ Generate a project first to see build and test options</div>', unsafe_allow_html=True)
else:
project = st.session_state.current_project
col1, col2, col3 = st.columns(3)
with col1:
if st.button("🔨 Build Project", key="build_btn"):
with st.spinner("🏗️ Building project..."):
# Create temporary directory
temp_dir = tempfile.mkdtemp()
create_project_files(project, temp_dir)
# Run build commands
build_success = True
build_output = ""
for cmd in project.get('build_commands', []):
try:
result = subprocess.run(
cmd.split(),
cwd=temp_dir,
capture_output=True,
text=True,
timeout=60
)
build_output += f"$ {cmd}\n{result.stdout}\n"
if result.returncode != 0:
build_success = False
build_output += f"Error: {result.stderr}\n"
except Exception as e:
build_success = False
build_output += f"Build failed: {str(e)}\n"
st.session_state.build_output = {
"success": build_success,
"output": build_output
}
# Display build results (persistent)
if st.session_state.build_output:
if st.session_state.build_output["success"]:
st.markdown('<div class="success-box">✅ Build successful!</div>', unsafe_allow_html=True)
else:
st.markdown('<div class="error-box">❌ Build failed</div>', unsafe_allow_html=True)
st.code(st.session_state.build_output["output"], language="bash")
with col2:
if st.button("🧪 Run Tests", key="test_btn"):
with st.spinner("🔬 Running tests..."):
temp_dir = tempfile.mkdtemp()
create_project_files(project, temp_dir)
test_results = st.session_state.oracle.run_tests(
temp_dir,
language,
project.get('test_commands', [])
)
st.session_state.test_results = test_results
# Display test results (persistent)
if st.session_state.test_results:
if st.session_state.test_results["success"]:
st.markdown('<div class="success-box">✅ All tests passed!</div>', unsafe_allow_html=True)
else:
st.markdown('<div class="error-box">❌ Some tests failed</div>', unsafe_allow_html=True)
st.code(st.session_state.test_results["output"], language="bash")
if st.session_state.test_results["errors"]:
st.error("Test Errors:")
st.code(st.session_state.test_results["errors"], language="bash")
with col3:
if st.button("🔧 Auto-Debug", key="debug_btn"):
if st.session_state.test_results and not st.session_state.test_results["success"]:
with st.spinner("🤖 Auto-debugging..."):
debug_result = st.session_state.oracle.debug_and_fix(
project,
st.session_state.test_results,
max_debug_iterations
)
if debug_result["success"]:
st.session_state.current_project = debug_result["updated_project"]
st.success("🔧 Auto-debug completed!")
st.markdown(debug_result["explanation"])
else:
st.error(f"Auto-debug failed: {debug_result['error']}")
else:
st.info("No failing tests to debug")
# Refactoring options
st.markdown("### 🔄 Refactoring Options")
refactor_col1, refactor_col2, refactor_col3, refactor_col4 = st.columns(4)
with refactor_col1:
if st.button("📚 Readability", key="refactor_readability"):
with st.spinner("📖 Refactoring for readability..."):
result = st.session_state.oracle.refactor_code(project, "readability")
if result["success"]:
st.session_state.refactor_results["readability"] = result["refactored"]
# Display readability refactor result (persistent)
if "readability" in st.session_state.refactor_results:
with st.expander("📚 Readability Refactor Result"):
st.markdown(st.session_state.refactor_results["readability"])
with refactor_col2:
if st.button("⚡ Performance", key="refactor_performance"):
with st.spinner("🚀 Optimizing performance..."):
result = st.session_state.oracle.refactor_code(project, "performance")
if result["success"]:
st.session_state.refactor_results["performance"] = result["refactored"]
# Display performance refactor result (persistent)
if "performance" in st.session_state.refactor_results:
with st.expander("⚡ Performance Refactor Result"):
st.markdown(st.session_state.refactor_results["performance"])
with refactor_col3:
if st.button("📦 Size", key="refactor_size"):
with st.spinner("📉 Minimizing size..."):
result = st.session_state.oracle.refactor_code(project, "size")
if result["success"]:
st.session_state.refactor_results["size"] = result["refactored"]
# Display size refactor result (persistent)
if "size" in st.session_state.refactor_results:
with st.expander("📦 Size Refactor Result"):
st.markdown(st.session_state.refactor_results["size"])
with refactor_col4:
if st.button("🛡️ Security", key="refactor_security"):
with st.spinner("🔒 Enhancing security..."):
result = st.session_state.oracle.refactor_code(project, "security")
if result["success"]:
st.session_state.refactor_results["security"] = result["refactored"]
# Display security refactor result (persistent)
if "security" in st.session_state.refactor_results:
with st.expander("🛡️ Security Refactor Result"):
st.markdown(st.session_state.refactor_results["security"])
with tab3:
st.markdown("### 🔍 Code Analysis & Insights")
if not st.session_state.current_project:
st.markdown('<div class="info-box">ℹ️ Generate a project first to see analysis options</div>', unsafe_allow_html=True)
else:
project = st.session_state.current_project
# Code explanation
st.markdown("### 📖 Explain Code")
explain_file = st.selectbox(
"Select file to explain:",
list(project['files'].keys()),
key="explain_file_select"
)
if st.button("🔍 Explain This File", key="explain_btn"):
with st.spinner("🧠 Analyzing code..."):
explanation = st.session_state.oracle.explain_code(
project['files'][explain_file],
language
)
st.session_state.explanations[explain_file] = explanation
# Display explanation (persistent)
if explain_file in st.session_state.explanations:
with st.expander(f"📖 Explanation: {explain_file}"):
st.markdown(st.session_state.explanations[explain_file])
# Architecture visualization
st.markdown("### 🏗️ Architecture Overview")
col1, col2 = st.columns(2)
with col1:
if st.button("📊 Visualize Architecture", key="viz_arch_btn"):
# Create a simple architecture diagram
files = list(project['files'].keys())
file_types = {}
for file in files:
ext = file.split('.')[-1] if '.' in file else 'other'
file_types[ext] = file_types.get(ext, 0) + 1
# Store visualization data in session state
st.session_state.arch_viz_data = file_types
# Display architecture visualization (persistent)
if hasattr(st.session_state, 'arch_viz_data'):
# Create pie chart of file types
fig = px.pie(
values=list(st.session_state.arch_viz_data.values()),
names=list(st.session_state.arch_viz_data.keys()),
title="Project File Distribution",
color_discrete_sequence=px.colors.qualitative.Set3
)
fig.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
st.plotly_chart(fig, use_container_width=True)
# Dependency graph (simplified)
st.markdown("### 📦 Dependencies")
deps = project.get('dependencies', [])
if deps:
dep_df = pd.DataFrame({'Dependency': deps, 'Type': ['External'] * len(deps)})
st.dataframe(dep_df, use_container_width=True)
else:
st.info("No external dependencies found")
# Code metrics
st.markdown("### 📏 Code Metrics")
st.markdown("### 📏 Code Metrics")
if hasattr(st.session_state, 'project_metrics') and st.session_state.project_metrics:
metrics = st.session_state.project_metrics
col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Files", metrics['total_files'])
col2.metric("Total Lines", metrics['total_lines'])
col3.metric("Avg Lines/File", metrics['avg_lines_per_file'])
col4.metric("Dependencies", metrics['dependencies'])
elif st.session_state.current_project:
# Fallback calculation if metrics not available
project = st.session_state.current_project
total_files = len(project['files'])
total_lines = sum(len(content.split('\n')) for content in project['files'].values())
avg_lines = round(total_lines/total_files) if total_files > 0 else 0
dependencies = len(project.get('dependencies', []))
col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Files", total_files)
col2.metric("Total Lines", total_lines)
col3.metric("Avg Lines/File", avg_lines)
col4.metric("Dependencies", dependencies)
with tab4:
st.markdown("### 📊 Project Health Dashboard")
if not st.session_state.current_project:
st.markdown('<div class="info-box">ℹ️ Generate a project first to see the dashboard</div>', unsafe_allow_html=True)
else:
project = st.session_state.current_project
# Health score calculation (mock)
health_score = 85 # This would be calculated based on various metrics
col1, col2, col3 = st.columns(3)
with col1: