OmniConvert Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import json
import csv

class OmniConvertApp:
    def __init__(self, master):
        self.master = master
        master.title("OmniConvert: The Ultimate File Converter")
        master.geometry("800x600")

        self.input_file = tk.StringVar()
        self.output_file = tk.StringVar()
        self.conversion_type = tk.StringVar(value="JSON to CSV") # Default value

        self.create_widgets()

    def create_widgets(self):
        # Input File Selection
        input_label = ttk.Label(self.master, text="Input File:")
        input_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")
        input_entry = ttk.Entry(self.master, textvariable=self.input_file, width=60)
        input_entry.grid(row=0, column=1, padx=10, pady=10, sticky="we")
        input_button = ttk.Button(self.master, text="Browse", command=self.browse_input_file)
        input_button.grid(row=0, column=2, padx=10, pady=10, sticky="e")

        # Output File Selection
        output_label = ttk.Label(self.master, text="Output File:")
        output_label.grid(row=1, column=0, padx=10, pady=10, sticky="w")
        output_entry = ttk.Entry(self.master, textvariable=self.output_file, width=60)
        output_entry.grid(row=1, column=1, padx=10, pady=10, sticky="we")
        output_button = ttk.Button(self.master, text="Browse", command=self.browse_output_file)
        output_button.grid(row=1, column=2, padx=10, pady=10, sticky="e")

        # Conversion Type Selection
        conversion_label = ttk.Label(self.master, text="Conversion Type:")
        conversion_label.grid(row=2, column=0, padx=10, pady=10, sticky="w")
        conversion_options = ["JSON to CSV", "CSV to JSON", "TXT to JSON", "JSON to TXT", "XML to JSON", "JSON to XML"]
        conversion_combobox = ttk.Combobox(self.master, textvariable=self.conversion_type, values=conversion_options, state="readonly")
        conversion_combobox.grid(row=2, column=1, padx=10, pady=10, sticky="we")

        # Convert Button
        convert_button = ttk.Button(self.master, text="Convert", command=self.convert_file, style='Accent.TButton')
        convert_button.grid(row=3, column=1, padx=10, pady=20, sticky="e")

        # Status Label
        self.status_label = ttk.Label(self.master, text="Ready")
        self.status_label.grid(row=4, column=0, columnspan=3, padx=10, pady=10, sticky="w")

        # Details Button
        details_button = ttk.Button(self.master, text="Details", command=self.show_details)
        details_button.grid(row=5, column=0, columnspan=3, padx=10, pady=10, sticky="s")

        # Style
        style = ttk.Style(self.master)
        style.theme_use('clam')
        style.configure('Accent.TButton', background='#4CAF50', foreground='white', font=('Helvetica', 12, 'bold'))
        style.map('Accent.TButton', background=[('active', '!disabled', '#388E3C')])


    def browse_input_file(self):
        filename = filedialog.askopenfilename()
        self.input_file.set(filename)

    def browse_output_file(self):
        filename = filedialog.asksaveasfilename()
        self.output_file.set(filename)

    def convert_file(self):
        input_path = self.input_file.get()
        output_path = self.output_file.get()
        conversion = self.conversion_type.get()

        if not input_path or not output_path:
            messagebox.showerror("Error", "Please select both input and output files.")
            return

        try:
            if conversion == "JSON to CSV":
                self.json_to_csv(input_path, output_path)
            elif conversion == "CSV to JSON":
                self.csv_to_json(input_path, output_path)
            elif conversion == "TXT to JSON":
                 self.txt_to_json(input_path,output_path)
            elif conversion == "JSON to TXT":
                self.json_to_txt(input_path, output_path)
            elif conversion == "XML to JSON":
                self.xml_to_json(input_path, output_path)
            elif conversion == "JSON to XML":
                self.json_to_xml(input_path, output_path)
            else:
                messagebox.showerror("Error", "Invalid conversion type.")
                return

            self.status_label.config(text=f"{conversion} conversion successful!")
            messagebox.showinfo("Success", f"{conversion} conversion complete!")
        except Exception as e:
            self.status_label.config(text=f"Error: {e}")
            messagebox.showerror("Error", f"Conversion failed: {e}")

    def json_to_csv(self, json_path, csv_path):
        with open(json_path, 'r') as json_file:
            data = json.load(json_file)

        if isinstance(data, dict):
            data = [data] # Convert to list if it's a single object

        with open(csv_path, 'w', newline='') as csv_file:
            csv_writer = csv.writer(csv_file)
            header = data[0].keys()  # Assuming all dictionaries have the same keys
            csv_writer.writerow(header)
            for item in data:
                csv_writer.writerow(item.values())

    def csv_to_json(self, csv_path, json_path):
        data = []
        with open(csv_path, 'r') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            for row in csv_reader:
                data.append(row)

        with open(json_path, 'w') as json_file:
            json.dump(data, json_file, indent=4)

    def txt_to_json(self, txt_path, json_path):
        data = []
        with open(txt_path, 'r') as txt_file:
            for line in txt_file:
                # Assuming each line is a value that needs to be converted into JSON
                # Create a dictionary for each line
                data.append({'value': line.strip()})

        with open(json_path, 'w') as json_file:
            json.dump(data, json_file, indent=4)

    def json_to_txt(self, json_path, txt_path):
        with open(json_path, 'r') as json_file:
            data = json.load(json_file)

        with open(txt_path, 'w') as txt_file:
            if isinstance(data, list):
                for item in data:
                    # Assuming each item is a dictionary or a simple value
                    if isinstance(item, dict):
                        txt_file.write(str(item) + '\n')  # Write the dictionary as a string
                    else:
                        txt_file.write(str(item) + '\n')  # Write the value as a string
            else:
                txt_file.write(str(data) + '\n')  # Write the entire JSON data as a string

    def xml_to_json(self, xml_path, json_path):
        try:
            import xmltodict
        except ImportError:
            messagebox.showerror("Error", "xmltodict library is required for XML conversions.  Please install it (pip install xmltodict).")
            return

        try:
            with open(xml_path, 'r') as xml_file:
                xml_data = xml_file.read()

            data = xmltodict.parse(xml_data)

            with open(json_path, 'w') as json_file:
                json.dump(data, json_file, indent=4)
        except Exception as e:
            messagebox.showerror("Error", f"XML to JSON conversion failed: {e}")

    def json_to_xml(self, json_path, xml_path):
       try:
            import json
            import xml.etree.ElementTree as ET
            from xml.dom import minidom
        except ImportError:
            messagebox.showerror("Error", "Required libraries are missing. Please ensure json and xml.etree.ElementTree are installed.")
            return

       try:
            with open(json_path, 'r') as json_file:
                data = json.load(json_file)

            def json_to_xml_recursive(data, parent=None):
                if isinstance(data, dict):
                    for key, value in data.items():
                        element = ET.SubElement(parent, key)
                        json_to_xml_recursive(value, element)
                elif isinstance(data, list):
                    for item in data:
                        element = ET.SubElement(parent, 'item')  # Generic tag for list items
                        json_to_xml_recursive(item, element)
                else:
                    parent.text = str(data)

            root = ET.Element('root') # Root element
            json_to_xml_recursive(data, root)

            xml_string = ET.tostring(root, encoding='utf-8')
            dom = minidom.parseString(xml_string)
            pretty_xml = dom.toprettyxml(indent="  ")

            with open(xml_path, 'w') as xml_file:
                xml_file.write(pretty_xml)

       except Exception as e:
            messagebox.showerror("Error", f"JSON to XML conversion failed: {e}")


    def show_details(self):
        details_text = (
            "OmniConvert is a versatile file conversion tool designed to handle a variety of common file formats.  It currently supports conversions between JSON, CSV, TXT, and XML formats. Key features include:\n\n"  # Corrected line
            "- User-friendly graphical interface for easy file selection and conversion."
            "- Support for converting JSON to CSV and vice versa."
            "- Ability to convert text files to JSON and JSON to text files."
            "- XML to JSON and JSON to XML conversion capabilities (requires the 'xmltodict' library; install with 'pip install xmltodict')."
            "- Clear status updates and error messages."
            "- Conversion progress displayed in the status bar."
            "- Robust error handling to prevent crashes."
            "- Customizable output options, such as specifying the output file name and location.\n\n"
            "OmniConvert simplifies file conversion tasks, making it an indispensable tool for data manipulation and exchange. Future updates will include support for more file formats and advanced conversion options."
        )
        messagebox.showinfo("Details", details_text)


root = tk.Tk()
app = OmniConvertApp(root)
root.mainloop()
👁️ Viewed: 7

Comments