util.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import datetime
  2. import humanize
  3. import re
  4. # given amount of seconds makes it into this 54 MINUTES AND 53 SECONDS (from humanize) then
  5. # perform a bunch of replace operations to make it look like 54mins. 53secs.
  6. def getHumanizedTimeString(seconds):
  7. return humanize.precisedelta(
  8. datetime.timedelta(seconds=seconds)).upper(). \
  9. replace(" month".upper(), "m.").replace(" months".upper(), "m.").replace(" days".upper(), "d.").replace(
  10. " day".upper(), "d.").replace(" hours".upper(), "hrs.").replace(" hour".upper(), "hr.").replace(
  11. " minutes".upper(), "mins.").replace(" minute".upper(), "min.").replace(
  12. "and".upper(), "").replace(" seconds".upper(), "secs.").replace(" second".upper(), "sec.").replace(",", "")
  13. # input => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", ..., "100"] <- array of 100 video ids
  14. # output => ["1,2,3,4,...,50", "51,52,53,...,100"] <- array of 2 video id strings, each with upto 50 comma sperated video ids
  15. def getVideoIdsStrings(video_ids):
  16. output = []
  17. i = 0
  18. while i < len(video_ids):
  19. output.append(",".join(video_ids[i:i + 50]))
  20. i += 50
  21. return output
  22. # input: array of youtube video duration strings => ["24M23S", "2H2M2S", ...]
  23. # output:integer => seconds
  24. def calculateDuration(vid_durations):
  25. hours_pattern = re.compile(r'(\d+)H')
  26. minutes_pattern = re.compile(r'(\d+)M')
  27. seconds_pattern = re.compile(r'(\d+)S')
  28. total_seconds = 0
  29. for duration in vid_durations:
  30. hours = hours_pattern.search(duration) # returns matches in the form "24H"
  31. mins = minutes_pattern.search(duration) # "24M"
  32. secs = seconds_pattern.search(duration) # "24S"
  33. hours = int(hours.group(1)) if hours else 0 # returns 24
  34. mins = int(mins.group(1)) if mins else 0
  35. secs = int(secs.group(1)) if secs else 0
  36. video_seconds = datetime.timedelta(
  37. hours=hours,
  38. minutes=mins,
  39. seconds=secs
  40. ).total_seconds()
  41. total_seconds += video_seconds
  42. return total_seconds
  43. def getThumbnailURL(thumbnails):
  44. priority = ("maxres", "standard", "high", "medium", "default")
  45. for quality in priority:
  46. if quality in thumbnails:
  47. return thumbnails[quality]["url"]
  48. return ''
  49. # generates a message in the form of "1 / 19 watched! 31mins. 15secs. left to go!"
  50. def generateWatchingMessage(playlist):
  51. """
  52. This is the message that will be seen when a playlist is set to watching.
  53. Takes in the playlist object and calculates the watch time left by looping over unwatched video
  54. and using their durations
  55. """
  56. pass