import re
import requests
import shutil
import time


def url_to_frames(url):
    """given a url, get a list of timestamped frames"""
    r = requests.get(url)
    match = re.search('\"storyboard_spec\":\"([^\"]*)\"', str(r.content)).group(1).replace('\\\\', '')
    sighs = re.findall('\$M#([^\|$]+)(?:\||$)', match)
    base_url = match[:match.find('|')] + '?sigh=$S'

    l_value = len(sighs)
    sigh = sighs[-1]
    m_value = 0

    base_url = base_url.replace('$L', str(l_value)).replace('$S', sigh)

    while True:
        mosaic_url = base_url.replace('$N', 'M{}'.format(m_value))

        r = requests.get(mosaic_url, stream=True)
        if r.status_code != 200:
            print('failed on m_value={}'.format(m_value))
            break

        with open('mosaics/L{}_M{}_{}'.format(l_value, m_value, sigh), 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

        time.sleep(0.5)

        m_value += 1

    # print(re.search('\$M#', match).pos) # do not work. but we want all positions where this happens
    print(base_url) # replace $L with the l-number, $N with 'M0', 'M1', etc, and add '?sigh=' + the matched thing from above


if __name__ == '__main__':
    url = 'https://www.youtube.com/watch?v=OvXHbJzWMqI'
    url_to_frames(url)

@@ -30,26 +30,58 @@
 ort 
-shutil%0Aimport time
+time%0A%0Afrom PIL import Image%0Afrom io import BytesIO
 %0A%0A%0Ad
@@ -532,16 +532,71 @@
  sigh)%0A%0A
+    imgs = %7B%7D%0A    img_keys = %5B%5D%0A%0A    # get all mosaics%0A
     whil
@@ -669,16 +669,93 @@
 _value))
+%0A        img_keys.append('mosaics/L%7B%7D_M%7B%7D_%7B%7D'.format(l_value, m_value, sigh))
 %0A%0A      
@@ -860,23 +860,23 @@
 iled on 
-m_value
+img_key
 =%7B%7D'.for
@@ -871,39 +871,44 @@
 _key=%7B%7D'.format(
-m_value
+img_keys%5B-1%5D
 ))%0A            b
@@ -917,95 +917,8 @@
 ak%0A%0A
-        with open('mosaics/L%7B%7D_M%7B%7D_%7B%7D'.format(l_value, m_value, sigh), 'wb') as f:%0A    
     
@@ -961,39 +961,45 @@
     
-    shutil.copyfileobj
+imgs%5Bimg_keys%5B-1%5D%5D = Image.open
 (r.raw
-, f
 )%0A%0A 
@@ -1024,258 +1024,93 @@
 0.5)
-%0A%0A        m_value += 1%0A%0A    # print(re.search('%5C$M#', match).pos) # do not work. but we want all positions where this happens%0A    print(base_url) # replace $L with the l-number, $N with 'M0', 'M1', etc, and add '?sigh=' + the matched thing from above
+ # do not set off youtube's firewall%0A        m_value += 1%0A%0A    return img_keys, imgs%0A
 %0A%0A%0Ai

load images into memory