def diff_textfiles(source_textfile, other_textfile):
    '''
    Compares two textfiles. Returns strings that indicate losslessness.
    '''
    if filecmp.cmp(source_textfile, other_textfile, shallow=False):
        print(" - YOUR FILES ARE LOSSLESS YOU SHOULD BE SO HAPPY!!!")
        return 'lossless'

    else:
        print(" - CHECKSUM MISMATCH - Further information on the next line!!!")
        return 'lossy' def create_csv(csv_file, *args):
    f = open(csv_file, 'w', newline='')
    try:
        writer = csv.writer(f)
        writer.writerow(*args)
    finally:
        f.close() def append_csv(csv_file, *args):
    f = open(csv_file, 'a', newline='')
    try:
        writer = csv.writer(f)
        writer.writerow(*args)
    finally:
        f.close() def send_gmail(email_to, attachment, subject, email_body, email_address, password):
    '''
    Rarely used but working emailer.
    '''
    emailfrom = ""
    emailto = email_to
    #emailto = ", ".join(emailto)
    fileToSend = attachment
    username = email_address
    password = password
    msg = MIMEMultipart()
    msg["From"]    = emailfrom
    msg["To"]      = ", ".join(emailto)
    msg["Subject"] = subject
    msg.preamble   = "testtesttest"
    body = MIMEText(email_body)
    msg.attach(body)
    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"
    maintype, subtype = ctype.split("/", 1)
    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
    attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
    msg.attach(attachment)
    server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    server_ssl.ehlo() # optional, called by login()
    server_ssl.login(username, password)
    # ssl server doesn't support or need tls, so don't call server_ssl.starttls()
    server_ssl.sendmail(emailfrom, emailto, msg.as_string())
    print(msg.as_string())
    #server_ssl.quit()
    server_ssl.close()
    print(' - successfully sent the mail') def hashlib_manifest(manifest_dir, manifest_textfile, path_to_remove):
    '''
    Creates an MD5 manifest with relative filepaths.
    '''
    file_count = 0
    for root, directories, filenames in os.walk(manifest_dir):
        filenames = [f for f in filenames if not f[0] == '.']
        directories[:] = [d for d in directories if not d[0] == '.']
        for files in filenames:
            #print(" - Calculating number of files to process in current directory -  %s files        \r "% file_count)
            print("- Calculating number of files to process in current directory - {0} files ".format(file_count), end="\r")
            file_count += 1
    manifest_generator = ''
    md5_counter = 1
    for root, directories, filenames in os.walk(manifest_dir):
        filenames = [f for f in filenames if f[0] != '.']
        directories[:] = [d for d in directories if d[0] != '.']
        for files in filenames:
            print(' - Generating MD5 for %s - file %d of %d' % (os.path.join(root, files), md5_counter, file_count))
            md5 = hashlib_md5(os.path.join(root, files))
            md5_counter += 1
            root2 = os.path.abspath(root).replace(path_to_remove, '')
            try:
                if root2[0] == '/':
                    root2 = root2[1:]
                if root2[0] == '\\':
                    root2 = root2[1:]
            except: IndexError
            manifest_generator += md5[:32] + '  ' + os.path.join(root2, files).replace("\\", "/") + '\n'
    manifest_list = manifest_generator.splitlines()
    files_in_manifest = len(manifest_list)
    # http://stackoverflow.com/a/31306961/2188572
    manifest_list = sorted(manifest_list, key=lambda x: (x[34:]))
    with open(manifest_textfile, "w", encoding='utf-8') as fo:
        for i in manifest_list:
            fo.write((unicodedata.normalize('NFC', i) + '\n')) def make_mediainfo(xmlfilename, xmlvariable, inputfilename):
    '''
    Writes a verbose mediainfo XML output using the OLDXML schema.
    '''
    mediainfo_cmd = [
        'mediainfo',
        '-f',
        '--language=raw',
        '--File_TestContinuousFileNames=0',
        '--output=OLDXML',
        inputfilename
    ]
    with open(xmlfilename, "w") as fo:
        # https://stackoverflow.com/a/21486747
        try:
            xmlvariable = subprocess.check_output(mediainfo_cmd).decode(sys.stdout.encoding)
        except UnicodeDecodeError:
            xmlvariable = subprocess.check_output(mediainfo_cmd).decode('cp1252')
        fo.write(xmlvariable) def make_mediatrace(tracefilename, xmlvariable, inputfilename):
    mediatrace_cmd = [
            'mediainfo',
            '-f',
            '--Details=1', '--File_TestContinuousFileNames=0', # Use verbose output.
            '--output=XML',
            inputfilename
        ]
    with open(tracefilename, "w") as fo:
        # https://stackoverflow.com/a/21486747
        try:
            xmlvariable = subprocess.check_output(mediatrace_cmd).decode(sys.stdout.encoding)
        except UnicodeDecodeError:
            try:
                xmlvariable = subprocess.check_output(mediatrace_cmd).decode('cp1252')
            except UnicodeDecodeError:
                # Some N19/STL files seem to produce characters which are incompatible with uff-8 and cp1252.
                xmlvariable = 'None'
        fo.write(xmlvariable) def get_date_modified(filename):
    """Gets the date modified date of a filename in ISO8601 style.

    Date created values seem to be difficult to grab in a cross-platform way.


        Args:
            filename: Path of filename to check.

        Returns:
            date_modified: string, for example '2016-12-19T21:30:43'

        """
    epoch_time = os.path.getmtime(filename)
    date_modified = datetime.datetime.fromtimestamp(epoch_time).strftime("%Y-%m-%dT%H:%M:%S")
    return date_modified def make_premis(source_file, items, premis, premis_namespace, premisxml,representation_uuid,sequence):
    # the sequence argument determines if a sequence counter is launched
    xml_info = create_object(source_file, items, premis, premis_namespace, premisxml, representation_uuid, sequence)
    return xml_info def write_premis(doc, premisxml):
    with open(premisxml,'w') as outFile:
        doc.write(outFile,pretty_print=True) def make_agent(premis,linkingEventIdentifier_values, agentId ):
    csv_file = os.path.expanduser("~/ifigit/ifiscripts/premis_agents.csv")
    if os.path.isfile(csv_file):
        read_object = open(csv_file)
        reader = csv.reader(read_object)
        csv_list = list(reader)
        read_object.close()
    for lists in csv_list:
        for item in lists:
            if item == agentId:
                agent_info = lists
    agentIdType_value,agentIdValue_value,agentName_value,agentType_value, agentVersion_value,agentNote_value,agentRole = agent_info

    if agentVersion_value == 'ffmpeg_autoextract':
        agentVersion_value = subprocess.check_output(['ffmpeg','-version','-v','0']).splitlines()[0]
    premis_namespace            = "http://www.loc.gov/premis/v3"
    agent                       = ET.SubElement(premis, "{%s}agent" % (premis_namespace))
    premis.insert(-1, agent)
    agentIdentifier             = create_unit(1,agent,'agentIdentifier')
    agentIdType                 = create_unit(2,agentIdentifier,'agentIdentifierType')
    agentIdValue                = create_unit(2,agentIdentifier,'agentIdentifierValue')
    agentName                   = create_unit(2,agent,'agentName')
    agentName.text              = agentName_value
    if not agentNote_value == '':
        agentNote                   = create_unit(5,agent,'agentNote')
        agentNote.text              = agentNote_value
    agentType                   = create_unit(3,agent,'agentType')
    if not agentVersion_value == '':
        agentVersion                = create_unit(4,agent,'agentVersion')
        agentVersion.text           = agentVersion_value
    agentIdType.text            = agentIdType_value
    agentIdValue.text           = agentIdValue_value
    agentType.text              = agentType_value
    for event_link in linkingEventIdentifier_values:
        linkingEventIdentifier      = create_unit(6,agent,'linkingEventIdentifier')
        linkingEventIdentifierType = create_unit(1,linkingEventIdentifier, 'linkingEventIdentifierType')
        linkingEventIdentifierValue = create_unit(1,linkingEventIdentifier, 'linkingEventIdentifierValue')
        linkingEventIdentifierValue.text = event_link
        linkingEventIdentifierType.text = 'UUID'
    agent_info                  = [agentIdType_value,agentIdValue_value]
    return agent_info def make_event(premis,event_type, event_detail, agentlist, eventID, eventLinkingObjectIdentifier, eventLinkingObjectRole, event_time):
        premis_namespace                    = "http://www.loc.gov/premis/v3"
        event = ET.SubElement(premis, "{%s}event" % (premis_namespace))
        premis.insert(-1,event)
        event_Identifier                    = create_unit(1,event,'eventIdentifier')
        event_id_type                       = ET.Element("{%s}eventIdentifierType" % (premis_namespace))
        event_Identifier.insert(0,event_id_type)
        event_id_value                      = ET.Element("{%s}eventIdentifierValue" % (premis_namespace))
        event_Identifier.insert(0,event_id_value)
        event_Type                          = ET.Element("{%s}eventType" % (premis_namespace))
        event.insert(2,event_Type)
        event_DateTime                      = ET.Element("{%s}eventDateTime" % (premis_namespace))
        event.insert(3,event_DateTime)
        if event_time == 'now':
            event_DateTime.text             = time.strftime("%Y-%m-%dT%H:%M:%S")
        else:
            event_DateTime.text             = event_time
        event_Type.text                     = event_type
        event_id_value.text                 = eventID
        event_id_type.text                  = 'UUID'
        eventDetailInformation              = create_unit(4,event,'eventDetailInformation')
        eventDetail                         = create_unit(0,eventDetailInformation,'eventDetail')
        eventDetail.text                    = event_detail
        for i in eventLinkingObjectIdentifier:
            linkingObjectIdentifier             = create_unit(5,event,'linkingObjectIdentifier')
            linkingObjectIdentifierType         = create_unit(0,linkingObjectIdentifier,'linkingObjectIdentifierType')
            linkingObjectIdentifierValue        = create_unit(1,linkingObjectIdentifier,'linkingObjectIdentifierValue')
            linkingObjectIdentifierValue.text   = i
            linkingObjectRole                   = create_unit(2,linkingObjectIdentifier,'linkingObjectRole')
            linkingObjectIdentifierType.text    = 'UUID'
            linkingObjectRole.text              = eventLinkingObjectRole
        for i in agentlist:
            linkingAgentIdentifier              = create_unit(-1,event,'linkingAgentIdentifier')
            linkingAgentIdentifierType          = create_unit(0,linkingAgentIdentifier,'linkingAgentIdentifierType')
            linkingAgentIdentifierValue         = create_unit(1,linkingAgentIdentifier,'linkingAgentIdentifierValue')
            linkingAgentIdentifierRole          = create_unit(2,linkingAgentIdentifier,'linkingAgentRole')
            linkingAgentIdentifierRole.text     = 'implementer'
            linkingAgentIdentifierType.text     = i[0]
            linkingAgentIdentifierValue.text    = i[1] def setup_xml(source_file):
    premisxml           = os.path.dirname(os.path.dirname(source_file)) + '/metadata' '/' + os.path.basename(os.path.dirname(os.path.dirname(source_file))) + '_premis.xml'
    namespace           = '<premis:premis xmlns:premis="http://www.loc.gov/premis/v3" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/premis/v3 https://www.loc.gov/standards/premis/premis.xsd" version="3.0"></premis:premis>'
    premis_namespace    = "http://www.loc.gov/premis/v3"
    xsi_namespace       = "http://www.w3.org/2001/XMLSchema-instance"
    print premisxml
    if os.path.isfile(premisxml):
        print 'looks like premis already exists?'
        parser      = ET.XMLParser(remove_blank_text=True)
        doc         = ET.parse(premisxml,parser=parser)
        premis      = doc.getroot()
    else:
        premis              = ET.fromstring(namespace)
        doc                 = ET.ElementTree(premis)
    return premisxml, premis_namespace, doc, premis def create_unit(index,parent, unitname):
    premis_namespace = "http://www.loc.gov/premis/v3"
    unitname = ET.Element("{%s}%s" % (premis_namespace, unitname))
    parent.insert(index,unitname)
    return unitname def create_representation(premisxml, premis_namespace, doc, premis, items, linkinguuids, representation_uuid, sequence, intellectual_entity_uuid):
        object_parent                                           = create_unit(1, premis, 'object')
        object_identifier_parent                                = create_unit(1,object_parent, 'objectIdentifier')
        object_identifier_uuid                                  = create_unit(0,object_parent, 'objectIdentifier')
        object_identifier_uuid_type                             = create_unit(1,object_identifier_uuid, 'objectIdentifierType')
        object_identifier_uuid_type.text                        = 'UUID'
        object_identifier_uuid_value                            = create_unit(2,object_identifier_uuid, 'objectIdentifierValue')
        object_identifier_uuid_value.text                       = representation_uuid
        # add uuids to csv so that other workflows can use them as linking identifiers.
        representation_uuid_csv(items['filmographic'],items['sourceAccession'], representation_uuid)
        object_parent.insert(1,object_identifier_parent)
        ob_id_type                                              = ET.Element("{%s}objectIdentifierType" % (premis_namespace))
        ob_id_type.text                                         = 'Irish Film Archive Object Entry Register'
        objectIdentifierValue                                   = create_unit(1, object_identifier_parent, 'objectIdentifierValue')
        objectIdentifierValue.text                              = items['oe']
        object_identifier_parent.insert(0,ob_id_type)
        objectCategory                                          = create_unit(2,object_parent, 'objectCategory')
        objectCategory.text                                     = 'representation'
        # These hardcoded relationships do not really belong here. They should be stipulated by another microservice
        if sequence == 'sequence':
            representation_relationship(object_parent, premisxml, items, 'structural', 'has root',linkinguuids[1][0], 'root_sequence', 'UUID')
            for i in linkinguuids[1]:
                representation_relationship(object_parent, premisxml, items, 'structural', 'includes',i, 'includes', 'UUID')

        representation_relationship(object_parent, premisxml, items, 'structural', 'includes',linkinguuids[0], 'n/a', 'UUID')
        representation_relationship(object_parent, premisxml, items, 'derivation', 'has source',linkinguuids[2], 'n/a', 'Irish Film Archive Film Accession Register 2010 -')
        representation_relationship(object_parent, premisxml, items, 'structural', 'represents',intellectual_entity_uuid, 'n/a', 'UUID') def create_intellectual_entity(premisxml, premis_namespace, doc, premis, items, intellectual_entity_uuid):
    object_parent                                           = create_unit(0, premis, 'object')
    object_identifier_uuid                                  = create_unit(2,object_parent, 'objectIdentifier')
    object_identifier_uuid_type                             = create_unit(1,object_identifier_uuid, 'objectIdentifierType')
    object_identifier_uuid_type.text                        = 'UUID'
    object_identifier_uuid_value                            = create_unit(2,object_identifier_uuid, 'objectIdentifierValue')
    object_identifier_uuid_value.text                       = intellectual_entity_uuid
    # add uuids to csv so that other workflows can use them as linking identifiers.
    representation_uuid_csv(items['filmographic'],items['sourceAccession'], intellectual_entity_uuid)
    object_identifier_filmographic                          = create_unit(3,object_parent, 'objectIdentifier')
    object_identifier_filmographic_reference_number         = create_unit(1,object_identifier_filmographic, 'objectIdentifierType')
    object_identifier_filmographic_reference_number.text    = 'Irish Film Archive Filmographic Database'
    object_identifier_filmographic_reference_value          = create_unit(2,object_identifier_filmographic, 'objectIdentifierValue')
    object_identifier_filmographic_reference_value.text     = items['filmographic']
    objectCategory                                          = create_unit(4,object_parent, 'objectCategory')
    objectCategory.text                                     = 'intellectual entity'
