testfiles / app.py
dunlp's picture
Update app.py
a145384 verified
raw
history blame
5.51 kB
import os
import re
import gradio as gr
from shutil import copy
from tkinter import Tk
from tkinter.filedialog import askdirectory
from os import makedirs, listdir
from os.path import isdir, isfile, join, realpath
# --- Constants ---
phases = ["iFAT", "(i)SAT"]
inputPhases = {**{i: k for i, k in enumerate(phases)}, **{len(phases): "All"}}
regTemplate = r'template'
# --- Helper Functions ---
# Function to open a folder selection dialog
def select_folder():
Tk().withdraw() # Hides the root window
folder_selected = askdirectory()
return folder_selected
# Function to validate if a directory exists
def validate_directory(directory_path):
return os.path.isdir(directory_path)
# Function to get list of files matching a pattern
def getFilesWith(path: str, reg: str):
if not isdir(path):
print(f"{path} is not a valid path")
return None
content = listdir(path)
if len(content) == 0:
print(f"{path} has no content")
return None
files = [f for f in content if isfile(join(path, f)) and re.search(reg, f, re.IGNORECASE)]
if len(files) == 0:
print(f"{path} contains no {reg}")
return None
return files
# Function to create new folders
def createNewFolders(dirs: list):
for d in dirs:
if not isdir(d):
makedirs(d)
else:
print(f"Directory already exists: {d}")
# Function to create new templates
def createNewTemplates(objs, templatesDir, regTemplate, root):
templatefiles = getFilesWith(templatesDir, regTemplate)
for k in objs:
regPhase = r""
match k:
case "(i)SAT":
regPhase = r"sat"
case "iFAT":
regPhase = r"fat"
files = [f for f in templatefiles if re.search(regPhase, f, re.IGNORECASE)]
if len(files) == 0:
print(f"Phase {k} has no templates")
continue
for o in objs[k]:
targetLocation = join(root, o)
tlFiles = getFilesWith(targetLocation, regPhase)
if tlFiles:
print(f"{k} files already exist in: {targetLocation}")
continue
for f in files:
templatepath = join(templatesDir, f)
targetpath = targetLocation
if re.search(r"hut_\d{4}[a-zA-Z]{2}", f, re.IGNORECASE):
targetpath = join(targetLocation, f[:4] + o + f[10:])
copy(templatepath, targetpath)
# Function to get objects per phase
def getObjectsPerPhase(phase: str = "All"):
with open("./objecten.txt", "r") as f:
t = f.read().split("\n\n")
objs = {p: [] for p in phases}
if phase in phases:
objs = {phase: []}
regObject = r"\d{4}[a-zA-Z]{2}"
for g in t:
ls = g.split("\n")
k = ls[0]
if k in objs:
objs[k] = ls[1::]
else:
print(f"Key [{k}] is not recognized")
objs = {k: objs[k] for k in objs if objs[k]}
for k in objs:
for i, o in enumerate(objs[k]):
m = re.search(regObject, o)
if not m:
continue
objs[k][i] = m.group(0)
return objs
# Function to copy and paste templates
def copyPasteTemplates(root: str, phase: str, templatesDir: str):
objs = getObjectsPerPhase(phase)
objectslist = list(set([o for p in [objs[k] for k in objs] for o in p]))
createNewFolders([join(root, o) for o in objectslist])
print("Directories created")
createNewTemplates(objs, templatesDir, regTemplate, root)
print("Templates ready")
# --- Main Gradio App ---
# Main function to run steps
def run_steps(phase, root_dir, templates_dir):
testphase = phase
rootDir = root_dir
templatesDir = templates_dir
# Run folder creation process
if not validate_directory(rootDir):
return f"Error: Root directory '{rootDir}' does not exist."
if not validate_directory(templatesDir):
return f"Error: Templates directory '{templatesDir}' does not exist."
copyPasteTemplates(rootDir, testphase, templatesDir)
return "Folders created successfully!"
# Gradio interface
def validate_and_run(phase, root_dir, templates_dir):
if not root_dir or not templates_dir:
return "Error: Please provide both the root and templates directory paths."
return run_steps(phase, root_dir, templates_dir)
# Functions to trigger folder selection for Gradio
def select_root_directory():
return select_folder()
def select_templates_directory():
return select_folder()
# Gradio app components
with gr.Blocks() as app:
gr.Markdown("# Folder Creation Tool")
phase_input = gr.Dropdown(choices=list(inputPhases.values()), label="Select Phase")
root_dir_input = gr.Textbox(label="Root Directory", placeholder="Select the root directory")
root_dir_button = gr.Button("Select Root Directory")
root_dir_button.click(fn=select_root_directory, outputs=root_dir_input)
templates_dir_input = gr.Textbox(label="Templates Directory", placeholder="Select the templates directory")
templates_dir_button = gr.Button("Select Templates Directory")
templates_dir_button.click(fn=select_templates_directory, outputs=templates_dir_input)
create_button = gr.Button("Create Folders")
output = gr.Textbox(label="Output")
create_button.click(validate_and_run, inputs=[phase_input, root_dir_input, templates_dir_input], outputs=output)
app.launch()