Source

babtools-misc / convert_to_ogv.py

Full commit
#!/usr/bin/env python
# encoding: utf-8

"""Convert all target files to ogv into a target directory, skipping previously converted files. Usage similar to "cp".

Usage:

    - ./convert_to_ogv.py * ogv/
      converts all files into the ogv/ folder which aren't yet there (identified by filename).
      Only takes relative paths! 
"""

__copyright__ = """ 
  convert_to_ogv - Convert all target files to ogv, skipping previously converted files. 
----------------------------------------------------------------- 
© 2008 - 2009 Copyright by Arne Babenhauserheide

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
  MA 02110-1301 USA

""" 



from sys import argv
from os import listdir, makedirs
from os.path import isdir, dirname, join, abspath, normpath
from subprocess import call

# First parse cmdline args
# Fast help output
if "--help" in argv:
    print __doc__
    exit()

# Now read and remove the target dir from argv
target = argv[-1]
argv = argv[1:-1]

# Remove any trailing "/"
argv = [normpath(p) for p in argv]

# We should now have only filepaths in the argv

# Now we need a convenience function to change the suffix
def suffix_to_ogv(name):
    """Replace the suffix with .ogv"""
    n = name.split(".")
    n[-1] = "ogv"
    name = ".".join(n)
    return name

#: All existing files in the target folder
existing_ogv = listdir(target)

#: All given files which aren't yet in the target folder - with replaced suffixes and their old name {ogv: old}
ogv_to_be = {}
for name in argv:
    if abspath(name) == name:
        print("Sorry, we currently only take relative paths.")
        print(__doc__)
        exit()
        
    ogv = suffix_to_ogv(name)
    if not ogv in existing_ogv: 
        ogv_to_be[ogv] = name

# Now we add another function which converts a given file and saves it with a given new filename
def convert_to_ogv(orig_path, new_path):
    """Use ffmpeg2theora to convert the file."""
    # If we don't yet have the dirs for the new file, create them
    if not isdir(dirname(new_path)):
        makedirs(dirname(new_path))
    call(["ffmpeg2theora", "-o", new_path, orig_path])

# And actually do it :)
for ogv in ogv_to_be:
    convert_to_ogv(ogv_to_be[ogv], join(target, ogv))