import subprocess
import sys
import os
import datetime
import time
import csv
import uuid
import lxml.etree as ET
from glob import glob
from ififuncs import diff_textfiles
from ififuncs import create_csv
from ififuncs import append_csv
from ififuncs import send_gmail
from ififuncs import hashlib_manifest
from ififuncs import make_mediainfo
from ififuncs import make_mediatrace
from ififuncs import get_date_modified
from premis import make_premis
from premis import write_premis
from premis import make_agent
from premis import make_event
from premis import setup_xml
from premis import create_unit
from premis import create_representation
from premis import create_intellectual_entity
    permission = ''
    if not permission == 'y' or permission == 'Y':
        print '\n\n**** All image sequences within these directories will be converted the input for this script.\n'
        for i in all_files:
            print i
        permission =  raw_input('\n**** All image sequences within these directories will be converted the input for this script \n**** If this looks ok, please press Y, otherwise, type N\n' )
        while permission not in ('Y','y','N','n'):
            permission =  raw_input('\n**** All image sequences within these directories will be converted the input for this script \n**** If this looks ok, please press Y, otherwise, type N\n')
        if permission == 'n' or permission == 'N':
            print 'Exiting at your command- Cheerio for now'
            sys.exit()
        elif permission =='y' or permission == 'Y':
            print 'Ok so!'
    csv_report_filename = desktop_logdir + '/seq2prores_report' + time.strftime("_%Y_%m_%dT%H_%M_%S") + '.csv'
    user = get_user()
    create_csv(csv_report_filename, ('Sequence Name', 'Start time', 'Finish Time'))
    for source_directory in all_files:
        for root,dirnames,filenames in os.walk(source_directory):
                #if "tiff_scans"  in dirnames:
                source_directory = root# + '/tiff_scans'
                total_size = 0
                remove_bad_files(source_directory)
                source_parent_dir    = os.path.dirname(source_directory)
                normpath             = os.path.normpath(source_directory)
                relative_path        = normpath.split(os.sep)[-1]
                split_path           = os.path.split(os.path.basename(source_directory))[1]
                start = datetime.datetime.now()

                info = get_filenames(source_directory, 'dpx_framemd5')
                if info == 'none':
                    continue
                for files in filenames:
                    total_size += os.path.getsize(os.path.join(root,files))
                master_parent_dir     = os.path.dirname(source_parent_dir)
                master_object_dir     = master_parent_dir + '/objects/image'
                master_metadata_dir = master_parent_dir + '/' + 'metadata'
                middle =  os.listdir(os.path.dirname(os.path.dirname(master_parent_dir)) + '/mezzanine')[0]
                mezzanine_object_dir            =  os.path.dirname(os.path.dirname(master_parent_dir)) + '/mezzanine/%s/objects' % middle
                mezzanine_parent_dir   = os.path.dirname(os.path.dirname(master_parent_dir)) + '/mezzanine/%s' % middle
                mezzanine_metadata_dir = mezzanine_parent_dir + '/metadata'
                source_manifest =  master_parent_dir + '/' + os.path.basename( master_parent_dir) +  '_manifest.md5'
                mezzanine_manifest =   mezzanine_parent_dir + '/' + os.path.basename( mezzanine_parent_dir) +  '_manifest.md5'
                audio_dir_list = os.listdir(master_parent_dir + '/objects/audio')
                for audio_files in audio_dir_list:
                    if not audio_files[0] == '.':
                        if audio_files.endswith('.wav'):
                            master_audio =  master_parent_dir + '/objects/audio/' + audio_files
                            audio_date_modified = get_date_modified(master_audio)
                mezzanine_file =  mezzanine_object_dir + '/' + os.path.basename(mezzanine_parent_dir) + '_mezzanine.mov'
                if os.path.isfile(mezzanine_file):
                    print 'Mezzanine file already exists so this script has most likely already been run.. skipping.'
                    continue
                image_seq_without_container = info[0]
                start_number                = info[1]
                container                   = info[2]
                image_date_modified         = info[3]
                start_number_length = len(start_number)
                number_regex = "%0" + str(start_number_length) + 'd.'
                audio_dir            = source_parent_dir + '/audio'
                logs_dir            =  mezzanine_parent_dir + '/logs'
                intellectual_entity_uuid = str(uuid.uuid4())
                source_representation_uuid = premis_description(master_object_dir, master_parent_dir + '/objects/audio', user, image_date_modified, audio_date_modified, intellectual_entity_uuid)

                os.chdir(audio_dir)
                audio_file_list = glob('*.wav')
                audio_file = os.path.join(audio_dir,audio_file_list[0])
                dpx_filename                = image_seq_without_container + number_regex + container
                logfile = logs_dir + '/%s_prores.log' % os.path.basename(mezzanine_parent_dir)
                env_dict = os.environ.copy()
                # https://github.com/imdn/scripts/blob/0dd89a002d38d1ff6c938d6f70764e6dd8815fdd/ffmpy.py#L272
                logfile = "\'" + logfile + "\'"
                env_dict['FFREPORT'] = 'file={}:level=48'.format(logfile)
                seq2prores= ['ffmpeg','-y','-f','image2','-framerate','24', '-start_number', start_number, '-i', root + '/' + dpx_filename ,'-i', audio_file,'-c:v','prores','-profile:v', '3','-c:a','pcm_s24le', '-ar', '48000', mezzanine_object_dir + '/' + os.path.basename(mezzanine_parent_dir) + '_mezzanine.mov','-f', 'framemd5', '-an', master_metadata_dir + '/image/' + os.path.basename(master_parent_dir) + '.framemd5', '-c:a', 'pcm_s24le', '-f', 'framemd5', '-vn', master_metadata_dir + '/audio/' + os.path.basename(master_parent_dir) + '.framemd5']
                print seq2prores
                subprocess.call(seq2prores,env=env_dict)
                representation_uuid = str(uuid.uuid4())
                split_list = os.path.basename(mezzanine_parent_dir).split('_')
                premisxml, premis_namespace, doc, premis = setup_xml(mezzanine_file)
                items = {"workflow":"seq2prores","oe":'n/a', "filmographic":split_list[0], "sourceAccession":split_list[1], "interventions":['placeholder'], "prepList":['placeholder'], "user":user}
                premis = doc.getroot()
                xml_info    = make_premis(mezzanine_file, items, premis, premis_namespace,premisxml, representation_uuid, '????')
                sequence = xml_info[3]

                linking_representation_uuids = []
                linking_representation_uuids.append(xml_info[2])
                linking_representation_uuids.append(xml_info[2]) # the duplicate does nothing btw, they are a placeholder from a hardcoded function
                linking_representation_uuids.append(source_representation_uuid)
                create_intellectual_entity(premisxml, premis_namespace, doc, premis, items, intellectual_entity_uuid)
                create_representation(premisxml, premis_namespace, doc, premis, items,linking_representation_uuids, representation_uuid,sequence, intellectual_entity_uuid)
                doc         = xml_info[0]
                premisxml   = xml_info[1]
                final_sip_manifest_uuid                     = str(uuid.uuid4())
                prores_event_uuid                           = str(uuid.uuid4())

                macMiniTelecineMachineAgent_events          = [prores_event_uuid,final_sip_manifest_uuid  ]
                macMiniTelecineMachineAgent                 = make_agent(premis,macMiniTelecineMachineAgent_events, '230d72da-07e7-4a79-96ca-998b9f7a3e41')
                macMiniTelecineMachineOSAgent_events        = [prores_event_uuid,final_sip_manifest_uuid ]
                macMiniTelecineOSAgent                      = make_agent(premis,macMiniTelecineMachineOSAgent_events, '9486b779-907c-4cc4-802c-22e07dc1242f')

                hashlib_events                              = [final_sip_manifest_uuid ]
                hashlibAgent                                = make_agent(premis,hashlib_events, '9430725d-7523-4071-9063-e8a6ac4f84c4')
                ffmpegAgent_events                          = [prores_event_uuid ]
                ffmpegAgent                                 = make_agent(premis,ffmpegAgent_events , 'ee83e19e-cdb1-4d83-91fb-7faf7eff738e')
                operatorEvents                              = [final_sip_manifest_uuid,prores_event_uuid]
                operatorAgent                               = make_agent(premis,operatorEvents ,user)
                #ffmpegAgent                                 = make_agent(premis,[framemd5_uuid ], 'ee83e19e-cdb1-4d83-91fb-7faf7eff738e')
                make_event(premis, 'creation', 'Image Sequence and WAV re-encoded to Apple Pro Res 422 HQ with 48khz 24-bit PCM audio', [macMiniTelecineMachineAgent ,macMiniTelecineOSAgent, ffmpegAgent, operatorAgent ],prores_event_uuid,[representation_uuid], 'outcome', 'now')

                print premisxml
                mezzanine_mediainfoxml =  "%s/%s_mediainfo.xml" % (mezzanine_metadata_dir,os.path.basename(mezzanine_parent_dir) )
                tracexml =  "%s/%s_mediatrace.xml" % (mezzanine_metadata_dir,os.path.basename(mezzanine_parent_dir) )
                audio_mediainfoxml = "%s/%s_mediainfo.xml" % (master_metadata_dir + '/audio',os.path.basename(master_audio) )
                audio_mediatracexml = "%s/%s_mediatrace.xml" % (master_metadata_dir + '/audio',os.path.basename(master_audio) )
                if not os.path.isfile(audio_mediainfoxml):
                    make_mediainfo(audio_mediainfoxml,'audiomediaxmlinput',master_audio)
                if not os.path.isfile(audio_mediatracexml):
                    make_mediainfo(audio_mediatracexml,'audiomediatraceinput',master_audio)
                if not os.path.isfile(mezzanine_mediainfoxml):
                    make_mediainfo(mezzanine_mediainfoxml,'mediaxmlinput',mezzanine_object_dir + '/' + os.path.basename(mezzanine_parent_dir) + '_mezzanine.mov')
                if not os.path.isfile(tracexml):

                    make_mediatrace(tracexml,'mediatracexmlinput',mezzanine_object_dir + '/' + os.path.basename(mezzanine_parent_dir) + '_mezzanine.mov')