Jump to content

Recommended Posts

Posted

Um pequeno script que usa o FFMPEG para converter ficheiros de um tipo para o outro (por exemplo, de mp3 para ogg ou de wmv para mp3, e também funciona com videos, de wmv para avi, flv para avi, enfim, vejam o que é que ele pode converter por vós mesmos 😉)

Ora como eu sou um preguiçoso de primeira, para não estar a converter os ficheiros um a um, este script procura por todos os ficheiros de um dado tipo numa pasta e converte-os para o outro tipo.

Como não fiz nenhuma interface de texto, para mudarem os parâmetros, apenas têm de mudar os primeiros parâmetros (Talvez depois eu crie uma interface com argumentos). FEITO! em EDIT

A primeira variável diz respeito ao tipo de ficheiros originais, a segunda o tipo de ficheiros para os quais vão ser convertidos, a terceira a pasta onde estão os ficheiros (infelizmente/felizmente como eu não tenho os ficheiros separados por pastas, não tenho de andar a abrir várias pastas, por isso não sei se este script funcionará com várias pastas.) FEITO! em EDIT3! e a quarta o local onde se vai armazenar os ficheiros (caso não seja dito, utilizasse a localização dos ficheiros por converter).

Talvez faça o script criar uma pasta para armazenar os ficheiros convertidos, para não criar muita confusão na pasta onde estão os originais. FEITO! em EDIT2

E sem mais demoras... o script 🙂

_________________________________________________________________________________________________

EDIT3: Script alterado para aceitar flags e procurar por ficheiros em várias pastas.

#!/usr/bin/python

# Created by Rolando2424 (26/5/2007)

# Use it, custom it, change it, love it, worship it

import os, sys
from optparse import OptionParser

original = "" # Will hold the original type of file
location = "" # Will hold the location of the original files
converted = "" # Will hold the converted type of file
destination = "" # Will hold the folder to place the files (if not given, it will be the same as "location"
roots_dir = [] # Will hold the folders inside "location"
files_to_convert = [] # Will hold the full path of the original files
destination_full_path = [] # Will hold the full path of the converted files

print

def main():
   """Function that will get the arguments passed by the user in the
   command line and assign those value to the matching variables, and
   execute the rest of the script"""
   global original
   global location
   global converted
   global destination
   argv = OptionParser()
   argv.add_option("-o", "--original", action = "store", type = "string",
           dest = "original", help = "Original type of file")
   argv.add_option("-c", "--converted", action = "store", type = "string",
           dest = "converted", help = "Converted type of files")
   argv.add_option("-l", "--location", action = "store", type = "string",
           dest = "location", help = "Location of the files")
   argv.add_option("-d", "--destination", action = "store", type = "string",
           dest = "destination", help = "Location of where to place the files (Optional, if not given, they will be put in --location)")
   argv.add_option("-v", "--verbose", action = "store_true", dest = "verbose",
           help = "Outputs stuff to the terminal")
   argv.add_option("-s", "--simulate", action = "store_true", dest = "simulation",
           help = "Simulation. Only prints the commands that will be sended to the terminal (No conversion).")

   (options, extra_stuff) = argv.parse_args()

   if options.verbose == True:
       verbose = True
   else:
       verbose = False

   if options.simulation == True:
       simulation = True
   else:
       simulation = False

   if verbose == True:
       print options

   try:
       original = options.original
       converted = options.converted
       location = options.location
       if original == None or converted == None or location == None: # If there isn't those three arguments, exit the script
           raise IndexError
       if location[-1] != "/":
           location = location + "/"
   except IndexError:
       print """You need to give at least the -o -c and -l for the script to work.
For more information, use the flag -h or --help.
"""
       sys.exit()

   try:
       destination = options.destination
       if destination[-1] != "/":
           destination = destination + "/"
       if destination == None: # If it's not passed, then change the value to match the one on the location variable
           raise IndexError
   except TypeError:
       destination = location
   if verbose == True:
       print "{ destination : %s}" % (destination)
       print """The original type of file is: %s
The converted type of files is: %s
The location of the files is: %s
The destination of the files is: %s
""" % (original, converted, location, destination)
       get_files_verbose(simulation)
   else:
       get_files(simulation)

   convert(simulation)

