Posts Tagged ‘python’

Download multiple youtube videos + Linux Python code

November 10, 2007

For those of you who like downloading videos from youtube.com, I made a simple Python code so you guys can download as many as you like at the same time.

For those of you who don’t know how to download videos from youtube.com yet,here’s a simple guide:

In youtube.com’s page, copy the url of the video you want to download, shown here encircled in red, for example:

youtube-page-url.png

Then create a text file in this format:

<youtube video url 1>,<filename1>

<youtube video url 2>,<filename2>

for example:

http://youtube.com/watch?v=skwY-Uij19U,mgs3 full story part1
http://youtube.com/watch?v=9thb0F98OOg,mgs3 full story part2

Place all the video urls you want to download at the same time (including the filename of the videos) in that text file. Remember to press the Return (Enter) button after every url/filename line on the text file. The video url and video filename you want for the file should be separated only by a single comma. The white spaces in the video filename you’ll give will be transformed into underscores (e.g. “video 1 part – 1” becomes “video_1_part_-_1”).

To run the program I made type

 ./dl-youtube.py  --file=<text file with youtube video url>

Anyway, there’s a help message included.

The code also assumes you have youtube-dl (found here) code in your $PATH. Copy/download the youtube-dl code and save it on your PC. You can just do a

 chmod 775 youtube-dl

to make the code executable. Then copy it to, say, your bin folder (which is in your $PATH by default):

 cp -v youtube-dl /usr/bin

Here’s the code:

#!/usr/bin/python
try:
	import commands, os, sys, string, getopt
except ImportError, msg1:
	exit(msg1)

try:
	options, xarguments = getopt.getopt(sys.argv[1:],'h', ['file=','version'])
except getopt.error:
	print "Error: You tried to use an unknown option or the argument for an option that requires it was missing. Try `dl-youtube.py -h' for more information."
	sys.exit(0)

def isempty(self) :
    return (len(self) == 0) 

def help_message():
	print '''This program assumes youtube-dl is in $PATH. You basically create a text file containing all the youtube videos that you want to download in this format:
	,video_title
	e.g.
	
	
	The title and the link must be separated by a single comma only, as seen from the example above.
	Options:
	-h		displays this help message
	--file=		give the text file containing the formatted ,
	--version	displays Python version
'''
	sys.exit(0)

def youtubedl(dl_list):
	try:
#change my_proxy to whatever proxy you want to use. If you don't want any, just delete the line after this.
		os.system("export http_proxy=my_proxy")
		file = open(dl_list,"r")
		lines = file.readlines()
		for x in lines:
			lnknme = x.split(",")
			namae = lnknme[1][:-1].replace(' ',"_")
#replace username and passwd with your youtube username and password. If you don't have any, just remove this part: '-u username -p passwd'
			os.system("youtube-dl -u username -p passwd -o "+namae+".flv "+lnknme[0])
			print namae
	except ValueError, msg:
		exit(msg)
	file.close()

if isempty(options):
	help_message()

for a in options[:]:
    if a[0] == '-h':
        help_message()

for a in options[:]:
	if a[0] == '--file' and a[1] != '':
		youtubedl(a[1])
		options.remove(a)
		break
	elif a[0] == '--file' and a[1] == '':
		print '--file expects an argument'
		sys.exit(0)

for a in options[:]:
    if a[0] == '--version':
        print 'dl-youtube.py version 1.0'
        sys.exit(0)

If you have comments/suggestion/questions, please feel free to post and ask them.

You can download the source code as an odt file here=>dl-youtube.odt

Remember to save it as a text file with a .py extension for the Python interpreter. Unfortunately, WordPress only accepts jpg, jpeg, png, gif, pdf, doc, ppt, and odt for file uploads so I wasn’t able to upload the dl-youtube.py code. Just be sure to remember that indention is very important to Python.

Or better yet, if you don’t want to download the source code, you can view this page’s source code (in Firefox, right-click page then click View Page Source) and just copy the original and correct code with proper indentions, to a text editor, and save it with a .py extension.

How to join avi files + python automation code

August 16, 2007

I downloaded videos from rapidshare.com, but like most large file size videos there, the videos I got were split into parts. This is because rapidshare.com has a file size upload limit of 250 MB AFAIK.

