Wednesday, December 16, 2015

Throwback Thursday inspired python code.

Throwback Thursday inspired code.

For anyone else out there finding this, if you take the code and modify it or put it somewhere else public, let me know. If I do such a thing, I too will let you know.

First off, all I wanted was a way to find images for Throwback Thursday and I have a very messy folder called Pictures and in there my photos go back to 2003, November.

Some are older, but their modification/creation dates on my computer will not reflect their true date/time so this tool will be useless for those. Unless I modify it later, for example, I can think of an improvement. . . if date modified content does not match date in name of file (parse the name of the file) then use the name as the date.

[update] I am not sure how to make this better. It is definitely not 100% accurate. For example, today, some of the 10 images I've pulled up were created on 9/6/2012 (Thursday) BUT they were created for a web-site by a script I used in the past.  By pure coincidence, it also happens to be originally taken on Thursday, July 19, 2012... so, here it is :).

Angel Island, Thursday, July 19, 2012


The code is currently below. I also put it on Siafoo.

================================= usage:

Mac OS X Terminal with python3 and python installed.  This python3 is 3.4.

Show in Mac Preview app 10 files of png or jpg found in /foo/bar directory:

python3 tbt.py /foo/bar/ -n 10 -m

List all files in /foo/bar directory:

python3 tbt.py -l /foo/bar

List all options with -h:

unknown68a86d404130:play michaelcase$ python3 tbt.py -h
usage: tbt.py [-h] [-d D] [-l] [-m] [-mw] [-n N] directory

Program for "Throwback Thursdays" allows users to specify day of week to find,
defaults to Thursday, and provides a list of files of jpg and png within the directory you
specify that occurred on that day of week. However, precedence goes mw, m then
l. In other words, ONLY ONE of those flags will be supported, if you specify
more than one, the precedence is enforced.

positional arguments:
  directory   Required. Directory from which to read files.

optional arguments:
  -h, --help  show this help message and exit
  -d D        Optional. Day of week. Defaults to Thursday. Can not do multiple
              days.
  -l          Optional. Reply with list of files that can be passed to
              something like xargs.
  -m          Optional. Mac OS open Preview App with resulting list of files.
              If the list of files gets too long, the command may fail.
  -mw         Optional. Mac OS open Preview App with one image per window. Can
              be torture to your screen, be careful.
  -n N        Optional. Number of files to *randomly* retreive from list.

(Revision 1.0 of 2015-12-14 14:15:28)


================================= code, cut here to end. put in file tyt.py


# use os.path.getctime to get creation date/time.
# use date.weekday() to get 0 = Monday to 6 = Sunday.
# then use present Thursdays as tbt files :)

# ctime - the last time the file's inode was changed (e.g. permissions changed, file renamed, etc..)
# mtime - last time the file's CONTENTS were changed
# atime - last time the file was accessed.
# author: Michael E. Case, mec at dcn dot davis dot ca dot us
 
import sys
import os
from datetime import *
import time
from sys import argv
#from subprocess import Popen
import argparse
import random

# 2015-12-14: 
# Given a path, search through it and all it's subdirectories for "throwback thursday" files.

# info to identify program and current revision, and some globals.
global pgm, rev, date
pgm  = (sys.argv[0]).replace('./','')
rev  = '$Revision: 1.0 $'.replace('$','')[9:].strip()
date = '$Date: 2015-12-14 14:15:28 $'.replace('$','')[5:].strip()

def isint( s ):
    try:
        int(s)
    except ValueError:
        return False
    else:
        return True

