Artificial-superintelligence commited on
Commit
8903fd7
Β·
verified Β·
1 Parent(s): 3fb4935

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -111
app.py CHANGED
@@ -5,30 +5,59 @@ 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
 
11
  # Configure the Gemini API
12
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
13
 
14
  # Create the model with optimized parameters and enhanced system instructions
15
  generation_config = {
16
- "temperature": 0.6, # Lower temperature for more deterministic responses
17
- "top_p": 0.8, # Adjusted for better diversity
18
- "top_k": 30, # Increased for more diverse tokens
19
- "max_output_tokens": 16384, # Increased for longer responses
20
  }
21
 
22
  model = genai.GenerativeModel(
23
  model_name="gemini-1.5-pro",
24
  generation_config=generation_config,
25
  system_instruction="""
26
- 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.
27
- 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.
28
  """
29
  )
30
  chat_session = model.start_chat(history=[])
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def generate_response(user_input):
33
  try:
34
  response = chat_session.send_message(user_input)
@@ -37,151 +66,129 @@ def generate_response(user_input):
37
  return f"Error: {e}"
38
 
39
  def optimize_code(code):
40
- # Placeholder for advanced code optimization logic
41
- # This could involve using external tools or libraries for static analysis and optimization
 
 
 
 
 
 
 
 
 
 
42
  with open("temp_code.py", "w") as file:
43
- file.write(code)
44
  result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
45
  os.remove("temp_code.py")
46
- return code
 
47
 
48
  def fetch_from_github(query):
49
- # Placeholder for fetching code snippets from GitHub
50
- # This could involve using the GitHub API to search for relevant code
51
- return ""
 
 
52
 
53
  def interact_with_api(api_url):
54
- # Placeholder for interacting with external APIs
55
  response = requests.get(api_url)
56
  return response.json()
57
 
58
  def train_ml_model(code_data):
59
- # Placeholder for training a machine learning model to predict code improvements
60
  df = pd.DataFrame(code_data)
61
  X = df.drop('target', axis=1)
62
  y = df['target']
63
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
64
- model = RandomForestClassifier()
65
  model.fit(X_train, y_train)
66
  return model
67
 
68
- # Streamlit UI setup
69
- st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="πŸ’»", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- st.markdown("""
72
- <style>
73
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
74
 
75
- body {
76
- font-family: 'Inter', sans-serif;
77
- background-color: #f0f4f8;
78
- color: #1a202c;
79
- }
80
- .stApp {
81
- max-width: 1000px;
82
- margin: 0 auto;
83
- padding: 2rem;
84
- }
85
- .main-container {
86
- background: #ffffff;
87
- border-radius: 16px;
88
- padding: 2rem;
89
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
90
- }
91
- h1 {
92
- font-size: 2.5rem;
93
- font-weight: 700;
94
- color: #2d3748;
95
- text-align: center;
96
- margin-bottom: 1rem;
97
- }
98
- .subtitle {
99
- font-size: 1.1rem;
100
- text-align: center;
101
- color: #4a5568;
102
- margin-bottom: 2rem;
103
- }
104
- .stTextArea textarea {
105
- border: 2px solid #e2e8f0;
106
- border-radius: 8px;
107
- font-size: 1rem;
108
- padding: 0.75rem;
109
- transition: all 0.3s ease;
110
- }
111
- .stTextArea textarea:focus {
112
- border-color: #4299e1;
113
- box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
114
- }
115
- .stButton button {
116
- background-color: #4299e1;
117
- color: white;
118
- border: none;
119
- border-radius: 8px;
120
- font-size: 1.1rem;
121
- font-weight: 600;
122
- padding: 0.75rem 2rem;
123
- transition: all 0.3s ease;
124
- width: 100%;
125
- }
126
- .stButton button:hover {
127
- background-color: #3182ce;
128
- }
129
- .output-container {
130
- background: #f7fafc;
131
- border-radius: 8px;
132
- padding: 1rem;
133
- margin-top: 2rem;
134
- }
135
- .code-block {
136
- background-color: #2d3748;
137
- color: #e2e8f0;
138
- font-family: 'Fira Code', monospace;
139
- font-size: 0.9rem;
140
- border-radius: 8px;
141
- padding: 1rem;
142
- margin-top: 1rem;
143
- overflow-x: auto;
144
- }
145
- .stAlert {
146
- background-color: #ebf8ff;
147
- color: #2b6cb0;
148
- border-radius: 8px;
149
- border: none;
150
- padding: 0.75rem 1rem;
151
- }
152
- .stSpinner {
153
- color: #4299e1;
154
- }
155
- </style>
156
- """, unsafe_allow_html=True)
157
 
