dunlp commited on
Commit
184f2d6
1 Parent(s): 9a7c444

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -65
app.py CHANGED
@@ -1,73 +1,84 @@
1
- import os
2
- import shutil
3
- import zipfile
4
- import tempfile
5
  import gradio as gr
 
 
 
6
 
7
- def process(phase, template_zip, object_file):
8
  try:
9
- if template_zip is None:
10
- return "Error: Please upload the template directory as a ZIP file."
11
- if object_file is None:
12
- return "Error: Please upload the object names TXT file."
13
-
14
- # Create a temporary directory for processing
15
- with tempfile.TemporaryDirectory() as tmpdir:
16
- # Unzip the template directory
17
- template_dir = os.path.join(tmpdir, 'template')
18
- with zipfile.ZipFile(template_zip.name, 'r') as zip_ref:
19
- zip_ref.extractall(template_dir)
20
-
21
- # Read object names from the txt file
22
- object_names = object_file.read().decode('utf-8').splitlines()
23
-
24
- # Create a directory to store the results
25
- result_dir = os.path.join(tmpdir, 'results')
26
- os.makedirs(result_dir, exist_ok=True)
27
-
28
- for object_name in object_names:
29
- if not object_name.strip():
30
- continue # Skip empty lines
31
- # Create a directory for the object under result_dir
32
- object_dir = os.path.join(result_dir, f"{phase}_{object_name}")
33
- os.makedirs(object_dir, exist_ok=True)
34
-
35
- # Copy files from template_dir to object_dir
36
- for root, dirs, files in os.walk(template_dir):
37
- rel_path = os.path.relpath(root, template_dir)
38
- dest_dir = os.path.join(object_dir, rel_path)
39
- os.makedirs(dest_dir, exist_ok=True)
40
- for filename in files:
41
- template_file = os.path.join(root, filename)
42
- if os.path.isfile(template_file):
43
- # Get the file extension
44
- name, ext = os.path.splitext(filename)
45
- # Create new filename with object name appended
46
- new_filename = f"{name}_{object_name}{ext}"
47
- new_file = os.path.join(dest_dir, new_filename)
48
- shutil.copy(template_file, new_file)
49
-
50
- # Zip the result_dir
51
- result_zip_path = os.path.join(tmpdir, 'result.zip')
52
- shutil.make_archive(os.path.splitext(result_zip_path)[0], 'zip', result_dir)
53
-
54
- # Return the zip file for download
55
- return result_zip_path
56
- except Exception as e:
57
- return f"Error: {str(e)}"
58
 
59
- phase_dropdown = gr.Dropdown(choices=['FAT', 'iFAT', 'iSAT'], label='Select Phase')
 
 
60
 
61
- template_zip_input = gr.File(label='Template Directory (ZIP file)', file_types=['.zip'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- object_file_input = gr.File(label='Object Names File (TXT)', file_types=['.txt'])
64
 
65
- output_file = gr.File(label='Download Result ZIP')
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- gr.Interface(
68
- fn=process,
69
- inputs=[phase_dropdown, template_zip_input, object_file_input],
70
- outputs=output_file,
71
- title='Directory and File Creator',
72
- description='Upload the template directory as a ZIP file and the object names TXT file. The processed files will be provided as a downloadable ZIP.'
73
- ).launch()
 
 
 
 
 
1
  import gradio as gr
2
+ import zipfile
3
+ import io
4
+ import re
5
 
6
+ def process_files(phase, objecten_file, template_files):
7
  try:
8
+ # Read and process the 'objecten.txt' file
9
+ content = objecten_file.read().decode('utf-8')
10
+ t = content.strip().split('\n\n')
11
+ phases = ["iFAT", "(i)SAT"]
12
+ objs = {p: [] for p in phases}
13
+ if phase in phases:
14
+ objs = {phase: []}
15
+ else:
16
+ objs = {p: [] for p in phases}
17
+
18
+ regObject = r"\d{4}[a-zA-Z]{2}"
19
+ for g in t:
20
+ ls = g.strip().split('\n')
21
+ k = ls[0]
22
+ if k in objs:
23
+ objs[k] = ls[1:]
24
+ else:
25
+ error_msg = f"Key [{k}] is not recognized."
26
+ return None, error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Extract object codes
29
+ for k in objs:
30
+ objs[k] = [re.search(regObject, o).group(0) for o in objs[k] if re.search(regObject, o)]
31
 
32
+ # Create an in-memory ZIP file
33
+ zip_buffer = io.BytesIO()
34
+ with zipfile.ZipFile(zip_buffer, 'w') as zf:
35
+ for k in objs:
36
+ regPhase = ''
37
+ if k == '(i)SAT':
38
+ regPhase = r'sat'
39
+ elif k == 'iFAT':
40
+ regPhase = r'fat'
41
+
42
+ # Filter template files for this phase
43
+ phase_templates = [f for f in template_files if re.search(regPhase, f.name, re.IGNORECASE)]
44
+ if not phase_templates:
45
+ error_msg = f"Phase {k} has no templates."
46
+ return None, error_msg
47
+
48
+ for o in objs[k]:
49
+ folder_path = f"{o}/"
50
+ for f in phase_templates:
51
+ template_filename = f.name
52
+ # Adjust filename if needed
53
+ if re.search(r"hut_\d{4}[a-zA-Z]{2}", template_filename, re.IGNORECASE):
54
+ adjusted_filename = template_filename[:4] + o + template_filename[10:]
55
+ else:
56
+ adjusted_filename = template_filename
57
+
58
+ file_content = f.read()
59
+ f.seek(0) # Reset file pointer
60
+ file_path = folder_path + adjusted_filename
61
+ zf.writestr(file_path, file_content)
62
+ zip_buffer.seek(0)
63
+ return zip_buffer, None
64
+ except Exception as e:
65
+ return None, str(e)
66
 
67
+ phase_options = ['iFAT', '(i)SAT', 'All']
68
 
69
+ interface = gr.Interface(
70
+ fn=process_files,
71
+ inputs=[
72
+ gr.Dropdown(choices=phase_options, label="Select Phase"),
73
+ gr.File(label="Upload 'objecten.txt' File", type='file'),
74
+ gr.File(label="Upload Template Files", type='file', multiple=True)
75
+ ],
76
+ outputs=[
77
+ gr.File(label="Download ZIP File"),
78
+ gr.Textbox(label="Error Message", lines=2)
79
+ ],
80
+ title="Template Folder Generator",
81
+ description="Upload 'objecten.txt' and template files to generate folders and files."
82
+ )
83
 
84
+ interface.launch()