dunlp commited on
Commit
1130bd7
1 Parent(s): 06626f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -61
app.py CHANGED
@@ -1,73 +1,91 @@
1
- import re
2
  import gradio as gr
 
 
 
 
3
 
4
- # Simulating an in-memory virtual filesystem for directories and files
5
- virtual_filesystem = {}
 
 
 
 
 
 
 
 
 
6
 
7
- def create_virtual_directory(path):
8
- if path not in virtual_filesystem:
9
- virtual_filesystem[path] = {}
10
- return f"Directory '{path}' created."
11
- return f"Directory '{path}' already exists."
 
 
 
 
12
 
13
- def create_new_templates(objs, templatesDir, regTemplate, root):
14
- result = []
15
- if templatesDir not in virtual_filesystem:
16
- return f"Error: Template directory '{templatesDir}' not found."
17
 
18
- template_files = [f for f in virtual_filesystem[templatesDir] if re.search(regTemplate, f, re.IGNORECASE)]
19
- if not template_files:
20
- return f"No templates matching '{regTemplate}' found in {templatesDir}."
21
-
22
- for phase in objs:
23
- phase_files = [f for f in template_files if re.search(phase.lower(), f, re.IGNORECASE)]
24
- if not phase_files:
25
- result.append(f"No templates for phase '{phase}' found.")
26
- continue
27
 
28
- for obj in objs[phase]:
29
- target_dir = f"{root}/{obj}"
30
- create_virtual_directory(target_dir)
31
- result.append(f"Copied templates for {obj}.")
32
-
33
- return "\n".join(result)
34
 
35
- # Simulated phase selection
36
- def get_objects_per_phase(phase="All"):
37
- objects = {
38
- "iFAT": ["001ABC", "002DEF"],
39
- "(i)SAT": ["003GHI", "004JKL"],
40
- }
41
- return objects if phase == "All" else {phase: objects.get(phase, [])}
42
 
43
- def process_folders_and_templates(root_dir, phase, templates_dir):
44
- try:
45
- # Create directories based on phase objects
46
- objects = get_objects_per_phase(phase)
47
- for obj_list in objects.values():
48
- for obj in obj_list:
49
- create_virtual_directory(f"{root_dir}/{obj}")
50
-
51
- # Copy template files
52
- return create_new_templates(objects, templates_dir, r'template', root_dir)
53
- except Exception as e:
54
- return f"Error occurred: {str(e)}"
55
-
56
- # Gradio Interface
57
- def gradio_interface(root_dir, phase, templates_dir):
58
- return process_folders_and_templates(root_dir, phase, templates_dir)
59
 
60
- # Gradio App
61
- with gr.Blocks() as app:
62
- gr.Markdown("# Folder and Template Processor")
63
-
64
- root_dir = gr.Textbox(label="Root Directory")
65
- phase = gr.Dropdown(choices=["iFAT", "(i)SAT", "All"], label="Phase Selection")
66
- templates_dir = gr.Textbox(label="Templates Directory")
 
 
67
 
68
- output = gr.Textbox(label="Output")
69
 
70
- submit_button = gr.Button("Create Folders and Copy Templates")
71
- submit_button.click(gradio_interface, inputs=[root_dir, phase, templates_dir], outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- app.launch()
 
 
1
  import gradio as gr
2
+ import zipfile
3
+ import io
4
+ import re
5
+ import traceback
6
 
7
+ def process_files(phase, objecten_file_dict, template_files_data):
8
+ try:
9
+ # Read and process the 'objecten.txt' file
10
+ content = objecten_file_dict['data'].decode('utf-8')
11
+ t = content.strip().split('\n\n')
12
+ phases = ["iFAT", "(i)SAT"]
13
+ objs = {p: [] for p in phases}
14
+ if phase in phases:
15
+ objs = {phase: []}
16
+ else:
17
+ objs = {p: [] for p in phases}
18
 
19
+ regObject = r"\d{4}[a-zA-Z]{2}"
20
+ for g in t:
21
+ ls = g.strip().split('\n')
22
+ k = ls[0]
23
+ if k in objs:
24
+ objs[k] = ls[1:]
25
+ else:
26
+ error_msg = f"Key [{k}] is not recognized."
27
+ return None, error_msg
28
 
29
+ # Extract object codes
30
+ for k in objs:
31
+ objs[k] = [re.search(regObject, o).group(0) for o in objs[k] if re.search(regObject, o)]
 
32
 
33
+ # Create an in-memory ZIP file
34
+ zip_buffer = io.BytesIO()
35
+ with zipfile.ZipFile(zip_buffer, 'w') as zf:
36
+ for k in objs:
37
+ regPhase = ''
38
+ if k == '(i)SAT':
39
+ regPhase = r'sat'
40
+ elif k == 'iFAT':
41
+ regPhase = r'fat'
42
 
43
+ # Filter template files for this phase
44
+ phase_templates = []
45
+ for file_dict in template_files_data:
46
+ filename = file_dict['name']
47
+ if re.search(regPhase, filename, re.IGNORECASE):
48
+ phase_templates.append(file_dict)
49
 
50
+ if not phase_templates:
51
+ error_msg = f"Phase {k} has no templates."
52
+ return None, error_msg
 
 
 
 
53
 
54
+ for o in objs[k]:
55
+ folder_path = f"{o}/"
56
+ for file_dict in phase_templates:
57
+ template_filename = file_dict['name']
58
+ # Adjust filename if needed
59
+ if re.search(r"hut_\d{4}[a-zA-Z]{2}", template_filename, re.IGNORECASE):
60
+ adjusted_filename = template_filename[:4] + o + template_filename[10:]
61
+ else:
62
+ adjusted_filename = template_filename
 
 
 
 
 
 
 
63
 
64
+ file_content = file_dict['data']
65
+ file_path = folder_path + adjusted_filename
66
+ zf.writestr(file_path, file_content)
67
+ zip_buffer.seek(0)
68
+ return zip_buffer, None
69
+ except Exception as e:
70
+ # Capture the full traceback
71
+ error_msg = traceback.format_exc()
72
+ return None, error_msg
73
 
74
+ phase_options = ['iFAT', '(i)SAT', 'All']
75
 
76
+ interface = gr.Interface(
77
+ fn=process_files,
78
+ inputs=[
79
+ gr.Dropdown(choices=phase_options, label="Select Phase"),
80
+ gr.File(label="Upload 'objecten.txt' File", type='binary'),
81
+ gr.File(label="Upload Template Files", type='binary', multiple=True)
82
+ ],
83
+ outputs=[
84
+ gr.File(label="Download ZIP File"),
85
+ gr.Textbox(label="Error Log", lines=15)
86
+ ],
87
+ title="Template Folder Generator",
88
+ description="Upload 'objecten.txt' and template files to generate folders and files."
89
+ )
90
 
91
+ interface.launch()