158
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
159
- st.title("πŸ’» Sleek AI Code Assistant")
160
- st.markdown('<p class="subtitle">Powered by Google Gemini</p>', unsafe_allow_html=True)
161
 
162
- prompt = st.text_area("What code can I help you with today?", height=120)
163
 
164
- if st.button("Generate Code"):
165
  if prompt.strip() == "":
166
  st.error("Please enter a valid prompt.")
167
  else:
168
- with st.spinner("Generating code..."):
169
  completed_text = generate_response(prompt)
170
  if "Error" in completed_text:
171
  st.error(completed_text)
172
  else:
173
- optimized_code = optimize_code(completed_text)
174
- st.success("Code generated and optimized successfully!")
 
 
175
 
176
  st.markdown('<div class="output-container">', unsafe_allow_html=True)
177
  st.markdown('<div class="code-block">', unsafe_allow_html=True)
178
  st.code(optimized_code)
179
  st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
180
  st.markdown('</div>', unsafe_allow_html=True)
181
 
182
  st.markdown("""
183
  <div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
184
- Created with ❀️ by Your Sleek AI Code Assistant
185
  </div>
186
  """, unsafe_allow_html=True)
187
 
 
5
  import os
6
  import pylint
7
  import pandas as pd
8
+ import numpy as np
9
  from sklearn.model_selection import train_test_split
10
  from sklearn.ensemble import RandomForestClassifier
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.optim as optim
14
+ from transformers import AutoTokenizer, AutoModel
15
+ import ast
16
+ import networkx as nx
17
+ import matplotlib.pyplot as plt
18
 
19
  # Configure the Gemini API
20
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
21
 
22
  # Create the model with optimized parameters and enhanced system instructions
23
  generation_config = {
24
+ "temperature": 0.6,
25
+ "top_p": 0.8,
26
+ "top_k": 30,
27
+ "max_output_tokens": 16384,
28
  }
29
 
30
  model = genai.GenerativeModel(
31
  model_name="gemini-1.5-pro",
32
  generation_config=generation_config,
33
  system_instruction="""
34
+ You are Ath, a highly advanced code assistant with deep knowledge in AI, machine learning, and software engineering. You provide cutting-edge, optimized, and secure code solutions. Speak casually and use tech jargon when appropriate.
 
35
  """
36
  )
37
  chat_session = model.start_chat(history=[])
38
 
39
+ # Load pre-trained BERT model for code understanding
40
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
41
+ codebert_model = AutoModel.from_pretrained("microsoft/codebert-base")
42
+
43
+ class CodeImprovement(nn.Module):
44
+ def __init__(self, input_dim):
45
+ super(CodeImprovement, self).__init__()
46
+ self.fc1 = nn.Linear(input_dim, 512)
47
+ self.fc2 = nn.Linear(512, 256)
48
+ self.fc3 = nn.Linear(256, 128)
49
+ self.fc4 = nn.Linear(128, 2) # Binary classification: needs improvement or not
50
+
51
+ def forward(self, x):
52
+ x = torch.relu(self.fc1(x))
53
+ x = torch.relu(self.fc2(x))
54
+ x = torch.relu(self.fc3(x))
55
+ return torch.sigmoid(self.fc4(x))
56
+
57
+ code_improvement_model = CodeImprovement(768) # 768 is BERT's output dimension
58
+ optimizer = optim.Adam(code_improvement_model.parameters())
59
+ criterion = nn.BCELoss()
60
+
61
  def generate_response(user_input):
62
  try:
63
  response = chat_session.send_message(user_input)
 
66
  return f"Error: {e}"
67
 
68
  def optimize_code(code):
69
+ # Use abstract syntax tree for advanced code analysis
70
+ tree = ast.parse(code)
71
+ analyzer = CodeAnalyzer()
72
+ analyzer.visit(tree)
73
+
74
+ # Apply code transformations based on analysis
75
+ transformer = CodeTransformer(analyzer.get_optimizations())
76
+ optimized_tree = transformer.visit(tree)
77
+
78
+ optimized_code = ast.unparse(optimized_tree)
79
+
80
+ # Run pylint for additional suggestions
81
  with open("temp_code.py", "w") as file:
82
+ file.write(optimized_code)
83
  result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True)
84
  os.remove("temp_code.py")
85
+
86
+ return optimized_code, result.stdout
87
 
88
  def fetch_from_github(query):
