main.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/python2
  2. #
  3. # Author: Arnau Sanchez <pyarnau@gmail.com>
  4. # Project site: https://github.com/tokland/youtube-upload
  5. """
  6. Upload a video to Youtube from the command-line.
  7. $ youtube-upload --title="A.S. Mutter playing" \
  8. --description="Anne Sophie Mutter plays Beethoven" \
  9. --category=Music \
  10. --tags="mutter, beethoven" \
  11. anne_sophie_mutter.flv
  12. www.youtube.com/watch?v=pxzZ-fYjeYs
  13. """
  14. import os
  15. import sys
  16. import optparse
  17. import collections
  18. import youtube_upload.auth
  19. import youtube_upload.upload_video
  20. import youtube_upload.categories
  21. import youtube_upload.lib as lib
  22. # http://code.google.com/p/python-progressbar (>= 2.3)
  23. try:
  24. import progressbar
  25. except ImportError:
  26. progressbar = None
  27. class InvalidCategory(Exception): pass
  28. class OptionsMissing(Exception): pass
  29. EXIT_CODES = {
  30. OptionsMissing: 2,
  31. InvalidCategory: 3,
  32. }
  33. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  34. debug = lib.debug
  35. def get_progress_info():
  36. """Return a function callback to update the progressbar."""
  37. build = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  38. if progressbar:
  39. widgets = [
  40. progressbar.Percentage(), ' ',
  41. progressbar.Bar(), ' ',
  42. progressbar.ETA(), ' ',
  43. progressbar.FileTransferSpeed(),
  44. ]
  45. bar = progressbar.ProgressBar(widgets=widgets)
  46. def _callback(total_size, completed):
  47. if not hasattr(bar, "next_update"):
  48. bar.maxval = total_size
  49. bar.start()
  50. bar.update(completed)
  51. return build(callback=_callback, finish=bar.finish)
  52. else:
  53. return build(callback=None, finish=lambda: True)
  54. def get_category_id(category):
  55. """Return category ID from its name."""
  56. if category:
  57. if category in youtube_upload.categories.IDS:
  58. return str(youtube_upload.categories.IDS[category])
  59. else:
  60. msg = "{0} is not a valid category".format(category)
  61. raise InvalidCategory(msg)
  62. def upload_video(youtube, options, video_path, total_videos, index):
  63. """Upload video with index (for split videos)."""
  64. title = lib.to_utf8(options.title)
  65. description = lib.to_utf8(options.description or "").decode("string-escape")
  66. ns = dict(title=title, n=index+1, total=total_videos)
  67. complete_title = \
  68. (options.title_template.format(**ns) if total_videos > 1 else title)
  69. progress = get_progress_info()
  70. category_id = get_category_id(options.category)
  71. body = {
  72. "snippet": {
  73. "title": complete_title,
  74. "tags": map(str.strip, (options.tags or "").split(",")),
  75. "description": description,
  76. "categoryId": category_id,
  77. },
  78. "status": {
  79. "privacyStatus": options.privacy
  80. },
  81. "recordingDetails": {
  82. "location": lib.string_to_dict(options.location),
  83. },
  84. }
  85. debug("Start upload: {0} ({1})".format(video_path, complete_title))
  86. video_id = youtube_upload.upload_video.upload(youtube, video_path, body,
  87. progress_callback=progress.callback, chunksize=16*1024)
  88. progress.finish()
  89. return video_id
  90. def run_main(parser, options, args, output=sys.stdout):
  91. """Run the main scripts from the parsed options/args."""
  92. required_options = ["title"]
  93. missing = [opt for opt in required_options if not getattr(options, opt)]
  94. if missing:
  95. parser.print_usage()
  96. msg = "Some required option are missing: %s" % ", ".join(missing)
  97. raise OptionsMissing(msg)
  98. default_client_secrets = \
  99. os.path.join(sys.prefix, "share/youtube_upload/client_secrets.json")
  100. home = os.path.expanduser("~")
  101. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  102. client_secrets = options.client_secrets or default_client_secrets
  103. credentials = options.credentials_file or default_credentials
  104. debug("Using client secrets: {0}".format(client_secrets))
  105. debug("Using credentials file: {0}".format(credentials))
  106. youtube = youtube_upload.auth.get_resource(client_secrets, credentials)
  107. for index, video_path in enumerate(args):
  108. video_id = upload_video(youtube, options, video_path, len(args), index)
  109. video_url = WATCH_VIDEO_URL.format(id=video_id)
  110. debug("Video URL: {0}".format(video_url))
  111. output.write(video_id + "\n")
  112. def main(arguments):
  113. """Upload videos to Youtube."""
  114. usage = """Usage: %prog [OPTIONS] VIDEO_PATH [VIDEO_PATH2 ...]
  115. Upload videos to youtube."""
  116. parser = optparse.OptionParser(usage)
  117. # Video metadata
  118. parser.add_option('-t', '--title', dest='title', type="string",
  119. help='Video(s) title')
  120. parser.add_option('-c', '--category', dest='category', type="string",
  121. help='Video(s) category')
  122. parser.add_option('-d', '--description', dest='description', type="string",
  123. help='Video(s) description')
  124. parser.add_option('', '--tags', dest='tags', type="string",
  125. help='Video(s) tags (separated by commas: tag1,tag2,...)')
  126. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  127. default="public", help='Privacy status (public | unlisted | private)')
  128. parser.add_option('', '--location', dest='location', type="string",
  129. default=None, metavar="latitude=VAL, longitude=VAL, altitude=VAL",
  130. help='Video(s) location"')
  131. parser.add_option('', '--title-template', dest='title_template',
  132. type="string", default="{title} [{n}/{total}]", metavar="STRING",
  133. help='Template for multiple videos (default: {title} [{n}/{total}])')
  134. # Authentication
  135. parser.add_option('', '--client-secrets', dest='client_secrets',
  136. type="string", help='Client secrets JSON file')
  137. parser.add_option('', '--credentials-file', dest='credentials_file',
  138. type="string", help='Client secrets JSON file')
  139. options, args = parser.parse_args(arguments)
  140. run_main(parser, options, args)
  141. if __name__ == '__main__':
  142. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))