Artificial-superintelligence commited on
Commit
cff1791
·
verified ·
1 Parent(s): 5d34773

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -261
app.py CHANGED
@@ -3,318 +3,246 @@ import google.generativeai as genai
3
  import requests
4
  import subprocess
5
  import os
 
6
  import pandas as pd
7
- import numpy as np
8
  from sklearn.model_selection import train_test_split
9
  from sklearn.ensemble import RandomForestClassifier
10
- import torch
11
- import torch.nn as nn
12
- import torch.optim as optim
13
- from transformers import AutoTokenizer, AutoModel, pipeline
14
- import ast
15
- import networkx as nx
16
- import matplotlib.pyplot as plt
17
- import re
18
- import javalang
19
- import clang.cindex
20
- import radon.metrics as radon_metrics
21
- import radon.complexity as radon_complexity
22
- import black
23
- import isort
24
- import autopep8
25
 
26
  # Configure the Gemini API
27
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
28
 
29
  # Create the model with optimized parameters and enhanced system instructions
30
  generation_config = {
31
- "temperature": 0.7,
32
- "top_p": 0.9,
33
- "top_k": 40,
34
- "max_output_tokens": 32768,
35
  }
36
 
37
  model = genai.GenerativeModel(
38
  model_name="gemini-1.5-pro",
39
  generation_config=generation_config,
40
  system_instruction="""
41
- You are Ath, an extremely advanced code assistant with deep expertise in AI, machine learning, software engineering, and multiple programming languages. You provide cutting-edge, optimized, and secure code solutions across various domains. Use your vast knowledge to generate high-quality code, perform advanced analyses, and offer insightful optimizations. Adapt your language and explanations based on the user's expertise level.
 
42
  """
43
  )
44
  chat_session = model.start_chat(history=[])
45
 
46
- # Load pre-trained models for code understanding and generation
47
- tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
48
- codebert_model = AutoModel.from_pretrained("microsoft/codebert-base")
49
- code_generation_model = pipeline("text-generation", model="EleutherAI/gpt-neo-2.7B")
50
-
51
- class AdvancedCodeImprovement(nn.Module):
52
- def __init__(self, input_dim):
53
- super(AdvancedCodeImprovement, self).__init__()
54
- self.fc1 = nn.Linear(input_dim, 1024)
55
- self.fc2 = nn.Linear(1024, 512)
56
- self.fc3 = nn.Linear(512, 256)
57
- self.fc4 = nn.Linear(256, 128)
58
- self.fc5 = nn.Linear(128, 64)
59
- self.fc6 = nn.Linear(64, 32)
60
- self.fc7 = nn.Linear(32, 16)
61
- self.fc8 = nn.Linear(16, 4) # Multiple classification: style, efficiency, security, maintainability
62
-
63
- def forward(self, x):
64
- x = torch.relu(self.fc1(x))
65
- x = torch.relu(self.fc2(x))
66
- x = torch.relu(self.fc3(x))
67
- x = torch.relu(self.fc4(x))
68
- x = torch.relu(self.fc5(x))
69
- x = torch.relu(self.fc6(x))
70
- x = torch.relu(self.fc7(x))
71
- return torch.sigmoid(self.fc8(x))
72
-
73
- code_improvement_model = AdvancedCodeImprovement(768) # 768 is BERT's output dimension
74
- optimizer = optim.Adam(code_improvement_model.parameters())
75
- criterion = nn.BCELoss()
76
-
77
  def generate_response(user_input):
 
78
  try:
79
  response = chat_session.send_message(user_input)
80
  return response.text
81
  except Exception as e:
82
- return f"Error in generating response: {str(e)}"
83
-
84
- def detect_language(code):
85
- # Simple language detection based on keywords and syntax
86
- if re.search(r'\b(def|class|import)\b', code):
87
- return 'python'
88
- elif re.search(r'\b(function|var|let|const)\b', code):
89
- return 'javascript'
90
- elif re.search(r'\b(public|private|class)\b', code):
91
- return 'java'
92
- elif re.search(r'\b(#include|int main)\b', code):
93
- return 'c++'
94
- else:
95
- return 'unknown'
96
-
97
- def validate_and_fix_code(code, language):
98
- if language == 'python':
99
- try:
100
- fixed_code = autopep8.fix_code(code)
101
- fixed_code = isort.SortImports(file_contents=fixed_code).output
102
- fixed_code = black.format_str(fixed_code, mode=black.FileMode())
103
- return fixed_code
104
- except Exception as e:
105
- return code, f"Error in fixing Python code: {str(e)}"
106
- elif language == 'javascript':
107
- # Use a JS beautifier (placeholder)
108
- return code
109
- elif language == 'java':
110
- # Use a Java formatter (placeholder)
111
- return code
112
- elif language == 'c++':
113
- # Use a C++ formatter (placeholder)
114
- return code
115
- else:
116
- return code
117
 