def tbt_main():

    #read command arguments
    global pgm, rev, date

    ap = argparse.ArgumentParser(prog=pgm, epilog="(Revision "+rev+" of "+date+")", description="""Program for \"Throwback Thursdays\"
allows users to specify day of week to find, defaults to Thursday, and provides a list of files of jpg and png within the directory 
you specify that occurred on that day of week. However, precedence goes mw, m then l. In other words, ONLY ONE of 
those flags will be supported, if you specify more than one, the precedence is enforced.""")    
    ap.add_argument("directory", help="Required. Directory from which to read files.")
    ap.add_argument("-d", help="Optional. Day of week. Defaults to Thursday. Can not do multiple days.", default="3")
    ap.add_argument("-l", help="Optional. Reply with list of files that can be passed to something like xargs.", action="store_true", default=False)
    ap.add_argument("-m", help="Optional. Mac OS open Preview App with resulting list of files. If the list of files gets too long, the command may fail.", action="store_true", default=False)
    ap.add_argument("-mw", help="Optional. Mac OS open Preview App with one image per window. Can be torture to your screen, be careful.", action="store_true", default=False)
    ap.add_argument("-n", help="Optional. Number of files to *randomly* retreive from list.", default=-1, type=int)
    newargs = ap.parse_args() 
    #print(newargs)
    #if ()
    listfiles = newargs.l
    indir = newargs.directory
    nf = newargs.n
    macprev = newargs.m
    macprevwin = newargs.mw
    dow = 3
    if isint(newargs.d) == False:
        lcd = newargs.d.lower()
        if "monday" in lcd:
            dow = 0
        elif "tuesday" in lcd:
            dow = 1
        elif "wednesday" in lcd:
            dow = 2
        elif "thursday" in lcd:
            dow = 3
        elif "friday" in lcd:
            dow = 4
        elif "saturday" in lcd:
            dow = 5
        elif "sunday" in lcd:
            dow = 6
        else:
            print(newargs.d+" not found in day of week. Day of week will default to Thursday (3).")
            dow = 3
    else:
        if dow > 6:
            print(newargs.d+" is greater than 6. Day of week will default to Thursday (3).")
            dow = 3


    if macprev == True and macprevwin == True and listfiles == True:
        macprev = False
        listfiles = False
        print("Found -mw, -w and -l, precedence dictates using mw.")
    if macprev == True and listfiles == True:
        listfiles = False
        print("Found -w and -l, precedence ditates using -m.")
    if macprevwin == True and listfiles == True:
        listfiles = False
        print("Found -mw and -l, precedence dictates using -mw.")

    # print(macprev, str(nf), indir, listfiles)

    # print(indir)
    fs = ""
    fsofar = 0
    randomfs = False
    if nf != -1:
        randomfs = True
    nfilestot = 0
    # probtofind = 0
    rindstosave = []

    # can't figure out how to do this using "probability of this picture being one of the n you requested."
    # or rather, that solution did not always give me n. So the new solution is come up with n integers between
    # one and nfilestot. Those will be the ones we get. No repeats, of course.
    if randomfs == True:
        for root, dirs, files in os.walk(indir, topdown=True):
            #print("in first for")
            for name in files:
                tm = os.path.getmtime(os.path.join(root,name))
                dt = datetime.fromtimestamp(tm)
                if dt.weekday() == dow:
                    if len(name.split(".")) > 1:
                        spl = name.split(".")
                        last = spl[len(spl)-1]
                        if last.lower() == "jpg" or last.lower() == "png":
                            nfilestot +=1
        #print("total number of all jpg and png = "+str(nfilestot))
        if nfilestot > 0:
            nsel = 0
            while nsel < nf and nf > 0:
                rn = random.randint(1, nfilestot) # [1, nfilestot]
                if rn not in rindstosave:
                    rindstosave.append(rn)
                    nsel += 1
                
            # print ("nsel = "+str(nsel))
            # print (rindstosave)
            rindstosave.sort()
            # print (rindstosave)
            # probtofind = nf / nfilestot
    fc = 0
    for root, dirs, files in os.walk(indir, topdown=True):
        #print("in first for")
        for name in files:
            #print("in second for")
            tm = os.path.getmtime(os.path.join(root,name))
            dt = datetime.fromtimestamp(tm)
            if dt.weekday() == dow:
                if len(name.split(".")) > 1:
                    spl = name.split(".")
                    last = spl[len(spl)-1]
                    if last.lower() == "jpg" or last.lower() == "png":
                        fc += 1
                        #print("found jpg")
                        #os.system
                        #Popen
                        if macprev == True:
                            #print (fs)
                            if randomfs == False:
                                fs += "\""+os.path.join(root,name)+"\" "
                            else:
                                if fc in rindstosave:
                                    fs += "\""+os.path.join(root,name)+"\" "
                                    rindstosave = rindstosave[1:]
                        if macprevwin == True:
                            if randomfs == False:
                                os.system("open -a /Applications/Preview.app "+"\""+os.path.join(root,name)+"\"")
                            else:
                                if fc in rindstosave:
                                    os.system("open -a /Applications/Preview.app "+"\""+os.path.join(root,name)+"\"")
                                    rindstosave = rindstosave[1:]
                        if listfiles == True:
                            if randomfs == False:
                                print("\""+os.path.join(root,name)+"\"")
                            else:
                                if fc in rindstosave:
                                    print("\""+os.path.join(root,name)+"\"")
                                    rindstosave = rindstosave[1:]
                        #
#                print(os.path.join(root,name)) 
                # call("open -f -a /Applications/Preview.app", os.path.join(root,name))
    if macprev == True:
        #print ("open -a /Applications/Preview.app "+fs)
        os.system("open -a /Applications/Preview.app "+fs)

if __name__ == "__main__":
    tbt_main()