def get_files_verbose(simulate):
   """This function will get the list of files from within the "location"
   folder, while printing information to the terminal"""
   global location
   global destination
   global roots_dir
   global files_to_convert
   global converted
   for root, dir, files in os.walk(location):
       roots_dir.append(root)

   print """The folders are:
       """

   lenght_location = len(location)
   lenght_original_type = len(original)
   for dir in roots_dir:
       print dir
       files = os.listdir(dir)
       dir = dir[lenght_location:]
       if len(dir) != 0:
           dir = dir + "/"
       else:
           pass
       try:
           os.chdir(destination + dir)
       except OSError:
           if simulate == True: # No need to create the folders if it's a simulation
               pass
           else:
               os.makedirs(destination + dir)

           print """
           Creating folders!"""
       for file in files:
           if original in file:
               full_path_location =  location + dir + file
               files_to_convert.append(full_path_location)
               file = file[:-lenght_original_type] + converted
               full_path_destination = destination + dir + file
               destination_full_path.append(full_path_destination)

           else:
               pass

   print """
   The full path to the files is:
       """

   for file in files_to_convert:
       print file

   print """
   The full path to the destination of the files is:
       """

   for file in destination_full_path:
       print file

   print ""

def get_files(simulate):
   """This function will get the list of files from within the "location"
   folder"""
   global location
   global destination
   global roots_dir
   global dir
   global files_to_convert
   global converted
   for root, dir, files in os.walk(location):
       roots_dir.append(root)

   lenght_location = len(location)
   lenght_original_type = len(original)
   for dir in roots_dir:
       files = os.listdir(dir)
       dir = dir[lenght_location:]
       if len(dir) != 0:
           dir = dir + "/"
       else:
           pass
       try:
           os.chdir(destination + dir)
       except OSError:
           if simulate == True: # No need to create the folders, if it's a simulation
               pass
           else:
               os.makedirs(destination + dir)
       for file in files:
           if original in file:
               full_path_location =  location + dir + file
               files_to_convert.append(full_path_location)
               file = file[:-lenght_original_type] + converted
               full_path_destination = destination + dir + file
               destination_full_path.append(full_path_destination)

           else:
               pass

def convert(simulate):
   global files_to_convert
   global destination_full_path
   counter = 0
   for file in files_to_convert:
       if simulate == True:
           print "ffmpeg -i '%s' '%s'" % (file, destination_full_path[counter])
       else:
           os.system("ffmpeg -i '%s' '%s'" % (file, destination_full_path[counter]))
       counter = counter + 1

   sys.exit()

main()


EDIT2: Script alterado para permitir especificar uma pasta para guardar os ficheiros, caso ela não seja dita, utilizar a localização base.

#!/usr/bin/python
# Created by Rolando2424, with help from djthyrax with the loop... Thank you! At least now the script is short.

# Use it, custom it, change it, love it, worship it

import os, sys

try:
   original_type = sys.argv[1]
   converted_type = sys.argv[2]
   location = sys.argv[3]

   try:
       destiny = sys.argv[4] # Try to use the 4th argument
   except IndexError: # If it doesn't exist, then destiny is the flies location
       destiny = location
   if destiny[-1] != "/":
       destiny = destiny + "/"
   try:
       os.chdir(destiny) # Checks if directory exists
   except OSError:
       os.makedirs(destiny) # Creates folder/s, if it cannot be found

except IndexError: # If there aren't four atributes passed
   print """
Usage: ./file_converter.py original final location destiny (optional)

Where:
-> original = original extension
-> final = final extension
-> location = location of the files to be converted
-> destiny = location of where to place the converted files, otherwise they'll be put in "location"
"""
   sys.exit()

os.chdir(location) # Change to the directory in question
files = os.listdir(location) # Get list of files

os.system('clear') #Clear terminal

for f in files:
   if original_type in f:
       f = str(f)
       converted_name = destiny + f.replace(original_type, converted_type) # Create full name
       os.system('ffmpeg -i "%s" "%s"' % (f, converted_name)) # Convert!
       os.system('clear') # Clear terminal


EDIT: Modifiquei o script para permitir argumentos. Para usar o script agora, só têm de fazer ./file_converter.py tipo-original tipo.convertido pasta-dos-ficheiros.

Aqui está o novo código com o loop do Djthyrax 🙂

#!/usr/bin/python
# Created by Rolando2424, with help from djthyrax with the loop... Thank you! At least now the script is short.

# Use it, custom it, change it, love it, worship it

import os, sys

try:
   original_type = sys.argv[1]
   converted_type = sys.argv[2]
   location = sys.argv[3]

except IndexError: # If there aren't three atributes passed
   print """
Usage: ./file_converter.py original final location

Where:
-> original = original extension
-> final = final extension
-> location = location of the files to be converted
"""
   sys.exit()

os.chdir(location) # Change to the directory in question
files = os.listdir(location) # Get list of files

os.system('clear') #Clear terminal