118
  def optimize_code(code):
119
- language = detect_language(code)
120
- fixed_code, fix_error = validate_and_fix_code(code, language)
121
-
122
- if fix_error:
123
- return fixed_code, fix_error
124
-
125
- if language == 'python':
126
- try:
127
- tree = ast.parse(fixed_code)
128
- # Perform advanced Python-specific optimizations
129
- optimizer = PythonCodeOptimizer()
130
- optimized_tree = optimizer.visit(tree)
131
- optimized_code = ast.unparse(optimized_tree)
132
- except SyntaxError as e:
133
- return fixed_code, f"SyntaxError: {str(e)}"
134
- elif language == 'java':
135
- try:
136
- tree = javalang.parse.parse(fixed_code)
137
- # Perform Java-specific optimizations
138
- optimizer = JavaCodeOptimizer()
139
- optimized_code = optimizer.optimize(tree)
140
- except javalang.parser.JavaSyntaxError as e:
141
- return fixed_code, f"JavaSyntaxError: {str(e)}"
142
- elif language == 'c++':
143
- try:
144
- index = clang.cindex.Index.create()
145
- tu = index.parse('temp.cpp', args=['-std=c++14'], unsaved_files=[('temp.cpp', fixed_code)])
146
- # Perform C++-specific optimizations
147
- optimizer = CppCodeOptimizer()
148
- optimized_code = optimizer.optimize(tu)
149
- except Exception as e:
150
- return fixed_code, f"C++ Parsing Error: {str(e)}"
151
- else:
152
- optimized_code = fixed_code # For unsupported languages, return the fixed code
153
-
154
- # Run language-specific linter
155
- lint_results = run_linter(optimized_code, language)
156
-
157
- return optimized_code, lint_results
158
 
159
- def run_linter(code, language):
160
- if language == 'python':
161
- with open("temp_code.py", "w") as file:
162
- file.write(code)
163
- result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
164
- os.remove("temp_code.py")
165
- return result.stdout
166
- elif language == 'javascript':
167
- # Run ESLint (placeholder)
168
- return "JavaScript linting not implemented"
169
- elif language == 'java':
170
- # Run CheckStyle (placeholder)
171
- return "Java linting not implemented"
172
- elif language == 'c++':
173
- # Run cppcheck (placeholder)
174
- return "C++ linting not implemented"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  else:
176
- return "Linting not available for the detected language"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
- def fetch_from_github(query):
179
- headers = {"Authorization": f"token {st.secrets['GITHUB_TOKEN']}"}
180
- response = requests.get(f"https://api.github.com/search/code?q={query}", headers=headers)
181
- if response.status_code == 200:
182
- return response.json()['items'][:5] # Return top 5 results
183
- return []
184
 
185
- def analyze_code_quality(code):
186
- inputs = tokenizer(code, return_tensors="pt", truncation=True, max_length=512, padding="max_length")
187
-
188
- with torch.no_grad():
189
- outputs = codebert_model(**inputs)
190
-
191
- cls_embedding = outputs.last_hidden_state[:, 0, :]
192
- predictions = code_improvement_model(cls_embedding)
193
 
194
- quality_scores = {
195
- "style": predictions[0][0].item(),
196
- "efficiency": predictions[0][1].item(),
197
- "security": predictions[0][2].item(),
198
- "maintainability": predictions[0][3].item()
199
  }
