File size: 24,708 Bytes
f8dbf90 1b83088 98e1f97 1b83088 00814c9 4bf76df c059984 00814c9 8c39446 c059984 00814c9 d4a5735 00814c9 8c39446 90eba29 a66a809 c059984 f8dbf90 1b83088 3134b3b 1b83088 f8dbf90 c059984 f8dbf90 90eba29 f8dbf90 3134b3b c059984 1b83088 f8dbf90 cba9efc f8dbf90 c059984 00814c9 9f8e60f 00814c9 90eba29 00814c9 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 00814c9 ca9dc4d 00814c9 90eba29 00814c9 90eba29 00814c9 90eba29 00814c9 c059984 00814c9 ad8639b 00814c9 90eba29 8c39446 90eba29 8c39446 c059984 8c39446 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 d4a5735 c059984 8c39446 c059984 8c39446 c059984 a66a809 c059984 d4a5735 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 75b06d3 8c39446 c059984 d4a5735 c059984 d4a5735 c059984 d35faf8 00814c9 83ac817 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 00814c9 c059984 8c39446 c059984 00814c9 f1447e0 d35faf8 990d424 8c39446 d35faf8 75b06d3 c059984 |
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 |
import streamlit as st import google.generativeai as genai import requests import subprocess import os import pylint import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score import git import spacy from spacy.lang.en import English import boto3 import unittest import docker import sympy as sp from scipy.optimize import minimize, differential_evolution import numpy as np import matplotlib.pyplot as plt import seaborn as sns from IPython.display import display from tenacity import retry, stop_after_attempt, wait_fixed import torch import torch.nn as nn import torch.optim as optim from transformers import AutoTokenizer, AutoModel import networkx as nx from sklearn.cluster import KMeans from scipy.stats import ttest_ind from statsmodels.tsa.arima.model import ARIMA import nltk from nltk.sentiment import SentimentIntensityAnalyzer import cv2 from PIL import Image import tensorflow as tf from tensorflow.keras.applications import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions # Configure the Gemini API genai.configure(api_key=st.secrets["GOOGLE_API_KEY"]) # Create the model with optimized parameters and enhanced system instructions generation_config = { "temperature": 0.4, "top_p": 0.8, "top_k": 50, "max_output_tokens": 4096, } model = genai.GenerativeModel( model_name="gemini-1.5-pro", generation_config=generation_config, system_instruction=""" You are Ath, an ultra-advanced AI code assistant with expertise across multiple domains including machine learning, data science, web development, cloud computing, and more. Your responses should showcase cutting-edge techniques, best practices, and innovative solutions. """ ) chat_session = model.start_chat(history=[]) @retry(stop=stop_after_attempt(5), wait=wait_fixed(2)) def generate_response(user_input): try: response = chat_session.send_message(user_input) return response.text except Exception as e: return f"Error: {e}" def optimize_code(code): with open("temp_code.py", "w") as file: file.write(code) result = subprocess.run(["pylint", "temp_code.py"], capture_output=True, text=True) os.remove("temp_code.py") return code def fetch_from_github(query): # Implement GitHub API interaction here pass def interact_with_api(api_url): response = requests.get(api_url) return response.json() def train_advanced_ml_model(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) models = { 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42), 'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42) } results = {} for name, model in models.items(): model.fit(X_train, y_train) y_pred = model.predict(X_test) results[name] = { 'accuracy': accuracy_score(y_test, y_pred), 'precision': precision_score(y_test, y_pred, average='weighted'), 'recall': recall_score(y_test, y_pred, average='weighted'), 'f1': f1_score(y_test, y_pred, average='weighted') } return results def handle_error(error): st.error(f"An error occurred: {error}") # Implement advanced error logging and notification system here def initialize_git_repo(repo_path): if not os.path.exists(repo_path): os.makedirs(repo_path) if not os.path.exists(os.path.join(repo_path, '.git')): repo = git.Repo.init(repo_path) else: repo = git.Repo(repo_path) return repo def integrate_with_git(repo_path, code): repo = initialize_git_repo(repo_path) with open(os.path.join(repo_path, "generated_code.py"), "w") as file: file.write(code) repo.index.add(["generated_code.py"]) repo.index.commit("Added generated code") def process_user_input(user_input): nlp = spacy.load("en_core_web_sm") doc = nlp(user_input) return doc def interact_with_cloud_services(service_name, action, params): client = boto3.client(service_name) response = getattr(client, action)(**params) return response def run_tests(): tests_dir = os.path.join(os.getcwd(), 'tests') if not os.path.exists(tests_dir): os.makedirs(tests_dir) init_file = os.path.join(tests_dir, '__init__.py') if not os.path.exists(init_file): with open(init_file, 'w') as f: f.write('') test_suite = unittest.TestLoader().discover(tests_dir) test_runner = unittest.TextTestRunner() test_result = test_runner.run(test_suite) return test_result def execute_code_in_docker(code): client = docker.from_env() try: container = client.containers.run( image="python:3.9", command=f"python -c '{code}'", detach=True, remove=True ) result = container.wait() logs = container.logs().decode('utf-8') return logs, result['StatusCode'] except Exception as e: return f"Error: {e}", 1 def solve_complex_equation(equation): x, y, z = sp.symbols('x y z') eq = sp.Eq(eval(equation)) solution = sp.solve(eq) return solution def advanced_optimization(function, bounds): result = differential_evolution(lambda x: eval(function), bounds) return result.x, result.fun def visualize_complex_data(data): df = pd.DataFrame(data) fig, axs = plt.subplots(2, 2, figsize=(16, 12)) sns.heatmap(df.corr(), annot=True, cmap='coolwarm', ax=axs[0, 0]) axs[0, 0].set_title('Correlation Heatmap') sns.pairplot(df, diag_kind='kde', ax=axs[0, 1]) axs[0, 1].set_title('Pairplot') df.plot(kind='box', ax=axs[1, 0]) axs[1, 0].set_title('Box Plot') sns.violinplot(data=df, ax=axs[1, 1]) axs[1, 1].set_title('Violin Plot') plt.tight_layout() return fig def analyze_complex_data(data): df = pd.DataFrame(data) summary = df.describe() correlation = df.corr() skewness = df.skew() kurtosis = df.kurtosis() return { 'summary': summary, 'correlation': correlation, 'skewness': skewness, 'kurtosis': kurtosis } def train_deep_learning_model(X, y): class DeepNN(nn.Module): def __init__(self, input_size): super(DeepNN, self).__init__() self.fc1 = nn.Linear(input_size, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, 1) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = torch.sigmoid(self.fc3(x)) return x X_tensor = torch.FloatTensor(X.values) y_tensor = torch.FloatTensor(y.values) model = DeepNN(X.shape[1]) criterion = nn.BCELoss() optimizer = optim.Adam(model.parameters()) epochs = 100 for epoch in range(epochs): optimizer.zero_grad() outputs = model(X_tensor) loss = criterion(outputs, y_tensor.unsqueeze(1)) loss.backward() optimizer.step() return model def perform_nlp_analysis(text): nlp = spacy.load("en_core_web_sm") doc = nlp(text) entities = [(ent.text, ent.label_) for ent in doc.ents] tokens = [token.text for token in doc] pos_tags = [(token.text, token.pos_) for token in doc] sia = SentimentIntensityAnalyzer() sentiment = sia.polarity_scores(text) return { 'entities': entities, 'tokens': tokens, 'pos_tags': pos_tags, 'sentiment': sentiment } def perform_image_analysis(image_path): img = cv2.imread(image_path) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Perform object detection model = ResNet50(weights='imagenet') img_resized = cv2.resize(img_rgb, (224, 224)) img_array = image.img_to_array(img_resized) img_array = np.expand_dims(img_array, axis=0) img_array = preprocess_input(img_array) predictions = model.predict(img_array) decoded_predictions = decode_predictions(predictions, top=3)[0] # Perform edge detection edges = cv2.Canny(img, 100, 200) return { 'predictions': decoded_predictions, 'edges': edges } def perform_time_series_analysis(data): df = pd.DataFrame(data) model = ARIMA(df, order=(1, 1, 1)) results = model.fit() forecast = results.forecast(steps=5) return { 'model_summary': results.summary(), 'forecast': forecast } def perform_graph_analysis(nodes, edges): G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) centrality = nx.degree_centrality(G) clustering = nx.clustering(G) shortest_paths = dict(nx.all_pairs_shortest_path_length(G)) return { 'centrality': centrality, 'clustering': clustering, 'shortest_paths': shortest_paths } # Streamlit UI setup st.set_page_config(page_title="Ultra AI Code Assistant", page_icon="π", layout="wide") # ... (Keep the existing CSS styles) st.markdown('<div class="main-container">', unsafe_allow_html=True) st.title("π Ultra AI Code Assistant") st.markdown('<p class="subtitle">Powered by Advanced AI and Domain Expertise</p>', unsafe_allow_html=True) task_type = st.selectbox("Select Task Type", [ "Code Generation", "Machine Learning", "Data Analysis", "Natural Language Processing", "Image Analysis", "Time Series Analysis", "Graph Analysis" ]) prompt = st.text_area("Enter your task description or code:", height=120) if st.button("Execute Task"): if prompt.strip() == "": st.error("Please enter a valid prompt.") else: with st.spinner("Processing your request..."): try: if task_type == "Code Generation": processed_input = process_user_input(prompt) completed_text = generate_response(processed_input.text) if "Error" in completed_text: handle_error(completed_text) else: optimized_code = optimize_code(completed_text) st.success("Code generated and optimized successfully!") st.markdown('<div class="output-container">', unsafe_allow_html=True) st.markdown('<div class="code-block">', unsafe_allow_html=True) st.code(optimized_code) st.markdown('</div>', unsafe_allow_html=True) st.markdown('</div>', unsafe_allow_html=True) repo_path = "./repo" integrate_with_git(repo_path, optimized_code) test_result = run_tests() if test_result.wasSuccessful(): st.success("All tests passed successfully!") else: st.error("Some tests failed. Please check the code.") execution_result, status_code = execute_code_in_docker(optimized_code) if status_code == 0: st.success("Code executed successfully in Docker!") st.text(execution_result) else: st.error(f"Code execution failed: {execution_result}") elif task_type == "Machine Learning": # For demonstration, we'll use a sample dataset from sklearn.datasets import make_classification X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42) results = train_advanced_ml_model(X, y) st.write("Machine Learning Model Performance:") st.json(results) st.write("Deep Learning Model:") deep_model = train_deep_learning_model(pd.DataFrame(X), pd.Series(y)) st.write(deep_model) elif task_type == "Data Analysis": # For demonstration, we'll use a sample dataset data = pd.DataFrame(np.random.randn(100, 5), columns=['A', 'B', 'C', 'D', 'E']) analysis_results = analyze_complex_data(data) st.write("Data Analysis Results:") st.write(analysis_results['summary']) st.write("Correlation Matrix:") st.write(analysis_results['correlation']) fig = visualize_complex_data(data) st.pyplot(fig) elif task_type == "Natural Language Processing": nlp_results = perform_nlp_analysis(prompt) st.write("NLP Analysis Results:") st.json(nlp_results) elif task_type == "Image Analysis": uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"]) if uploaded_file is not None: image = Image.open(uploaded_file) st.image(image, caption='Uploaded Image', use_column_width=True) # Save the uploaded image temporarily with open("temp_image.jpg", "wb") as f: f.write(uploaded_file.getbuffer()) analysis_results = perform_image_analysis("temp_image.jpg") st.write("Image Analysis Results:") st.write("Top 3 predictions:") for i, (imagenet_id, label, score) in enumerate(analysis_results['predictions']): st.write(f"{i + 1}: {label} ({score:.2f})") st.write("Edge Detection:") st.image(analysis_results['edges'], caption='Edge Detection', use_column_width=True) # Remove the temporary image file os.remove("temp_image.jpg") elif task_type == "Time Series Analysis": # For demonstration, we'll use a sample time series dataset dates = pd.date_range(start='1/1/2020', end='1/1/2021', freq='D') values = np.random.randn(len(dates)).cumsum() ts_data = pd.Series(values, index=dates) st.line_chart(ts_data) analysis_results = perform_time_series_analysis(ts_data) st.write("Time Series Analysis Results:") st.write(analysis_results['model_summary']) st.write("Forecast for the next 5 periods:") st.write(analysis_results['forecast']) elif task_type == "Graph Analysis": # For demonstration, we'll use a sample graph nodes = range(1, 11) edges = [(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (4, 8), (5, 9), (6, 10)] analysis_results = perform_graph_analysis(nodes, edges) st.write("Graph Analysis Results:") st.write("Centrality:") st.json(analysis_results['centrality']) st.write("Clustering Coefficient:") st.json(analysis_results['clustering']) # Visualize the graph G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) fig, ax = plt.subplots(figsize=(10, 8)) nx.draw(G, with_labels=True, node_color='lightblue', node_size=500, font_size=16, font_weight='bold', ax=ax) st.pyplot(fig) except Exception as e: handle_error(e) st.markdown(""" <div style='text-align: center; margin-top: 2rem; color: #4a5568;'> Created with β€οΈ by Your Ultra AI Code Assistant </div> """, unsafe_allow_html=True) st.markdown('</div>', unsafe_allow_html=True) # Additional helper functions def explain_code(code): """Generate an explanation for the given code using NLP techniques.""" explanation = generate_response(f"Explain the following code:\n\n{code}") return explanation def generate_unit_tests(code): """Generate unit tests for the given code.""" unit_tests = generate_response(f"Generate unit tests for the following code:\n\n{code}") return unit_tests def suggest_optimizations(code): """Suggest optimizations for the given code.""" optimizations = generate_response(f"Suggest optimizations for the following code:\n\n{code}") return optimizations def generate_documentation(code): """Generate documentation for the given code.""" documentation = generate_response(f"Generate documentation for the following code:\n\n{code}") return documentation # Add these new functions to the Streamlit UI if task_type == "Code Generation": st.sidebar.header("Code Analysis Tools") if st.sidebar.button("Explain Code"): explanation = explain_code(optimized_code) st.sidebar.subheader("Code Explanation") st.sidebar.write(explanation) if st.sidebar.button("Generate Unit Tests"): unit_tests = generate_unit_tests(optimized_code) st.sidebar.subheader("Generated Unit Tests") st.sidebar.code(unit_tests) if st.sidebar.button("Suggest Optimizations"): optimizations = suggest_optimizations(optimized_code) st.sidebar.subheader("Suggested Optimizations") st.sidebar.write(optimizations) if st.sidebar.button("Generate Documentation"): documentation = generate_documentation(optimized_code) st.sidebar.subheader("Generated Documentation") st.sidebar.write(documentation) # Add more advanced features def perform_security_analysis(code): """Perform a basic security analysis on the given code.""" security_analysis = generate_response(f"Perform a security analysis on the following code and suggest improvements:\n\n{code}") return security_analysis def generate_api_documentation(code): """Generate API documentation for the given code.""" api_docs = generate_response(f"Generate API documentation for the following code:\n\n{code}") return api_docs def suggest_design_patterns(code): """Suggest appropriate design patterns for the given code.""" design_patterns = generate_response(f"Suggest appropriate design patterns for the following code:\n\n{code}") return design_patterns # Add these new functions to the Streamlit UI if task_type == "Code Generation": st.sidebar.header("Advanced Code Analysis") if st.sidebar.button("Security Analysis"): security_analysis = perform_security_analysis(optimized_code) st.sidebar.subheader("Security Analysis") st.sidebar.write(security_analysis) if st.sidebar.button("Generate API Documentation"): api_docs = generate_api_documentation(optimized_code) st.sidebar.subheader("API Documentation") st.sidebar.write(api_docs) if st.sidebar.button("Suggest Design Patterns"): design_patterns = suggest_design_patterns(optimized_code) st.sidebar.subheader("Suggested Design Patterns") st.sidebar.write(design_patterns) # Add a feature to generate a complete project structure def generate_project_structure(project_description): """Generate a complete project structure based on the given description.""" project_structure = generate_response(f"Generate a complete project structure for the following project description:\n\n{project_description}") return project_structure # Add this new function to the Streamlit UI if st.sidebar.button("Generate Project Structure"): project_description = st.sidebar.text_area("Enter project description:") if project_description: project_structure = generate_project_structure(project_description) st.sidebar.subheader("Generated Project Structure") st.sidebar.code(project_structure) # Add a feature to suggest relevant libraries and frameworks def suggest_libraries(code): """Suggest relevant libraries and frameworks for the given code.""" suggestions = generate_response(f"Suggest relevant libraries and frameworks for the following code:\n\n{code}") return suggestions # Add this new function to the Streamlit UI if task_type == "Code Generation": if st.sidebar.button("Suggest Libraries"): library_suggestions = suggest_libraries(optimized_code) st.sidebar.subheader("Suggested Libraries and Frameworks") st.sidebar.write(library_suggestions) # Add a feature to generate code in multiple programming languages def translate_code(code, target_language): """Translate the given code to the specified target language.""" translated_code = generate_response(f"Translate the following code to {target_language}:\n\n{code}") return translated_code # Add this new function to the Streamlit UI if task_type == "Code Generation": target_language = st.sidebar.selectbox("Select target language for translation", ["Python", "JavaScript", "Java", "C++", "Go"]) if st.sidebar.button("Translate Code"): translated_code = translate_code(optimized_code, target_language) st.sidebar.subheader(f"Translated Code ({target_language})") st.sidebar.code(translated_code) # Add a feature to generate a README file for the project def generate_readme(project_description, code): """Generate a README file for the project based on the description and code.""" readme_content = generate_response(f"Generate a README.md file for the following project:\n\nDescription: {project_description}\n\nCode:\n{code}") return readme_content # Add this new function to the Streamlit UI if task_type == "Code Generation": if st.sidebar.button("Generate README"): project_description = st.sidebar.text_area("Enter project description:") if project_description: readme_content = generate_readme(project_description, optimized_code) st.sidebar.subheader("Generated README.md") st.sidebar.markdown(readme_content) # Add a feature to suggest code refactoring def suggest_refactoring(code): """Suggest code refactoring improvements for the given code.""" refactoring_suggestions = generate_response(f"Suggest code refactoring improvements for the following code:\n\n{code}") return refactoring_suggestions # Add this new function to the Streamlit UI if task_type == "Code Generation": if st.sidebar.button("Suggest Refactoring"): refactoring_suggestions = suggest_refactoring(optimized_code) st.sidebar.subheader("Refactoring Suggestions") st.sidebar.write(refactoring_suggestions) # Add a feature to generate sample test data def generate_test_data(code): """Generate sample test data for the given code.""" test_data = generate_response(f"Generate sample test data for the following code:\n\n{code}") return test_data # Add this new function to the Streamlit UI if task_type == "Code Generation": if st.sidebar.button("Generate Test Data"): test_data = generate_test_data(optimized_code) st.sidebar.subheader("Generated Test Data") st.sidebar.code(test_data) # Main execution if __name__ == "__main__": st.sidebar.header("About") st.sidebar.info("This Ultra AI Code Assistant is powered by advanced AI models and incorporates expertise across multiple domains including software development, machine learning, data analysis, and more.") st.sidebar.header("Feedback") feedback = st.sidebar.text_area("Please provide any feedback or suggestions:") if st.sidebar.button("Submit Feedback"): # Here you would typically send this feedback to a database or email st.sidebar.success("Thank you for your feedback!") |