testfiles / app.py
dunlp's picture
Update app.py
184f2d6 verified
raw
history blame
3.01 kB
import gradio as gr
import zipfile
import io
import re
def process_files(phase, objecten_file, template_files):
try:
# Read and process the 'objecten.txt' file
content = objecten_file.read().decode('utf-8')
t = content.strip().split('\n\n')
phases = ["iFAT", "(i)SAT"]
objs = {p: [] for p in phases}
if phase in phases:
objs = {phase: []}
else:
objs = {p: [] for p in phases}
regObject = r"\d{4}[a-zA-Z]{2}"
for g in t:
ls = g.strip().split('\n')
k = ls[0]
if k in objs:
objs[k] = ls[1:]
else:
error_msg = f"Key [{k}] is not recognized."
return None, error_msg
# Extract object codes
for k in objs:
objs[k] = [re.search(regObject, o).group(0) for o in objs[k] if re.search(regObject, o)]
# Create an in-memory ZIP file
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zf:
for k in objs:
regPhase = ''
if k == '(i)SAT':
regPhase = r'sat'
elif k == 'iFAT':
regPhase = r'fat'
# Filter template files for this phase
phase_templates = [f for f in template_files if re.search(regPhase, f.name, re.IGNORECASE)]
if not phase_templates:
error_msg = f"Phase {k} has no templates."
return None, error_msg
for o in objs[k]:
folder_path = f"{o}/"
for f in phase_templates:
template_filename = f.name
# Adjust filename if needed
if re.search(r"hut_\d{4}[a-zA-Z]{2}", template_filename, re.IGNORECASE):
adjusted_filename = template_filename[:4] + o + template_filename[10:]
else:
adjusted_filename = template_filename
file_content = f.read()
f.seek(0) # Reset file pointer
file_path = folder_path + adjusted_filename
zf.writestr(file_path, file_content)
zip_buffer.seek(0)
return zip_buffer, None
except Exception as e:
return None, str(e)
phase_options = ['iFAT', '(i)SAT', 'All']
interface = gr.Interface(
fn=process_files,
inputs=[
gr.Dropdown(choices=phase_options, label="Select Phase"),
gr.File(label="Upload 'objecten.txt' File", type='file'),
gr.File(label="Upload Template Files", type='file', multiple=True)
],
outputs=[
gr.File(label="Download ZIP File"),
gr.Textbox(label="Error Message", lines=2)
],
title="Template Folder Generator",
description="Upload 'objecten.txt' and template files to generate folders and files."
)
interface.launch()