200
-
201
- # Calculate additional metrics
202
- language = detect_language(code)
203
- if language == 'python':
204
- complexity = radon_complexity.cc_visit(code)
205
- maintainability = radon_metrics.mi_visit(code, True)
206
- quality_scores["cyclomatic_complexity"] = complexity[0].complexity
207
- quality_scores["maintainability_index"] = maintainability
208
-
209
- return quality_scores
210
-
211
- def visualize_code_structure(code):
212
- try:
213
- tree = ast.parse(code)
214
- graph = nx.DiGraph()
215
-
216
- def add_nodes_edges(node, parent=None):
217
- node_id = id(node)
218
- graph.add_node(node_id, label=f"{type(node).__name__}\n{ast.unparse(node)[:20]}")
219
- if parent:
220
- graph.add_edge(id(parent), node_id)
221
- for child in ast.iter_child_nodes(node):
222
- add_nodes_edges(child, node)
223
-
224
- add_nodes_edges(tree)
225
-
226
- plt.figure(figsize=(15, 10))
227
- pos = nx.spring_layout(graph, k=0.9, iterations=50)
228
- nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=8, font_weight='bold', arrows=True)
229
- labels = nx.get_node_attributes(graph, 'label')
230
- nx.draw_networkx_labels(graph, pos, labels, font_size=6)
231
-
232
- return plt
233
- except SyntaxError:
234
- return None
235
-
236
- def suggest_improvements(code, quality_scores):
237
- suggestions = []
238
- if quality_scores["style"] < 0.7:
239
- suggestions.append("Consider improving code style for better readability.")
240
- if quality_scores["efficiency"] < 0.7:
241
- suggestions.append("There might be room for optimizing the code's efficiency.")
242
- if quality_scores["security"] < 0.8:
243
- suggestions.append("Review the code for potential security vulnerabilities.")
244
- if quality_scores["maintainability"] < 0.7:
245
- suggestions.append("The code could be refactored to improve maintainability.")
246
- if "cyclomatic_complexity" in quality_scores and quality_scores["cyclomatic_complexity"] > 10:
247
- suggestions.append("Consider breaking down complex functions to reduce cyclomatic complexity.")
248
- return suggestions
249
-
250
- # Streamlit UI setup
251
- st.set_page_config(page_title="Highly Advanced AI Code Assistant", page_icon="🚀", layout="wide")
252
-
253
- # ... (keep the existing CSS styles) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
256
- st.title("🚀 Highly Advanced AI Code Assistant")
257
- st.markdown('<p class="subtitle">Powered by Advanced AI & Multi-Domain Expertise</p>', unsafe_allow_html=True)
258
 
259
- prompt = st.text_area("What advanced code task can I assist you with today?", height=120)
260
 
261
- if st.button("Generate Advanced Code"):
262
  if prompt.strip() == "":
263
  st.error("Please enter a valid prompt.")
264
  else:
265
- with st.spinner("Generating and analyzing code..."):
266
- completed_text = generate_response(prompt)
267
- if "Error in generating response" in completed_text:
268
- st.error(completed_text)
269
- else:
270
- optimized_code, lint_results = optimize_code(completed_text)
271
-
272
- if "Error" in lint_results:
273
- st.warning(f"Issues detected in the generated code. Attempting to fix...")
274
- st.code(optimized_code)
275
- st.info("Please review the code above. It may contain errors or be incomplete.")
276
  else:
277
- quality_scores = analyze_code_quality(optimized_code)
278
- overall_quality = sum(quality_scores.values()) / len(quality_scores)
279
- st.success(f"Code generated and optimized successfully! Overall Quality Score: {overall_quality:.2f}")
280
 
281
  st.markdown('<div class="output-container">', unsafe_allow_html=True)
282
  st.markdown('<div class="code-block">', unsafe_allow_html=True)
283
  st.code(optimized_code)
284
  st.markdown('</div>', unsafe_allow_html=True)
 
285
 
286
- col1, col2 = st.columns(2)
287
- with col1:
288
- st.subheader("Code Quality Metrics")
289
- for metric, score in quality_scores.items():
290
- st.metric(metric.capitalize(), f"{score:.2f}")
291
-
292
- with col2:
293
- st.subheader("Improvement Suggestions")
294
- suggestions = suggest_improvements(optimized_code, quality_scores)
295
- for suggestion in suggestions:
296
- st.info(suggestion)
297
 
298
- visualization = visualize_code_structure(optimized_code)
299
- if visualization:
300
- with st.expander("View Advanced Code Structure Visualization"):
301
- st.pyplot(visualization)
302
  else:
303
- st.warning("Unable to generate code structure visualization.")
304
-
305
- with st.expander("View Detailed Lint Results"):
306
- st.text(lint_results)
307
-
308
- with st.expander("Explore Similar Code from GitHub"):
309
- github_results = fetch_from_github(prompt)
310
- for item in github_results:
311
- st.markdown(f"[{item['name']}]({item['html_url']})")
312
-
313
- st.markdown('</div>', unsafe_allow_html=True)
314
 
