File size: 1,368 Bytes
67de853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import tarfile
import os
import shutil

IMAGE_EXTENSION = '.png'

# this script create a 'temp' folder and rename all images to its description, then add the folder to a tar file
if __name__ == "__main__":

    # remove the temp folder if it exists
    if os.path.exists('./temp'):
      for filename in os.listdir('./temp'): # empty the folder
        os.remove('./temp/' + filename)
      os.rmdir('./temp') # remove the folder
    
    # create the folder again
    os.makedirs('./temp')


    # copy all images to the temp folder
    for filename in os.listdir('./data/images'):
      # get the matching text file on the 'texts' folder, if not found, skip
      text_filename = filename[:-len(IMAGE_EXTENSION)] + '.txt'
      if not os.path.exists('./data/texts/' + text_filename):
        continue

      # read the text file
      with open('./data/texts/' + text_filename, 'r') as f:
        description = f.read()

      # copy the images to the temp folder, renaming it to the description replacing spaces with underscores
      shutil.copyfile('./data/images/' + filename, './temp/' + description.replace(' ', '_') + IMAGE_EXTENSION)

    # create a tar file with only the temp folder images
    with tarfile.open( "./images.tar.gz", "w:gz") as tar:
      for filename in os.listdir('./temp'):
        tar.add('./temp/' + filename, arcname=filename)