89
+ headers = {"Authorization": f"token {st.secrets['GITHUB_TOKEN']}"}
90
+ response = requests.get(f"https://api.github.com/search/code?q={query}", headers=headers)
91
+ if response.status_code == 200:
92
+ return response.json()['items'][:5] # Return top 5 results
93
+ return []
94
 
95
  def interact_with_api(api_url):
 
96
  response = requests.get(api_url)
97
  return response.json()
98
 
99
  def train_ml_model(code_data):
 
100
  df = pd.DataFrame(code_data)
101
  X = df.drop('target', axis=1)
102
  y = df['target']
103
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
104
+ model = RandomForestClassifier(n_estimators=100, max_depth=10)
105
  model.fit(X_train, y_train)
106
  return model
107
 
108
+ def analyze_code_quality(code):
109
+ # Tokenize and encode the code
110
+ inputs = tokenizer(code, return_tensors="pt", truncation=True, max_length=512, padding="max_length")
111
+
112
+ # Get BERT embeddings
113
+ with torch.no_grad():
114
+ outputs = codebert_model(**inputs)
115
+
116
+ # Use the [CLS] token embedding for classification
117
+ cls_embedding = outputs.last_hidden_state[:, 0, :]
118
+
119
+ # Pass through our code improvement model
120
+ prediction = code_improvement_model(cls_embedding)
121
+
122
+ return prediction.item() # Return the probability of needing improvement
123
 
124
+ def visualize_code_structure(code):
125
+ tree = ast.parse(code)
126
+ graph = nx.DiGraph()
127
 
128
+ def add_nodes_edges(node, parent=None):
129
+ node_id = id(node)
130
+ graph.add_node(node_id, label=type(node).__name__)
131
+ if parent:
132
+ graph.add_edge(id(parent), node_id)
133
+ for child in ast.iter_child_nodes(node):
134
+ add_nodes_edges(child, node)
135
+
136
+ add_nodes_edges(tree)
137
+
138
+ plt.figure(figsize=(12, 8))
139
+ pos = nx.spring_layout(graph)
140
+ nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=1000, font_size=8, font_weight='bold')
141
+ labels = nx.get_node_attributes(graph, 'label')
142
+ nx.draw_networkx_labels(graph, pos, labels, font_size=6)
143
+
144
+ return plt
145
+
146
+ # Streamlit UI setup
147
+ st.set_page_config(page_title="Advanced AI Code Assistant", page_icon="πŸš€", layout="wide")
148
+
149
+ # ... (keep the existing CSS styles) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
152
+ st.title("πŸš€ Advanced AI Code Assistant")
153
+ st.markdown('<p class="subtitle">Powered by Google Gemini & Deep Learning</p>', unsafe_allow_html=True)
154
 
155
+ prompt = st.text_area("What advanced code task can I help you with today?", height=120)
156
 
157
+ if st.button("Generate Advanced Code"):
158
  if prompt.strip() == "":
159
  st.error("Please enter a valid prompt.")
160
  else:
161
+ with st.spinner("Generating and analyzing code..."):
162
  completed_text = generate_response(prompt)
163
  if "Error" in completed_text:
164
  st.error(completed_text)
165
  else:
166
+ optimized_code, lint_results = optimize_code(completed_text)
167
+ quality_score = analyze_code_quality(optimized_code)
168
+
169
+ st.success(f"Code generated and optimized successfully! Quality Score: {quality_score:.2f}")
170
 
171
  st.markdown('<div class="output-container">', unsafe_allow_html=True)
172
  st.markdown('<div class="code-block">', unsafe_allow_html=True)
173
  st.code(optimized_code)
174
  st.markdown('</div>', unsafe_allow_html=True)
175
+
176
+ with st.expander("View Code Structure Visualization"):
177
+ st.pyplot(visualize_code_structure(optimized_code))
178
+
179
+ with st.expander("View Lint Results"):
180
+ st.text(lint_results)
181
+
182
+ with st.expander("Fetch Similar Code from GitHub"):
183
+ github_results = fetch_from_github(prompt)
184
+ for item in github_results:
185
+ st.markdown(f"[{item['name']}]({item['html_url']})")
186
+
187
  st.markdown('</div>', unsafe_allow_html=True)
188
 
189
  st.markdown("""
190
  <div style='text-align: center; margin-top: 2rem; color: #4a5568;'>
191
+ Crafted with πŸš€ by Your Advanced AI Code Assistant
192
  </div>
193
  """, unsafe_allow_html=True)
194