315
  st.markdown("""
316
  <div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
317
- Crafted with 🚀 by Your Highly Advanced AI Code Assistant
318
  </div>
319
  """, unsafe_allow_html=True)
320
 
 
3
  import requests
4
  import subprocess
5
  import os
6
+ import pylint
7
  import pandas as pd
 
8
  from sklearn.model_selection import train_test_split
9
  from sklearn.ensemble import RandomForestClassifier
10
+ import git
11
+ import spacy
12
+ from spacy.lang.en import English
13
+ import boto3
14
+ import unittest
 
 
 
 
 
 
 
 
 
 
15
 
16
  # Configure the Gemini API
17
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
18
 
19
  # Create the model with optimized parameters and enhanced system instructions
20
  generation_config = {
21
+ "temperature": 0.6, # Lower temperature for more deterministic responses
22
+ "top_p": 0.8, # Adjusted for better diversity
23
+ "top_k": 30, # Increased for more diverse tokens
24
+ "max_output_tokens": 16384, # Increased for longer responses
25
  }
26
 
27
  model = genai.GenerativeModel(
28
  model_name="gemini-1.5-pro",
29
  generation_config=generation_config,
30
  system_instruction="""
31
+ You are Ath, a highly knowledgeable code assistant. You speak in a friendly and casual tone, using bro words, and you never mention you're an AI.
32
+ Your responses should contain optimized, secure, and high-quality code only, without explanations. You are designed to provide accurate, efficient, and cutting-edge code solutions.
33
  """
34
  )
35
  chat_session = model.start_chat(history=[])
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def generate_response(user_input):
38
+ """Generate a response from the AI model."""
39
  try:
40
  response = chat_session.send_message(user_input)
41
  return response.text
42
  except Exception as e:
43
+ return f"Error: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def optimize_code(code):
46
+ """Optimize the generated code using static analysis tools."""
47
+ with open("temp_code.py", "w") as file:
48
+ file.write(code)
49
+ result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
50
+ os.remove("temp_code.py")
51
+ return code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ def fetch_from_github(query):
54
+ """Fetch code snippets from GitHub."""
55
+ # Placeholder for fetching code snippets from GitHub
56
+ return ""
57
+
58
+ def interact_with_api(api_url):
59
+ """Interact with external APIs."""
60
+ response = requests.get(api_url)
61
+ return response.json()
62
+
63
+ def train_ml_model(code_data):
64
+ """Train a machine learning model to predict code improvements."""
65
+ df = pd.DataFrame(code_data)
66
+ X = df.drop('target', axis=1)
67
+ y = df['target']
68
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
69
+ model = RandomForestClassifier()
70
+ model.fit(X_train, y_train)
71
+ return model
72
+
73
+ def handle_error(error):
74
+ """Handle errors and log them."""
75
+ st.error(f"An error occurred: {error}")
76
+
77
+ def initialize_git_repo(repo_path):
78
+ """Initialize or check the existence of a Git repository."""
79
+ if not os.path.exists(repo_path):
80
+ os.makedirs(repo_path)
81
+ if not os.path.exists(os.path.join(repo_path, '.git')):
82
+ repo = git.Repo.init(repo_path)
83
  else:
84
+ repo = git.Repo(repo_path)
85
+ return repo
86
+
87
+ def integrate_with_git(repo_path, code):
88
+ """Integrate the generated code with a Git repository."""
89
+ repo = initialize_git_repo(repo_path)
90
+ with open(os.path.join(repo_path, "generated_code.py"), "w") as file:
91
+ file.write(code)
92
+ repo.index.add(["generated_code.py"])
93
+ repo.index.commit("Added generated code")
94
+
95
+ def process_user_input(user_input):
96
+ """Process user input using advanced natural language processing."""
97
+ nlp = English()
98
+ doc = nlp(user_input)
99
+ return doc
100
+
101
+ def interact_with_cloud_services(service_name, action, params):
102
+ """Interact with cloud services using boto3."""
103
+ client = boto3.client(service_name)
104
+ response = getattr(client, action)(**params)
105
+ return response
106
+
107
+ def run_tests():
108
+ """Run automated tests using unittest."""
109
+ test_suite = unittest.TestLoader().discover('tests')
110
+ test_runner = unittest.TextTestRunner()
111
+ test_result = test_runner.run(test_suite)
112
+ return test_result
113
 
114
+ # Streamlit UI setup
115
+ st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="💻", layout="wide")
 
 
 
 
116
 
