Artificial-superintelligence commited on
Commit
ca9dc4d
Β·
verified Β·
1 Parent(s): 0b8a3aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -180
app.py CHANGED
@@ -3,236 +3,318 @@ import google.generativeai as genai
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
  try:
39
  response = chat_session.send_message(user_input)
40
  return response.text
41
  except Exception as e:
42
- return f"Error: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def optimize_code(code):
45
- # Placeholder for advanced code optimization logic
46
- # This could involve using external tools or libraries for static analysis and optimization
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
- # Placeholder for fetching code snippets from GitHub
55
- # This could involve using the GitHub API to search for relevant code
56
- return ""
57
-
58
- def interact_with_api(api_url):
59
- # Placeholder for interacting with external APIs
60
- response = requests.get(api_url)
61
- return response.json()
62
-
63
- def train_ml_model(code_data):
64
- # Placeholder for training 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
- # Placeholder for advanced error handling and logging
75
- st.error(f"An error occurred: {error}")
76
-
77
- def integrate_with_git(repo_path, code):
78
- # Placeholder for integrating with version control systems like Git
79
- repo = git.Repo(repo_path)
80
- with open(os.path.join(repo_path, "generated_code.py"), "w") as file:
81
- file.write(code)
82
- repo.index.add(["generated_code.py"])
83
- repo.index.commit("Added generated code")
84
-
85
- def process_user_input(user_input):
86
- # Placeholder for advanced natural language processing
87
- nlp = English()
88
- doc = nlp(user_input)
89
- return doc
90
-
91
- def interact_with_cloud_services(service_name, action, params):
92
- # Placeholder for interacting with cloud services
93
- client = boto3.client(service_name)
94
- response = getattr(client, action)(**params)
95
- return response
96
-
97
- def run_tests():
98
- # Placeholder for automated testing
99
- test_suite = unittest.TestLoader().discover('tests')
100
- test_runner = unittest.TextTestRunner()
101
- test_result = test_runner.run(test_suite)
102
- return test_result
103
 
104
- # Streamlit UI setup
105
- st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="πŸ’»", layout="wide")
 
 
106
 
107
- st.markdown("""
108
- <style>
109
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- body {
112
- font-family: 'Inter', sans-serif;
113
- background-color: #f0f4f8;
114
- color: #1a202c;
115
- }
116
- .stApp {
117
- max-width: 1000px;
118
- margin: 0 auto;
119
- padding: 2rem;
120
- }
121
- .main-container {
122
- background: #ffffff;
123
- border-radius: 16px;
124
- padding: 2rem;
125
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
126
- }
127
- h1 {
128
- font-size: 2.5rem;
129
- font-weight: 700;
130
- color: #2d3748;
131
- text-align: center;
132
- margin-bottom: 1rem;
133
- }
134
- .subtitle {
135
- font-size: 1.1rem;
136
- text-align: center;
137
- color: #4a5568;
138
- margin-bottom: 2rem;
139
- }
140
- .stTextArea textarea {
141
- border: 2px solid #e2e8f0;
142
- border-radius: 8px;
143
- font-size: 1rem;
144
- padding: 0.75rem;
145
- transition: all 0.3s ease;
146
- }
147
- .stTextArea textarea:focus {
148
- border-color: #4299e1;
149
- box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
150
- }
151
- .stButton button {
152
- background-color: #4299e1;
153
- color: white;
154
- border: none;
155
- border-radius: 8px;
156
- font-size: 1.1rem;
157
- font-weight: 600;
158
- padding: 0.75rem 2rem;
159
- transition: all 0.3s ease;
160
- width: 100%;
161
- }
162
- .stButton button:hover {
163
- background-color: #3182ce;
164
- }
165
- .output-container {
166
- background: #f7fafc;
167
- border-radius: 8px;
168
- padding: 1rem;
169
- margin-top: 2rem;
170
- }
171
- .code-block {
172
- background-color: #2d3748;
173
- color: #e2e8f0;
174
- font-family: 'Fira Code', monospace;
175
- font-size: 0.9rem;
176
- border-radius: 8px;
177
- padding: 1rem;
178
- margin-top: 1rem;
179
- overflow-x: auto;
180
- }
181
- .stAlert {
182
- background-color: #ebf8ff;
183
- color: #2b6cb0;
184
- border-radius: 8px;
185
- border: none;
186
- padding: 0.75rem 1rem;
187
- }
188
- .stSpinner {
189
- color: #4299e1;
190
  }
191
- </style>
192
- """, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
195
- st.title("πŸ’» Sleek AI Code Assistant")
196
- st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
197
 
198
- prompt = st.text_area("What code can I help you with today?", height=120)
199
 
200
- if st.button("Generate Code"):
201
  if prompt.strip() == "":
202
  st.error("Please enter a valid prompt.")
203
  else:
204
- with st.spinner("Generating code..."):
205
- try:
206
- processed_input = process_user_input(prompt)
207
- completed_text = generate_response(processed_input.text)
208
- if "Error" in completed_text:
209
- handle_error(completed_text)
 
 
 
 
 
210
  else:
211
- optimized_code = optimize_code(completed_text)
212
- st.success("Code generated and optimized successfully!")
 
213
 
214
  st.markdown('<div class="output-container">', unsafe_allow_html=True)
215
  st.markdown('<div class="code-block">', unsafe_allow_html=True)
216
  st.code(optimized_code)
217
  st.markdown('</div>', unsafe_allow_html=True)
218
- st.markdown('</div>', unsafe_allow_html=True)
219
 
220
- # Integrate with Git
221
- repo_path = "./repo" # Replace with your repository path
222
- integrate_with_git(repo_path, optimized_code)
 
 
 
 
 
 
 
 
223
 
224
- # Run automated tests
225
- test_result = run_tests()
226
- if test_result.wasSuccessful():
227
- st.success("All tests passed successfully!")
228
  else:
229
- st.error("Some tests failed. Please check the code.")
230
- except Exception as e:
231
- handle_error(e)
 
 
 
 
 
 
 
 
232
 
233
  st.markdown("""
234
  <div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
235
- Created with ❀️ by Your Sleek AI Code Assistant
236
  </div>
237
  """, unsafe_allow_html=True)
238
 
 
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