for f in files:
   if original_type in f:
       f = str(f)
       converted_name = f.replace(original_type, converted_type) # Create the name of the converted file
       os.system('ffmpeg -i "%s" "%s"' % (f, converted_name)) # Convert!
       os.system('clear') # Clear terminal

Vou deixar aqui o código antigo 😄


i
#!/usr/bin/python
# Created by Rolando2424

# Use it, custom it, change it, love it, worship it

import os

#User configuration

original_type = "mp3" # What is the type of the original files
converted_type = "ogg" # What is the type the files will be converted

files = os.listdir("/home/rolando/Desktop/teste") # The folder where the files are

# Please don't edit below this line

name_converted = []

for f in files:
   if original_type in f:
       f = str(f)
       f = f.replace(original_type, converted_type)
       name_converted.append(f)

counter = 0
max_counter = len(name_converted)
max_counter = max_counter - 1

for n in name_converted:
   os.system('ffmpeg -i "%s" "%s"' % (files[counter], name_converted[counter]))
   counter = counter + 1

Sucks doesn't it? 😄

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

O segundo loop só tá aí a ocupar memória:

# [...] #

for f in files:
    if original_type in f:
        f = str(f)
        g = f.replace(original_type, converted_type)
        os.system('ffmpeg -i "%s" "%s"' % (f, g))
        print "Sucessfully converted %s to %s" & (f, g)

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Pois, eu sei, mas o script foi feito mesmo à pressa 😉

EDIT: Modifiquei o script com o teu loop e adicionei a hipótese de se passar argumentos.

Para usar o programa é só fazer: ./file_converter.py tipo-original tipo-convertido pasta-de-ficheiros

Vou editar o primeiro post...

#!/usr/bin/python
# Created by Rolando2424, with help from djthyrax with the loop... Thank you! At least now the script is short.

# Use it, custom it, change it, love it, worship it

import os, sys

try:
    original_type = sys.argv[1]
    converted_type = sys.argv[2]
    location = sys.argv[3]

except IndexError: # If there aren't three atributes passed
    print """
Usage: ./file_converter.py original final location

Where:
-> original = original extension
-> final = final extension
-> location = location of the files to be converted
"""
    sys.exit()

os.chdir(location) # Change to the directory in question
files = os.listdir(location) # Get list of files

os.system('clear') #Clear terminal

for f in files:
    if original_type in f:
        f = str(f)
        converted_name = f.replace(original_type, converted_type) # Create the name of the converted file
        os.system('ffmpeg -i "%s" "%s"' % (f, converted_name)) # Convert!
        os.system('clear') # Clear terminal

Até ficou mais pequeno que o outro 🙂

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

Q tal no except:

print """
usage: convert original final location

where:
-> original = original extension
-> final = final extension
-> location = location of the files to be converted
"""

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Lol, ainda vais ser tu a fazer o script 😉

IMPLANTED!

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

agora só te falta teres uma opção para definir o destino dos files convertidos 😉

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Talvez faça o script criar uma pasta para armazenar os ficheiros convertidos, para não criar muita confusão na pasta onde estão os originais.

Eu já tinha dito que tenho de ver se trabalho nisso 😉

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

O script está fixe, devias verificar se o directório de destino existe, e também não devias utilizar um chamado ao programa clear para limpar o terminal, não funciona em todas as plataformas. De resto está bem porreiro! 😉

<3 life

Posted

O script está fixe, devias verificar se o directório de destino existe,

É o que eu estive a fazer ontem até às 4 da matina, mas depois o sono começa a levar a melhor.

mas o script estava a dar-me um problema, que era na parte de criar a pasta se ela não existisse. Por exemplo se eu quisesse colocar os ficheiros na pasta /home/rolando/Desktop/teste2/converted e a pasta teste2 não existisse, ele dava um OSError (porque estava a usar o comando os.mkdir(destiny) ), e a única maneira que arranjei foi trocar isso por "os.system("mkdir -p " + destiny + "")" e com o parâmetro -p, ele vai criando todas as pastas até chegar à final 😉

YURRAH FOR THE MAN PAGES!!! ^_^

EDIT (Ainda nem postei o post mas prontos 🙂 ) : LOL pelos vistos devia de ter usado os.makedirs(destiny) em vez de os.mkdir(destiny) como estava a usar... Acho que vou remover o os.system("mkdir -p " + destiny + "") e colocar o os.makedirs(destiny).

Mais umas alteração, para caso o destino não seja especificado, utiliza-se a pasta "base" 🙂

E sem mais demoras... O dito cujo 😄

