Xylygorithm Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, messagebox
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns


class DataAnalyzerApp:
    def __init__(self, master):
        self.master = master
        master.title("Advanced Data Insights Tool")
        master.geometry("1200x800")

        self.notebook = ttk.Notebook(master)
        self.notebook.pack(expand=True, fill="both", padx=10, pady=10)

        self.data_tab = ttk.Frame(self.notebook)
        self.analysis_tab = ttk.Frame(self.notebook)
        self.visualization_tab = ttk.Frame(self.notebook)
        self.automation_tab = ttk.Frame(self.notebook)
        self.settings_tab = ttk.Frame(self.notebook)


        self.notebook.add(self.data_tab, text="Data Import")
        self.notebook.add(self.analysis_tab, text="Data Analysis")
        self.notebook.add(self.visualization_tab, text="Visualization")
        self.notebook.add(self.automation_tab, text="Automation")
        self.notebook.add(self.settings_tab, text="Settings")


        self.create_data_tab()
        self.create_analysis_tab()
        self.create_visualization_tab()
        self.create_automation_tab()
        self.create_settings_tab()

    def create_data_tab(self):
        # Data Import Tab
        self.data_tab.columnconfigure(0, weight=1)
        self.data_tab.rowconfigure(1, weight=1)

        load_button = ttk.Button(self.data_tab, text="Load Data", command=self.load_data)
        load_button.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        self.data_display = tk.Text(self.data_tab, wrap=tk.WORD, state=tk.DISABLED)
        self.data_display.grid(row=1, column=0, sticky="nsew", padx=10, pady=10)
        self.data_scrollbar = ttk.Scrollbar(self.data_tab, orient=tk.VERTICAL, command=self.data_display.yview)
        self.data_scrollbar.grid(row=1, column=1, sticky="ns")
        self.data_display['yscrollcommand'] = self.data_scrollbar.set

    def create_analysis_tab(self):
        # Data Analysis Tab
        self.analysis_tab.columnconfigure(0, weight=1)
        self.analysis_tab.columnconfigure(1, weight=1)
        self.analysis_tab.rowconfigure(1, weight=1)

        self.analysis_options_frame = ttk.Frame(self.analysis_tab)
        self.analysis_options_frame.grid(row=0, column=0, columnspan=2, padx=10, pady=10, sticky="ew")

        self.analysis_type_label = ttk.Label(self.analysis_options_frame, text="Analysis Type:")
        self.analysis_type_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.analysis_type = tk.StringVar(value="descriptive")
        self.analysis_type_combo = ttk.Combobox(self.analysis_options_frame, textvariable=self.analysis_type, values=["descriptive", "correlation", "regression"])
        self.analysis_type_combo.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

        self.target_variable_label = ttk.Label(self.analysis_options_frame, text="Target Variable:")
        self.target_variable_label.grid(row=0, column=2, padx=5, pady=5, sticky="w")
        self.target_variable = tk.StringVar()
        self.target_variable_entry = ttk.Entry(self.analysis_options_frame, textvariable=self.target_variable)
        self.target_variable_entry.grid(row=0, column=3, padx=5, pady=5, sticky="ew")

        analyze_button = ttk.Button(self.analysis_tab, text="Run Analysis", command=self.run_analysis)
        analyze_button.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        self.analysis_output = tk.Text(self.analysis_tab, wrap=tk.WORD, state=tk.DISABLED)
        self.analysis_output.grid(row=1, column=0, columnspan=2, sticky="nsew", padx=10, pady=10)
        self.analysis_scrollbar = ttk.Scrollbar(self.analysis_tab, orient=tk.VERTICAL, command=self.analysis_output.yview)
        self.analysis_scrollbar.grid(row=1, column=2, sticky="ns")
        self.analysis_output['yscrollcommand'] = self.analysis_scrollbar.set

    def create_visualization_tab(self):
        # Visualization Tab
        self.visualization_tab.columnconfigure(0, weight=1)
        self.visualization_tab.rowconfigure(1, weight=1)

        self.visualization_options_frame = ttk.Frame(self.visualization_tab)
        self.visualization_options_frame.grid(row=0, column=0, padx=10, pady=10, sticky="ew")

        self.visualization_type_label = ttk.Label(self.visualization_options_frame, text="Visualization Type:")
        self.visualization_type_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.visualization_type = tk.StringVar(value="scatter")
        self.visualization_type_combo = ttk.Combobox(self.visualization_options_frame, textvariable=self.visualization_type, values=["scatter", "histogram", "box", "bar"])
        self.visualization_type_combo.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

        self.x_variable_label = ttk.Label(self.visualization_options_frame, text="X Variable:")
        self.x_variable_label.grid(row=0, column=2, padx=5, pady=5, sticky="w")
        self.x_variable = tk.StringVar()
        self.x_variable_entry = ttk.Entry(self.visualization_options_frame, textvariable=self.x_variable)
        self.x_variable_entry.grid(row=0, column=3, padx=5, pady=5, sticky="ew")

        self.y_variable_label = ttk.Label(self.visualization_options_frame, text="Y Variable:")
        self.y_variable_label.grid(row=0, column=4, padx=5, pady=5, sticky="w")
        self.y_variable = tk.StringVar()
        self.y_variable_entry = ttk.Entry(self.visualization_options_frame, textvariable=self.y_variable)
        self.y_variable_entry.grid(row=0, column=5, padx=5, pady=5, sticky="ew")

        plot_button = ttk.Button(self.visualization_tab, text="Create Plot", command=self.create_plot)
        plot_button.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        self.plot_frame = tk.Frame(self.visualization_tab)
        self.plot_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=10)

    def create_automation_tab(self):
        # Automation Tab (Example: Simple Script Runner)
        self.automation_tab.columnconfigure(0, weight=1)
        self.automation_tab.rowconfigure(1, weight=1)

        self.script_label = ttk.Label(self.automation_tab, text="Python Script:")
        self.script_label.grid(row=0, column=0, padx=10, pady=5, sticky="nw")

        self.script_text = tk.Text(self.automation_tab, wrap=tk.WORD, height=10)
        self.script_text.grid(row=1, column=0, sticky="nsew", padx=10, pady=5)

        run_script_button = ttk.Button(self.automation_tab, text="Run Script", command=self.run_script)
        run_script_button.grid(row=2, column=0, padx=10, pady=5, sticky="w")

        self.script_output = tk.Text(self.automation_tab, wrap=tk.WORD, state=tk.DISABLED)
        self.script_output.grid(row=3, column=0, sticky="nsew", padx=10, pady=5)
        self.script_scrollbar = ttk.Scrollbar(self.automation_tab, orient=tk.VERTICAL, command=self.script_output.yview)
        self.script_scrollbar.grid(row=3, column=1, sticky="ns")
        self.script_output['yscrollcommand'] = self.script_scrollbar.set

    def create_settings_tab(self):
        # Settings Tab (Example: Placeholder)
        settings_label = ttk.Label(self.settings_tab, text="Settings and Preferences will be added here.")
        settings_label.pack(padx=20, pady=20)

    def load_data(self):
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv"), ("Excel Files", "*.xlsx")])
        if file_path:
            try:
                if file_path.endswith(".csv"):
                    self.df = pd.read_csv(file_path)
                elif file_path.endswith(".xlsx"):
                    self.df = pd.read_excel(file_path)
                else:
                    messagebox.showerror("Error", "Unsupported file type.")
                    return

                self.data_display.config(state=tk.NORMAL)
                self.data_display.delete("1.0", tk.END)
                self.data_display.insert(tk.END, self.df.to_string())
                self.data_display.config(state=tk.DISABLED)
                messagebox.showinfo("Success", "Data loaded successfully!")

            except Exception as e:
                messagebox.showerror("Error", f"Error loading data: {e}")

    def run_analysis(self):
      if not hasattr(self, 'df'):
          messagebox.showerror("Error", "No data loaded. Please load data first.")
          return

      analysis_type = self.analysis_type.get()
      target_variable = self.target_variable.get()

      try:
          self.analysis_output.config(state=tk.NORMAL)
          self.analysis_output.delete("1.0", tk.END)

          if analysis_type == "descriptive":
              description = self.df.describe()
              self.analysis_output.insert(tk.END, description.to_string())
          elif analysis_type == "correlation":
              correlation = self.df.corr(numeric_only=True)
              self.analysis_output.insert(tk.END, correlation.to_string())
          elif analysis_type == "regression":
              if not target_variable:
                  messagebox.showerror("Error", "Please specify a target variable for regression.")
                  return
              if target_variable not in self.df.columns:
                  messagebox.showerror("Error", f"Target variable '{target_variable}' not found in the data.")
                  return

              try:
                  from sklearn.linear_model import LinearRegression
                  from sklearn.model_selection import train_test_split

                  X = self.df.drop(target_variable, axis=1, errors='ignore')  # Drop non-existent column gracefully
                  y = self.df[target_variable]
                  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

                  model = LinearRegression()
                  model.fit(X_train, y_train)
                  score = model.score(X_test, y_test)

                  self.analysis_output.insert(tk.END, f"Regression Score (R^2): {score}\n")
                  self.analysis_output.insert(tk.END, f"Coefficients: {model.coef_}\n")
                  self.analysis_output.insert(tk.END, f"Intercept: {model.intercept_}\n")

              except ImportError:
                  messagebox.showerror("Error", "Scikit-learn (sklearn) is required for regression analysis. Please install it.")
                  return
          else:
              messagebox.showerror("Error", "Invalid analysis type.")

          self.analysis_output.config(state=tk.DISABLED)

      except Exception as e:
          messagebox.showerror("Error", f"Error during analysis: {e}")



    def create_plot(self):
        if not hasattr(self, 'df'):
            messagebox.showerror("Error", "No data loaded. Please load data first.")
            return

        visualization_type = self.visualization_type.get()
        x_variable = self.x_variable.get()
        y_variable = self.y_variable.get()

        if not x_variable or not y_variable:
            messagebox.showerror("Error", "Please specify X and Y variables.")
            return

        if x_variable not in self.df.columns or y_variable not in self.df.columns:
            messagebox.showerror("Error", "One or both specified variables not found in the data.")
            return

        try:
            plt.clf()
            if visualization_type == "scatter":
                sns.scatterplot(x=x_variable, y=y_variable, data=self.df)
                plt.title(f"Scatter Plot: {x_variable} vs {y_variable}")
                plt.xlabel(x_variable)
                plt.ylabel(y_variable)
            elif visualization_type == "histogram":
                plt.hist(self.df[x_variable])
                plt.title(f"Histogram of {x_variable}")
                plt.xlabel(x_variable)
                plt.ylabel("Frequency")
            elif visualization_type == "box":
                sns.boxplot(x=x_variable, y=y_variable, data=self.df)
                plt.title(f"Box Plot of {x_variable} vs {y_variable}")
                plt.xlabel(x_variable)
                plt.ylabel(y_variable)
            elif visualization_type == "bar":
                # Assuming x is categorical and y is numerical
                sns.barplot(x=x_variable, y=y_variable, data=self.df)
                plt.title(f"Bar Plot of {x_variable} vs {y_variable}")
                plt.xlabel(x_variable)
                plt.ylabel(y_variable)
            else:
                messagebox.showerror("Error", "Invalid visualization type.")
                return

            plt.tight_layout()
            canvas = FigureCanvasTkAgg(plt.gcf(), master=self.plot_frame)
            canvas_widget = canvas.get_tk_widget()
            canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            canvas.draw()

        except Exception as e:
            messagebox.showerror("Error", f"Error creating plot: {e}")


    def run_script(self):
        script = self.script_text.get("1.0", tk.END)
        try:
            # Redirect stdout to the text widget
            import io, sys
            old_stdout = sys.stdout
            sys.stdout = TextRedirector(self.script_output)

            exec(script)

            # Restore stdout
            sys.stdout = old_stdout

        except Exception as e:
            self.script_output.config(state=tk.NORMAL)
            self.script_output.delete("1.0", tk.END)
            self.script_output.insert(tk.END, f"Error executing script: {e}")
            self.script_output.config(state=tk.DISABLED)

class TextRedirector:
    def __init__(self, widget):
        self.widget = widget

    def write(self, str):
        self.widget.config(state=tk.NORMAL)
        self.widget.insert(tk.END, str)
        self.widget.config(state=tk.DISABLED)

    def flush(self):
        pass #Add exception handling if needed



root = tk.Tk()
app = DataAnalyzerApp(root)
root.mainloop()
👁️ Viewed: 5

Comments