33import json
44import os
55import shutil
6+ import zipfile
67from copy import deepcopy
78from pathlib import Path
89from typing import Any
1314MINIMAL_SET_TEMPLATE = "minimal_template_set.json"
1415
1516
17+ def zip_sorted_folder (folder_path , zip_path ):
18+ """Zips the contents of a folder, preserving the directory structure.
19+ Args:
20+ folder_path: The path to the folder to zip.
21+ zip_path: The path where the zip file will be created.
22+ """
23+ with zipfile .ZipFile (zip_path , 'w' ) as zf :
24+ for root , dirs , files in os .walk (folder_path ):
25+ # Sort files for deterministic order
26+ for file in sorted (files ):
27+ abs_path = os .path .join (root , file )
28+ rel_path = os .path .relpath (abs_path , folder_path )
29+ zf .write (abs_path , arcname = rel_path )
30+
1631def converter (
1732 question_template : dict [str , Any ], set_template : dict [str , Any ], ListQuestions : list [Question ], output_dir : str
1833) -> None :
@@ -28,13 +43,9 @@ def converter(
2843
2944 # create directory to put the questions
3045 os .makedirs (output_dir , exist_ok = True )
31- output_question = os .path .join (output_dir , "set " )
46+ output_question = os .path .join (output_dir , "set_a_simple_example " )
3247 os .makedirs (output_question , exist_ok = True )
3348
34- # create directory to put images - should be in set
35- output_image = os .path .join (output_question , "media" )
36- os .makedirs (output_image , exist_ok = True )
37-
3849 # create the set file
3950 with open (f"{ output_question } /set_a_simple_example.json" , "w" ) as file :
4051 json .dump (set_template , file )
@@ -80,10 +91,13 @@ def converter(
8091 image_path = os .path .abspath (
8192 ListQuestions [i ].images [k ]
8293 ) # converts computer path into python path
94+ # If images exist, create a media directory
95+ output_image = os .path .join (output_question , "media" )
96+ os .makedirs (output_image , exist_ok = True )
8397 shutil .copy (image_path , output_image ) # copies image into the directory
8498
8599 # output zip file in destination folder
86- shutil . make_archive (output_question , " zip", output_question )
100+ zip_sorted_folder (output_question , output_question + ". zip" )
87101
88102
89103def main (questions : list [Question ], output_dir : str ) -> None :
0 commit comments