So I needed some way to join my avi files which I got from rapidshare.com. I think I could’ve lived with the fact that I can just let my avi videos be, without joining file1.avi.part1 to file1.avi.part2 together, for example. All I would’ve done is create a playlist of my split avi files and play them consecutively using MPlayer or VLC for example. I wouldn’t really care if there was a 1 second gap between the playback of file1.avi.part1 and file1.avi.part2. The problem was, I can only play file1.avi.part1 and not file1.avi.part2. This was a real pain since I wanted to watch the whole video/s.

The solution? Home grown in Linux (^)__(^)

Well, actually we need the

cat

command and we need

mencoder

installed. These shouldn’t be a problem nowadays.

For those out there who only want to join a few videos together, the first step is to issue this simple command:

$cat file1.avi.part1 file1.avi.part2 > file1.avi

where file1.avi is the temporary file which combines file1.avi.part1 and file1.avi.part2. But we’re not done yet, as the audio and video might not sync coming from file1.avi.part1 to file1.avi.part2. You can use

cat

on as many files as you want or on as many as your PC can accommodate btw.
What we do is this:

$ mencoder -forceidx -oac copy -ovc copy file1.avi -o file1_final.avi

in case you don’t trust me, you can always consult your man page (^)__(^)
The previous command synchronizes the audio and the video of file1.avi by streamcopying its audio and video into file1_final.avi.
And that should be it! Now you (and me) have a single contiguous file which you (or me) can watch.
But for users out there who mind all the typing, since they’ve got several avi files to join together, I’ve made a python program for you guys:

#! /usr/bin/python

try:
	import commands, os, sys, string, getopt
except ImportError, msg1:
	exit(msg1)

def help_message():
    print '''This program joins split avi files. The file names of the split avi files to be joined should be in the manner:
	(filename1).avi.part1, (filename1).avi.part2,...
	or
	(filename1).avi.001, (filename1).avi.002,...
	The point is, the filenames are separated by '.' from their file (avi) type extension. The final combined video has the format (filename1)_final.avi.
	This program also assumes there are at least 2 split files you want to join in a single file. Otherwise, it will just copy the single avi file into (filename1)_final.avi.
	A MEncoder installation is required.
    Options:
	-h		displays this help message
	--file=		expects a file containing the list of avi files to be joined
	--version	displays Python version

       e.g. To join avi files in the current directory, listed in split_files.txt:
	 join_avi.py --file=split_files.txt'''
    sys.exit(0)

def getFilenames(split_list):
	file = open(split_list, "r")
	lines = file.readlines()
	try:
		i=True
		for filename in lines:
			namae = filename.split(".")
			if i == True:
				os.system("cat "+namae[0]+"* > _"+namae[0]+"_.avi")
				os.system("mencoder -forceidx -oac copy -ovc copy _"+ namae[0]+"_.avi -o _"+namae[0]+"_final.avi")
				os.system("rm _"+namae[0]+"_.avi")
				i = False
			if i == False:
				if os.system("ls "+namae[0]+"*"):
					i = False
				else:
					i = True
	except ValueError, msg:
		exit(msg)
	file.close()

def isempty(self) :
    return (len(self) == 0) 

try:
	options, xarguments = getopt.getopt(sys.argv[1:],'ha', ['file=','version'])
except getopt.error:
	print "Error: You tried to use an unknown option or the argument for an option that requires it was missing. Try `options.py -h' for more information."
	sys.exit(0)

if isempty(options):
	help_message()

for a in options[:]:
    if a[0] == '-h':
        help_message()

for a in options[:]:
	if a[0] == '--file' and a[1] != '':
		getFilenames(a[1])
		options.remove(a)
		break
	elif a[0] == '--file' and a[1] == '':
		print '--file expects an argument'
		sys.exit(0)

for a in options[:]:
    if a[0] == '--version':
        print 'join_avi.py version 0.5'
        sys.exit(0)

If you have comments/suggestion/questions, please feel free to post and ask them.

You may also download the python source code from above here=> join_avi.odt. Just remember to save it as a text file with a .py extension for the Python interpreter. Unfortunately, WordPress only accepts jpg, jpeg, png, gif, pdf, doc, ppt, and odt for file uploads so I wasn’t able to upload the join_avi.py code.

Just be sure to remember that indention is very important to Python. If you don’t want to download the source code, you can view this page’s source code (in Firefox, right-click page then click View Page Source) and just copy the original and correct code with proper indentions, to a text editor, and save it with a .py extension.