Certainly! Below is a Gradio version of your file sorting script. This web-based interface allows you to interact with the file sorter through a user-friendly GUI. The functionality remains the same, including setting paths, adding/removing extensions, previewing sorting, and executing the sort.
import os
import glob
import shutil
import gradio as gr
# Initial default paths (These can be changed through the interface)
TargetFolder = r"C:\Users\hardy\Documents\School\File Sorter\test"
Log = True
ImagesPath = r"C:\Users\hardy\Pictures\Pictures"
MusicPath = r"C:\Users\hardy\Music\Music"
VideoPath = r"C:\Users\hardy\Videos\Videos"
# Mapping of file extensions to destination folders
extension_mapping = {
# Images
'jpg': ImagesPath,
'jpeg': ImagesPath,
'png': ImagesPath,
'dng': ImagesPath,
'img': ImagesPath,
'webp': ImagesPath,
'gif': ImagesPath,
'tif': ImagesPath,
# Music
'mp3': MusicPath,
'wav': MusicPath,
'flac': MusicPath,
'aac': MusicPath,
# Videos
'mp4': VideoPath,
'avi': VideoPath,
'mkv': VideoPath,
'mov': VideoPath,
# Documents
'pdf': r"C:\Users\hardy\Documents",
'docx': r"C:\Users\hardy\Documents",
'xlsx': r"C:\Users\hardy\Documents",
'pptx': r"C:\Users\hardy\Documents",
'txt': r"C:\Users\hardy\Documents",
# Compressed
'zip': r"C:\Users\hardy\Downloads\Compressed",
'rar': r"C:\Users\hardy\Downloads\Compressed",
'7z': r"C:\Users\hardy\Downloads\Compressed",
# Programming Files
'py': r"C:\Users\hardy\Documents\Programming",
'java': r"C:\Users\hardy\Documents\Programming",
'c': r"C:\Users\hardy\Documents\Programming",
'cpp': r"C:\Users\hardy\Documents\Programming",
# Add more if desired
}
def log(text=""):
if Log:
return f"INFO: {text}\n"
return ""
def sort_files():
output = ""
for ext, dest_path in extension_mapping.items():
result = typesort(ext, TargetFolder, dest_path)
output += result
return output if output else "No files to sort."
def typesort(file_extension, folder_path, copy_folder):
output = ""
if not os.path.exists(folder_path):
output += f"ERROR: The folder {folder_path} does not exist.\n"
return output
if not os.path.exists(copy_folder):
output += f"ERROR: The destination folder {copy_folder} does not exist.\n"
return output
# Search for all files with the given extension in the folder
search_pattern = os.path.join(folder_path, f'*.{file_extension}')
files = glob.glob(search_pattern)
if not files:
output += log(f"No files with the extension .{file_extension} found in {folder_path}.")
return output
# Move the found files
for file_path in files:
try:
shutil.move(file_path, copy_folder)
output += log(f"{file_path} moved to {copy_folder}.")
except Exception as e:
output += f"ERROR: Error moving {file_path}: {e}\n"
return output
def get_files_for_extension(ext, folder_path):
search_pattern = os.path.join(folder_path, f'*.{ext}')
files = glob.glob(search_pattern)
return files
def update_extension_destinations(new_path, extensions):
for ext in extensions:
extension_mapping[ext] = new_path
def preview_sort():
output = ""
for ext, dest_path in extension_mapping.items():
files_moved = get_files_for_extension(ext, TargetFolder)
if files_moved:
output += f"Files with extension '.{ext}' will be moved to '{dest_path}':\n"
for file_path in files_moved:
output += f" {file_path}\n"
else:
output += f"No files with extension '.{ext}' found in '{TargetFolder}'.\n"
return output if output else "No files to preview."
def add_extension(ext, dest):
ext = ext.strip().lower()
extension_mapping[ext] = dest.strip()
return f"Extension '.{ext}' will now be sorted into: {dest}"
def remove_extension(ext):
ext = ext.strip().lower()
if ext in extension_mapping:
del extension_mapping[ext]
return f"Extension '.{ext}' has been removed from sorting."
else:
return f"Extension '.{ext}' not found in current mappings."
def show_extensions():
output = "Current File Extension Mappings:\n"
for ext, path in extension_mapping.items():
output += f".{ext} -> {path}\n"
return output
def toggle_logging():
global Log
Log = not Log
return f"Logging is now {'enabled' if Log else 'disabled'}."
def set_paths(target_folder, images_path, music_path, video_path):
global TargetFolder, ImagesPath, MusicPath, VideoPath
TargetFolder = target_folder.strip()
ImagesPath = images_path.strip()
MusicPath = music_path.strip()
VideoPath = video_path.strip()
update_extension_destinations(ImagesPath, ['jpg', 'jpeg', 'png', 'dng', 'img', 'webp', 'gif', 'tif'])
update_extension_destinations(MusicPath, ['mp3', 'wav', 'flac', 'aac'])
update_extension_destinations(VideoPath, ['mp4', 'avi', 'mkv', 'mov'])
return "Paths updated successfully."
def show_paths():
return f"Current Paths:\nTarget Folder: {TargetFolder}\nImages Path: {ImagesPath}\nMusic Path: {MusicPath}\nVideo Path: {VideoPath}"
def save_settings():
try:
with open("file_sorter_settings.txt", "w") as f:
f.write(f"TargetFolder={TargetFolder}\n")
f.write(f"Log={Log}\n")
f.write(f"ImagesPath={ImagesPath}\n")
f.write(f"MusicPath={MusicPath}\n")
f.write(f"VideoPath={VideoPath}\n")
f.write("Extensions:\n")
for ext, path in extension_mapping.items():
f.write(f"{ext}:{path}\n")
return "Settings saved to 'file_sorter_settings.txt'."
except Exception as e:
return f"Error saving settings: {e}"
def load_settings():
try:
with open("file_sorter_settings.txt", "r") as f:
lines = f.readlines()
global TargetFolder, Log, ImagesPath, MusicPath, VideoPath, extension_mapping
extension_mapping = {}
for line in lines:
if line.startswith("TargetFolder="):
TargetFolder = line.strip().split("=", 1)[1]
elif line.startswith("Log="):
Log = line.strip().split("=", 1)[1] == 'True'
elif line.startswith("ImagesPath="):
ImagesPath = line.strip().split("=", 1)[1]
elif line.startswith("MusicPath="):
MusicPath = line.strip().split("=", 1)[1]
elif line.startswith("VideoPath="):
VideoPath = line.strip().split("=", 1)[1]
elif line.strip() == "Extensions:":
continue # Skip the Extensions line
else:
if ':' in line:
ext, path = line.strip().split(":", 1)
extension_mapping[ext] = path
return "Settings loaded from 'file_sorter_settings.txt'."
except FileNotFoundError:
return "No saved settings found. Using default settings."
except Exception as e:
return f"Error loading settings: {e}"
# Load settings at start
load_settings()
# Gradio Interface
with gr.Blocks(title="File Sorter") as demo:
gr.Markdown("# Welcome to File Sorter\n"
"This application allows you to sort files from a target folder into designated folders based on file extensions.")
with gr.Tab("Sort Files"):
sort_output = gr.Textbox(label="Sort Output", placeholder="Sorting logs will appear here...", lines=10)
confirm_sort = gr.Checkbox(label="Confirm Sort", value=True)
sort_button = gr.Button("Sort Files")
def on_sort(confirm_sort):
if confirm_sort:
return "Sorting cancelled. Please uncheck 'Confirm Sort' to proceed."
else:
return sort_files()
sort_button.click(on_sort, inputs=confirm_sort, outputs=sort_output)
with gr.Tab("Preview Sorting"):
preview_output = gr.Textbox(label="Preview Output", placeholder="Preview of files to be sorted...", lines=10)
preview_button = gr.Button("Preview Sorting")
preview_button.click(fn=preview_sort, outputs=preview_output)
with gr.Tab("Manage Extensions"):
with gr.Row():
ext_input = gr.Textbox(label="File Extension (without dot)")
dest_input = gr.Textbox(label="Destination Folder Path")
add_ext_button = gr.Button("Add Extension Mapping")
remove_ext_button = gr.Button("Remove Extension Mapping")
ext_output = gr.Textbox(label="Output", lines=2)
add_ext_button.click(fn=add_extension, inputs=[ext_input, dest_input], outputs=ext_output)
remove_ext_button.click(fn=remove_extension, inputs=ext_input, outputs=ext_output)
show_ext_button = gr.Button("Show Extension Mappings")
show_ext_output = gr.Textbox(label="Current Extension Mappings", lines=10)
show_ext_button.click(fn=show_extensions, outputs=show_ext_output)
with gr.Tab("Manage Paths"):
target_folder_input = gr.Textbox(label="Target Folder Path", value=TargetFolder)
images_path_input = gr.Textbox(label="Images Path", value=ImagesPath)
music_path_input = gr.Textbox(label="Music Path", value=MusicPath)
video_path_input = gr.Textbox(label="Video Path", value=VideoPath)
set_paths_button = gr.Button("Set Paths")
paths_output = gr.Textbox(label="Output", lines=2)
set_paths_button.click(fn=set_paths, inputs=[target_folder_input, images_path_input, music_path_input, video_path_input], outputs=paths_output)
show_paths_button = gr.Button("Show Current Paths")
show_paths_output = gr.Textbox(label="Current Paths", lines=5)
show_paths_button.click(fn=show_paths, outputs=show_paths_output)
with gr.Tab("Settings"):
toggle_log_button = gr.Button("Toggle Logging")
toggle_log_output = gr.Textbox(label="Logging Status", lines=1)
toggle_log_button.click(fn=toggle_logging, outputs=toggle_log_output)
with gr.Row():
save_button = gr.Button("Save Settings")
load_button = gr.Button("Load Settings")
settings_output = gr.Textbox(label="Settings Output", lines=2)
save_button.click(fn=save_settings, outputs=settings_output)
load_button.click(fn=load_settings, outputs=settings_output)
demo.launch()
How to Use the Gradio Interface:
-
Sort Files: Navigate to the "Sort Files" tab to execute the sorting. Uncheck the "Confirm Sort" checkbox to proceed, then click "Sort Files".
-
Preview Sorting: Go to the "Preview Sorting" tab and click "Preview Sorting" to see which files will be moved.
-
Manage Extensions:
- To add an extension, enter the extension (without a dot) and the destination folder, then click "Add Extension Mapping".
- To remove an extension, enter the extension and click "Remove Extension Mapping".
- Click "Show Extension Mappings" to view current mappings.
-
Manage Paths:
- Update the paths in the text fields and click "Set Paths" to apply.
- Click "Show Current Paths" to display the current paths.
-
Settings:
- Click "Toggle Logging" to enable or disable logging.
- Use "Save Settings" and "Load Settings" to save or load your configurations.
-
Launch: Run the script, and a Gradio interface will open in your browser for interaction.
Important Notes:
-
Permissions: Ensure that the script has the necessary permissions to read from and write to the directories specified.
-
Dependencies: Install Gradio using pip install gradio if you haven't already.
-
Paths: Update the default paths as necessary to match your system's directory structure.
-
Settings File: The settings are saved to and loaded from file_sorter_settings.txt in the script's directory.
-
Logging: Logging messages are displayed in the output text areas when logging is enabled.
Example:
Let's say you want to sort your downloads folder. You would:
- Set the Target Folder to your downloads directory.
- Adjust any destination paths if necessary.
- Optionally, add any new file extensions and their destinations.
- Preview the sorting to ensure it will act as expected.
- Uncheck "Confirm Sort" and click "Sort Files" to execute the sorting.
This Gradio application provides a convenient GUI for your file sorting script, making it easier to manage file organization tasks.