EDIT2: Agora tenho de ver se consigo fazer com que o script converta mais do que um tipo de ficheiro ao mesmo tempo 😄

_____________________________________________________________________________________________-

#!/usr/bin/python
# Created by Rolando2424, with help from djthyrax with the loop... Thank you! At least now the script is short.

# Use it, custom it, change it, love it, worship it

import os, sys

try:
    original_type = sys.argv[1]
    converted_type = sys.argv[2]
    location = sys.argv[3]
    
    try:
        destiny = sys.argv[4] # Try to use the 4th argument
    except IndexError: # If it doesn't exist, then destiny is the flies location
        destiny = location
    if destiny[-1] != "/":
        destiny = destiny + "/"
    try:
        os.chdir(destiny) # Checks if directory exists
    except OSError:
        os.makedirs(destiny) # Creates folder/s, if it cannot be found
            
except IndexError: # If there aren't four atributes passed
    print """
Usage: ./file_converter.py original final location destiny (optional)

Where:
-> original = original extension
-> final = final extension
-> location = location of the files to be converted
-> destiny = location of where to place the converted files, otherwise they'll be put in "location"
"""
    sys.exit()

os.chdir(location) # Change to the directory in question
files = os.listdir(location) # Get list of files

os.system('clear') #Clear terminal

for f in files:
    if original_type in f:
        f = str(f)
        converted_name = destiny + f.replace(original_type, converted_type) # Create full name
        os.system('ffmpeg -i "%s" "%s"' % (f, converted_name)) # Convert!
        os.system('clear') # Clear terminal

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

EDIT2: Agora tenho de ver se consigo fazer com que o script converta mais do que um tipo de ficheiro ao mesmo tempo 🙂

Isso é trabalho para a GUI que hás-de escrever 😉

Uma coisa

        converted_name = destiny.__add__("/").__add__(f.replace(original_type, converted_type)) # Create full name
#para quê estares a usar o método __add__ para aquilo? é muito mais fácil de ler assim:
        converted_name = destiny + "/" + f.replace(original_type, converted_type) # Create full name

KISS 🙂

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

LOL o GUI ainda vai demorar um bom pedaço 😄

E vou colocar fazer uma pequena modificação que me dizeste 😄

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

  • 2 months later...
Posted

Fiz uma nova versão do script ontem, sendo que agora suporta flags, e já verifica o interior das pastas pelos ficheiros.

As flags são: -o "tipo de ficheiro original", -c "Tipo de ficheiro convertido", -l "pasta onde estão os ficheiros originais", -d "pasta onde vão ser colocados os ficheiros (Opcional, se não for dado, os ficheiros vão ser colocados na localização original)", -s (simulação, não converte os ficiheiros, apenas imprime na consola o texto que vai ser enviado ao ffmpeg), -v (Verbose, imprime informação extra para a consola).

Ainda não tive muito tempo para limpar o código, mas aqui fica ele.

#!/usr/bin/python

# Created by Rolando2424 (26/5/2007)

# Use it, custom it, change it, love it, worship it

import os, sys
from optparse import OptionParser

original = "" # Will hold the original type of file
location = "" # Will hold the location of the original files
converted = "" # Will hold the converted type of file
destination = "" # Will hold the folder to place the files (if not given, it will be the same as "location"
roots_dir = [] # Will hold the folders inside "location"
files_to_convert = [] # Will hold the full path of the original files
destination_full_path = [] # Will hold the full path of the converted files

print 

def main():
    """Function that will get the arguments passed by the user in the
    command line and assign those value to the matching variables, and
    execute the rest of the script"""
    global original
    global location
    global converted
    global destination
    argv = OptionParser()
    argv.add_option("-o", "--original", action = "store", type = "string",
            dest = "original", help = "Original type of file")
    argv.add_option("-c", "--converted", action = "store", type = "string",
            dest = "converted", help = "Converted type of files")
    argv.add_option("-l", "--location", action = "store", type = "string",
            dest = "location", help = "Location of the files")
    argv.add_option("-d", "--destination", action = "store", type = "string",
            dest = "destination", help = "Location of where to place the files (Optional, if not given, they will be put in --location)")
    argv.add_option("-v", "--verbose", action = "store_true", dest = "verbose",
            help = "Outputs stuff to the terminal")
    argv.add_option("-s", "--simulate", action = "store_true", dest = "simulation",
            help = "Simulation. Only prints the commands that will be sended to the terminal (No conversion).")
    
    (options, extra_stuff) = argv.parse_args()
    
    if options.verbose == True:
        verbose = True
    else:
        verbose = False

    if options.simulation == True:
        simulation = True
    else:
        simulation = False
    
    if verbose == True:
        print options
    
    try:
        original = options.original
        converted = options.converted
        location = options.location
        if original == None or converted == None or location == None: # If there isn't those three arguments, exit the script
            raise IndexError
        if location[-1] != "/":
            location = location + "/"
    except IndexError:
        print """You need to give at least the -o -c and -l for the script to work.
For more information, use the flag -h or --help.
"""
        sys.exit()
    
    try:
        destination = options.destination
        if destination[-1] != "/":
            destination = destination + "/"
        if destination == None: # If it's not passed, then change the value to match the one on the location variable
            raise IndexError
    except TypeError:
        destination = location
    if verbose == True:
        print "{ destination : %s}" % (destination)
        print """The original type of file is: %s
The converted type of files is: %s
The location of the files is: %s
The destination of the files is: %s
""" % (original, converted, location, destination)
        get_files_verbose(simulation)
    else:
        get_files(simulation)

    convert(simulation)