117
+ st.markdown("""
118
+ <style>
119
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
 
 
 
 
 
120
 
121
+ body {
122
+ font-family: 'Inter', sans-serif;
123
+ background-color: #f0f4f8;
124
+ color: #1a202c;
 
125
  }
126
+ .stApp {
127
+ max-width: 1000px;
128
+ margin: 0 auto;
129
+ padding: 2rem;
130
+ }
131
+ .main-container {
132
+ background: #ffffff;
133
+ border-radius: 16px;
134
+ padding: 2rem;
135
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
136
+ }
137
+ h1 {
138
+ font-size: 2.5rem;
139
+ font-weight: 700;
140
+ color: #2d3748;
141
+ text-align: center;
142
+ margin-bottom: 1rem;
143
+ }
144
+ .subtitle {
145
+ font-size: 1.1rem;
146
+ text-align: center;
147
+ color: #4a5568;
148
+ margin-bottom: 2rem;
149
+ }
150
+ .stTextArea textarea {
151
+ border: 2px solid #e2e8f0;
152
+ border-radius: 8px;
153
+ font-size: 1rem;
154
+ padding: 0.75rem;
155
+ transition: all 0.3s ease;
156
+ }
157
+ .stTextArea textarea:focus {
158
+ border-color: #4299e1;
159
+ box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
160
+ }
161
+ .stButton button {
162
+ background-color: #4299e1;
163
+ color: white;
164
+ border: none;
165
+ border-radius: 8px;
166
+ font-size: 1.1rem;
167
+ font-weight: 600;
168
+ padding: 0.75rem 2rem;
169
+ transition: all 0.3s ease;
170
+ width: 100%;
171
+ }
172
+ .stButton button:hover {
173
+ background-color: #3182ce;
174
+ }
175
+ .output-container {
176
+ background: #f7fafc;
177
+ border-radius: 8px;
178
+ padding: 1rem;
179
+ margin-top: 2rem;
180
+ }
181
+ .code-block {
182
+ background-color: #2d3748;
183
+ color: #e2e8f0;
184
+ font-family: 'Fira Code', monospace;
185
+ font-size: 0.9rem;
186
+ border-radius: 8px;
187
+ padding: 1rem;
188
+ margin-top: 1rem;
189
+ overflow-x: auto;
190
+ }
191
+ .stAlert {
192
+ background-color: #ebf8ff;
193
+ color: #2b6cb0;
194
+ border-radius: 8px;
195
+ border: none;
196
+ padding: 0.75rem 1rem;
197
+ }
198
+ .stSpinner {
199
+ color: #4299e1;
200
+ }
201
+ </style>
202
+ """, unsafe_allow_html=True)
203
 
204
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
205
+ st.title("💻 Sleek AI Code Assistant")
206
+ st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
207
 
208
+ prompt = st.text_area("What code can I help you with today?", height=120)
209
 
210
+ if st.button("Generate Code"):
211
  if prompt.strip() == "":
212
  st.error("Please enter a valid prompt.")
213
  else:
214
+ with st.spinner("Generating code..."):
215
+ try:
216
+ processed_input = process_user_input(prompt)
217
+ completed_text = generate_response(processed_input.text)
218
+ if "Error" in completed_text:
219
+ handle_error(completed_text)
 
 
 
 
 
220
  else:
221
+ optimized_code = optimize_code(completed_text)
222
+ st.success("Code generated and optimized successfully!")
 
223
 
224
  st.markdown('<div class="output-container">', unsafe_allow_html=True)
225
  st.markdown('<div class="code-block">', unsafe_allow_html=True)
226
  st.code(optimized_code)
227
  st.markdown('</div>', unsafe_allow_html=True)
228
+ st.markdown('</div>', unsafe_allow_html=True)
229
 
230
+ # Integrate with Git
231
+ repo_path = "./repo" # Replace with your repository path
232
+ integrate_with_git(repo_path, optimized_code)
 
 
 
 
 
 
 
 
233
 
234
+ # Run automated tests
235
+ test_result = run_tests()
236
+ if test_result.wasSuccessful():
237
+ st.success("All tests passed successfully!")
238
  else:
239
+ st.error("Some tests failed. Please check the code.")
240
+ except Exception as e:
241
+ handle_error(e)
 
 
 
 
 
 
 
 
242
 
243
  st.markdown("""
244
  <div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
245
+ Created with ❤️ by Your Sleek AI Code Assistant
246
  </div>
247
  """, unsafe_allow_html=True)
248