2.2 Diseño de las técnicas de control
2.2.2 Técnicas de control para el tanque de mezclado
2.2.2.1 Sintonización del controlador tipo FOPID para el tanque de
Now that we have a class that allows us to gather information about photos, we can apply this information to perform useful tasks. In this case, we will use the file information to automatically organize a folder full of photos into a subset of folders based on the dates the photos were taken on. The following screenshot shows the output of the script:
The application will use the photo's information to sort pictures into folders by the date on which they were taken
Getting ready
You will need a selection of photos placed in a folder on the Raspberry Pi. Alternatively, you can insert a USB memory stick or card reader with photos on it—they will be located under /mnt/. However, please make sure you test the scripts with a copy of your photos first, just in case there are any problems.
How to do it…
Create the following script in filehandler.py to automatically organize your photos: #!/usr/bin/python3
#filehandler.py import os import shutil
import photohandler as PH from operator import itemgetter FOLDERSONLY=True DEBUG=True defaultpath="" NAME=0 DATE=1 class FileList: def __init__(self,folder): """Class constructor""" self.folder=folder self.listFileDates() def getPhotoNamedates(self):
"""returns the list of filenames and dates""" return self.photo_namedates
def listFileDates(self):
"""Generate list of filenames and dates""" self.photo_namedates = list()
if os.path.isdir(self.folder):
for filename in os.listdir(self.folder): if filename.lower().endswith(".jpg"): aPhoto = PH.Photo(os.path.join(self.folder,filename)) if aPhoto.filevalid: if (DEBUG):print("NameDate: %s %s"% (filename,aPhoto.getDate())) self.photo_namedates.append((filename, aPhoto.getDate())) self.photo_namedates = sorted(self.photo_namedates, key=lambda date: date[DATE])
def genFolders(self):
"""function to generate folders"""
for i,namedate in enumerate(self.getPhotoNamedates()): #Remove the - from the date format
new_folder=namedate[DATE].replace("-","") newpath = os.path.join(self.folder,new_folder) #If path does not exist create folder
if not os.path.exists(newpath):
if (DEBUG):print ("New Path: %s" % newpath) os.makedirs(newpath)
if (DEBUG):print ("Found file: %s move to %s" % (namedate[NAME],newpath))
src_file = os.path.join(self.folder,namedate[NAME]) dst_file = os.path.join(newpath,namedate[NAME]) try:
if (DEBUG):print ("File moved %s to %s" % (src_file, dst_file))
if (FOLDERSONLY==False):shutil.move(src_file, dst_file) except IOError:
print ("Skipped: File not found") def main():
"""called only when run directly, allowing module testing""" import tkinter as TK
from tkinter import filedialog app = TK.Tk()
app.withdraw()
dirname = TK.filedialog.askdirectory(parent=app, initialdir=defaultpath,
title='Select your pictures folder') if dirname != "": ourFileList=FileList(dirname) ourFileList.genFolders() if __name__=="__main__": main() #End
How it works…
We shall make a class called FileList; it will make use of the Photo class to manage the photos within a specific folder. There are two main steps for this: we first need to find all the images within the folder, and then generate a list containing both the filename and the photo date. We will use this information to generate new subfolders and move the photos into these folders.
When we create the FileList object, we will create the list using listFileDates(). We will then confirm that the folder provided is valid and use os.listdir to obtain the full list of files within the directory. We will check that each file is a .jpg file and obtain each photo's date (using the function defined in the Photo class). Next, we will add the filename and date as a tuple to the self.photo_namedates list.
Finally, we will use the built-in sorted function to place all the files in order of their date. While we don't need to do this here, this function would make it easier to remove duplicate dates if we were to use this module elsewhere.
The sorted function requires the list to be sorted, and in this case, we want to sort it by the date values.
sorted(self.photo_namedates,key=lambda date: date[DATE])
We will substitute date[DATE] with lambda date: as the value to sort by.
Once the FileList object has been initialized, we can use it by calling genFolders(). First, we convert the date text into a suitable format for our folders (YYYYMMDD), allowing our folders to be easily sorted in order of their date. Next, it will create the folders within the current directory if they don't already exist. Finally, it will move each of the files into the required subfolder.
We end up with our FileList class that is ready to be tested:
Operations Description
__init__(self,folder) This is the object initialization function
getPhotoNamedates(self) This returns a list of the filenames of the dates of the photos
listFileDates(self) This creates a list of the filenames and dates of the photos in the folder
The properties are mentioned as follows:
Properties Description
self.folder The folder we are working with
self.photo_namedates This contains a list of the filenames and dates
Tkinter filediaglog.askdirectory() is used to select the photo directory
To test this, we use the Tkinter filedialog.askdirectory() widget to allow us to select a target directory of pictures. We use app.withdrawn() to hide the main Tkinter window since it isn't required this time. We just need to create a new FileList object and then call genFolders() to move all our photos to new locations!
Two additional flags have been defined in this script that provide an extra control for testing. DEBUG allows us to enable or disable extra debugging messages by setting them to either True or False. Apart from this,
FOLDERSONLY when set to True only generates the folders and doesn't move the files (this is helpful for testing whether the new subfolders are correct).
Once you have run the script, you can check if all the folders have been created correctly. Finally, change FOLDERSONLY to True, and your program will automatically move and organize your photos according to their dates the next time. It is recommended that you only run this on a copy of your photos, just in case you get an error.