def get_files_verbose(simulate):
    """This function will get the list of files from within the "location"
    folder, while printing information to the terminal"""
    global location
    global destination
    global roots_dir
    global files_to_convert
    global converted
    for root, dir, files in os.walk(location):
        roots_dir.append(root)

    print """The folders are:
        """
    
    lenght_location = len(location)
    lenght_original_type = len(original)
    for dir in roots_dir:
        print dir
        files = os.listdir(dir)
        dir = dir[lenght_location:]
        if len(dir) != 0:
            dir = dir + "/"
        else:
            pass
        try:
            os.chdir(destination + dir)
        except OSError:
            if simulate == True: # No need to create the folders if it's a simulation
                pass
            else:
                os.makedirs(destination + dir)

            print """
            Creating folders!"""
        for file in files:
            if original in file:
                full_path_location =  location + dir + file
                files_to_convert.append(full_path_location)
                file = file[:-lenght_original_type] + converted
                full_path_destination = destination + dir + file
                destination_full_path.append(full_path_destination)
            
            else:
                pass

    print """
    The full path to the files is:
        """
    
    for file in files_to_convert:
        print file

    print """
    The full path to the destination of the files is:
        """

    for file in destination_full_path:
        print file
    
    print ""

def get_files(simulate):
    """This function will get the list of files from within the "location"
    folder"""
    global location
    global destination
    global roots_dir
    global dir
    global files_to_convert
    global converted
    for root, dir, files in os.walk(location):
        roots_dir.append(root)

    lenght_location = len(location)
    lenght_original_type = len(original)
    for dir in roots_dir:
        files = os.listdir(dir)
        dir = dir[lenght_location:]
        if len(dir) != 0:
            dir = dir + "/"
        else:
            pass
        try:
            os.chdir(destination + dir)
        except OSError:
            if simulate == True: # No need to create the folders, if it's a simulation
                pass
            else:
                os.makedirs(destination + dir)
        for file in files:
            if original in file:
                full_path_location =  location + dir + file
                files_to_convert.append(full_path_location)
                file = file[:-lenght_original_type] + converted
                full_path_destination = destination + dir + file
                destination_full_path.append(full_path_destination)
            
            else:
                pass

def convert(simulate):
    global files_to_convert
    global destination_full_path
    counter = 0
    for file in files_to_convert:
        if simulate == True:
            print "ffmpeg -i '%s' '%s'" % (file, destination_full_path[counter])
        else:
            os.system("ffmpeg -i '%s' '%s'" % (file, destination_full_path[counter]))
        counter = counter + 1

    sys.exit()

main()

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

Thanks, já vi o que queria. rolando2424, acho que vou fazer um port do teu script para PHP 😛

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Podes dar uma lista de formatos que isto consegue converter?

Segundo a Wikipedia:

The FFmpeg developers have reverse-engineered and/or reimplemented, among others:

    * The Sorenson 3 Codec used by many QuickTime movies

    * ASF, and thereby the original version of DivX

    * ATRAC3[2]

    * H.261,[2] H.263[2] and h.264/MPEG-4 AVC[2]

    * Indeo 2 and 3[2]

    * Windows Media Audio

    * Windows Media Video

    * QDesign Music Codec 2, used by many QuickTime movies prior to QuickTime 7.

    * VP5[2] and VP6[2]

    * Truespeech

The default MPEG-4 codec used by FFmpeg for encoding has the FourCC of FMP4.

EDIT: Lol, não tinha visto que havia uma segunda página...

djthyrax, força, faz o port 😉

Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄

Posted

djthyrax, força, faz o port 😉

Vai ficar para depois de outra coisa que tenho em mente 😛

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.