Skip to content

Instantly share code, notes, and snippets.

@chowse
Created January 26, 2011 04:11
Show Gist options
  • Save chowse/796214 to your computer and use it in GitHub Desktop.
Save chowse/796214 to your computer and use it in GitHub Desktop.
Simple video embed generation (YouTube and Vimeo)
import re
def url_to_embed(url, **kwargs):
for regex, embed_url in EMBED_PATTERNS:
m = regex.match(url)
if m:
args = dict(DEFAULT_ARGS)
args.update(kwargs)
args['url'] = embed_url % m.groupdict()
return EMBED_CODE % args
return None
# YouTube embeds
YOUTUBE_URL_RE = re.compile('''
^ # start
http:// # schema
(?:www\\.)? # optional www.
youtube\\.com/watch\? # domain + path
(?:.*?&)*? # optional leading params (except v=)
v=(?P<id>\w+) # v=<video id>
(&.*)? # optional trailing params
$ # end
''', re.VERBOSE)
YOUTUBE_EMBED_URL = 'http://www.youtube.com/embed/%(id)s'
# Vimeo embeds
VIMEO_URL_RE = re.compile('''
^ # start
http:// # schema
(?:www\\.)? # optional www.
vimeo\\.com/ # domain + path
(?P<id>\d+) # <video id>
(\?.*)? # optional params
$ # end
''', re.VERBOSE)
VIMEO_EMBED_URL = 'http://player.vimeo.com/video/%(id)s'
# All embed patterns
EMBED_PATTERNS = (
(YOUTUBE_URL_RE, YOUTUBE_EMBED_URL),
(VIMEO_URL_RE, VIMEO_EMBED_URL)
)
# Embed code
EMBED_CODE = '<iframe type="text/html" width="%(width)d" height="%(height)d" src="%(url)s" frameborder="0"></iframe>'
DEFAULT_ARGS = { 'width': 400, 'height': 300 }
if __name__ == '__main__':
while True:
print
print 'Enter a video URL:'
url = raw_input().strip()
if not url: break
embed = url_to_embed(url, width=640, height=480)
if embed:
print 'Embed code:'
print embed
else:
print 'Unrecognized URL'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment