main.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/python2
  2. #
  3. # Author: Arnau Sanchez <pyarnau@gmail.com>
  4. # 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 locale
  17. import optparse
  18. import collections
  19. import youtube_upload.auth
  20. import youtube_upload.upload_video
  21. import youtube_upload.categories
  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. VERSION = "0.8.0"
  30. EXIT_CODES = {
  31. OptionsMissing: 2,
  32. InvalidCategory: 3,
  33. }
  34. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  35. def to_utf8(s):
  36. """Re-encode string from the default system encoding to UTF-8."""
  37. current = locale.getpreferredencoding()
  38. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  39. def debug(obj, fd=sys.stderr):
  40. """Write obj to standard error."""
  41. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  42. if isinstance(obj, unicode) else obj)
  43. fd.write(string + "\n")
  44. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  45. """
  46. Catch exceptions on fun(*args, **kwargs) and return the exit code specified
  47. in the exit_codes dictionary. Return 0 if no exception is raised.
  48. """
  49. try:
  50. fun(*args, **kwargs)
  51. return 0
  52. except tuple(exit_codes.keys()) as exc:
  53. debug("[%s] %s" % (exc.__class__.__name__, exc))
  54. return exit_codes[exc.__class__]
  55. def get_encoding(fd):
  56. """Guess terminal encoding."""
  57. return fd.encoding or locale.getpreferredencoding()
  58. def compact(it):
  59. """Filter false (in the truth sense) elements in iterator."""
  60. return filter(bool, it)
  61. def tosize(seq, size):
  62. """Return list of fixed length from sequence."""
  63. return seq[:size] if len(seq) >= size else (seq + [None] * (size-len(seq)))
  64. def first(it):
  65. """Return first element in iterable."""
  66. return it.next()
  67. def get_progress_info():
  68. """Return a function callback to update the progressbar."""
  69. def _callback(total_size, completed):
  70. if not hasattr(bar, "next_update"):
  71. bar.maxval = total_size
  72. bar.start()
  73. bar.update(completed)
  74. build = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  75. if progressbar:
  76. widgets = [
  77. progressbar.Percentage(), ' ',
  78. progressbar.Bar(), ' ',
  79. progressbar.ETA(), ' ',
  80. progressbar.FileTransferSpeed(),
  81. ]
  82. bar = progressbar.ProgressBar(widgets=widgets)
  83. return build(callback=_callback, finish=bar.finish)
  84. else:
  85. return build(callback=lambda *args: True, finish=lambda: True)
  86. def string_to_dict(string):
  87. """Return dictionary from string "key1=value1, key2=value2"."""
  88. pairs = [s.strip() for s in (string or "").split(",")]
  89. return dict(pair.split("=") for pair in pairs)
  90. def get_category_id(category):
  91. """Return category ID from its name."""
  92. if category:
  93. if category in youtube_upload.categories.IDS:
  94. return str(youtube_upload.categories.IDS[category])
  95. else:
  96. msg = "{} is not a valid category".format(category)
  97. raise InvalidCategory(msg)
  98. def upload_video(youtube, options, video_path, total_videos, index):
  99. """Upload video with index (for split videos)."""
  100. title = to_utf8(options.title)
  101. description = to_utf8(options.description or "").decode("string-escape")
  102. ns = dict(title=title, n=index+1, total=total_videos)
  103. complete_title = \
  104. (options.title_template.format(**ns) if total_videos > 1 else title)
  105. progress = get_progress_info()
  106. category_id = get_category_id(options.category)
  107. body = {
  108. "snippet": {
  109. "title": complete_title,
  110. "tags": map(str.strip, (options.tags or "").split(",")),
  111. "description": description,
  112. "categoryId": category_id,
  113. },
  114. "status": {
  115. "privacyStatus": options.privacy
  116. },
  117. "recordingDetails": {
  118. "location": string_to_dict(options.location),
  119. },
  120. }
  121. debug("Start upload: {} ({})".format(video_path, complete_title))
  122. video_id = youtube_upload.upload_video.upload(youtube, video_path, body,
  123. progress_callback=progress.callback, chunksize=16*1024)
  124. progress.finish()
  125. return video_id
  126. def run_main(parser, options, args, output=sys.stdout):
  127. """Run the main scripts from the parsed options/args."""
  128. required_options = ["title"]
  129. missing = [opt for opt in required_options if not getattr(options, opt)]
  130. if missing:
  131. parser.print_usage()
  132. msg = "Some required option are missing: %s" % ", ".join(missing)
  133. raise OptionsMissing(msg)
  134. default_client_secrets = \
  135. os.path.join(sys.prefix, "share/youtube_upload/client_secrets.json")
  136. home = os.path.expanduser("~")
  137. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  138. client_secrets = options.client_secrets or default_client_secrets
  139. credentials = options.credentials_file or default_credentials
  140. debug("Using client secrets: {}".format(client_secrets))
  141. debug("Using credentials file: {}".format(credentials))
  142. youtube = youtube_upload.auth.get_resource(client_secrets, credentials)
  143. for index, video_path in enumerate(args):
  144. video_id = upload_video(youtube, options, video_path, len(args), index)
  145. video_url = WATCH_VIDEO_URL.format(id=video_id)
  146. debug("Video URL: {}".format(video_url))
  147. output.write(video_id + "\n")
  148. def main(arguments):
  149. """Upload videos to Youtube."""
  150. usage = """Usage: %prog [OPTIONS] VIDEO_PATH [VIDEO_PATH2 ...]
  151. Upload videos to youtube."""
  152. parser = optparse.OptionParser(usage, version=VERSION)
  153. # Required options
  154. parser.add_option('-t', '--title', dest='title', type="string",
  155. help='Video(s) title')
  156. parser.add_option('-c', '--category', dest='category', type="string",
  157. help='Video(s) category')
  158. # Optional options
  159. parser.add_option('-d', '--description', dest='description', type="string",
  160. help='Video(s) description')
  161. parser.add_option('', '--tags', dest='tags', type="string",
  162. help='Video(s) tags (separated by commas: tag1,tag2,...)')
  163. parser.add_option('', '--title-template', dest='title_template',
  164. type="string", default="{title} [{n}/{total}]", metavar="STRING",
  165. help='Template for multiple videos (default: {title} [{n}/{total}])')
  166. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  167. default="public", help='Privacy status (public | unlisted | private)')
  168. parser.add_option('', '--location', dest='location', type="string",
  169. default=None, metavar="latitude=VAL, longitude=VAL, altitude=VAL",
  170. help='Video(s) location"')
  171. # Authentication
  172. parser.add_option('', '--client-secrets', dest='client_secrets',
  173. type="string", help='Client secrets JSON file')
  174. parser.add_option('', '--credentials-file', dest='credentials_file',
  175. type="string", help='Client secrets JSON file')
  176. options, args = parser.parse_args(arguments)
  177. run_main(parser, options, args)
  178. if __name__ == '__main__':
  179. sys.exit(catch_exceptions(EXIT_CODES, main, sys.argv[1:]))