Advertisement
blueshiftlabs

CFB Emote Pack Generator

Nov 2nd, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.15 KB | None | 0 0
  1. import csv
  2. import os
  3. import requests
  4. import sh
  5. import shutil
  6. import sys
  7. import zipfile
  8.  
  9. SESSION = requests.Session()
  10.  
  11. def get_image_cached(filename, size=60):
  12.     cache_directory = os.path.join("cache", "full%d" % size)
  13.     if not os.path.exists(cache_directory):
  14.         os.makedirs(cache_directory)
  15.    
  16.     cache_filename = os.path.join(cache_directory, filename + ".png")
  17.    
  18.     if os.path.exists(cache_filename):
  19.         print "Cache hit: %s" % cache_filename
  20.         return cache_filename
  21.    
  22.     try:
  23.         url = (u"https://flair.redditcfb.com/full%d/%s.png"
  24.                % (size, filename))
  25.         print "Downloading %s..." % url
  26.         req = SESSION.get(url)
  27.         req.raise_for_status()
  28.         with open(cache_filename, 'wb') as fd:
  29.             for chunk in req.iter_content(64*1024):
  30.                 fd.write(chunk)
  31.             orig_size = fd.tell()
  32.        
  33.         print "Downloaded %d bytes." % orig_size
  34.  
  35.         try:
  36.             sh.pngout("/y", cache_filename, _ok_code=[0,1,2])
  37.         except sh.CommandNotFound:
  38.             pass
  39.  
  40.         try:
  41.             sh.optipng("-o7", cache_filename)
  42.         except sh.CommandNotFound:
  43.             pass
  44.        
  45.         new_size = os.path.getsize(cache_filename)
  46.         size_delta = orig_size - new_size
  47.         size_delta_percent = (size_delta * 100.0) / orig_size
  48.         print ("Optimized to %d bytes. Saved %d bytes (%.1f%%)."
  49.                % (new_size, size_delta, size_delta_percent))
  50.    
  51.         return cache_filename
  52.    
  53.     except Exception as e:
  54.         stdout = getattr(e, 'stdout')
  55.         if stdout:
  56.             print stdout
  57.            
  58.         try:
  59.             os.remove(cache_filename)
  60.         except OSError:
  61.             pass
  62.            
  63.         raise
  64.        
  65. def read_utf8_csv(csvfile, *args, **kwargs):
  66.     reader = csv.DictReader(csvfile, *args, **kwargs)
  67.     for row in reader:
  68.         yield { k: unicode(v, 'utf-8') for (k, v) in row.iteritems() }
  69.  
  70. def remake_all_dirs():
  71.     for dirname in ('standard', 'mega'):
  72.         if os.path.isdir(dirname):
  73.             shutil.rmtree(dirname)
  74.        
  75.         os.mkdir(dirname)
  76.        
  77.         for subdir in ('#f', '#i', '#l'):
  78.             os.mkdir(os.path.join(dirname, subdir))
  79.  
  80.         archive = zipfile.ZipFile(dirname + '.zip',
  81.                                   'w', zipfile.ZIP_STORED)
  82.         ARCHIVES[dirname] = archive
  83.            
  84. def clear_cache():
  85.     if os.path.isdir('cache'):
  86.         shutil.rmtree('cache')
  87.  
  88. def maybe(s):
  89.     return None if s == u'None' else s
  90.  
  91. ARCHIVES = {}
  92.  
  93. def copy(cache, packtype, imgtype, filename=None):
  94.     if not filename:
  95.         parts = imgtype.split('/')
  96.         imgtype = parts[0]
  97.         filename = parts[1]
  98.     emote_path = os.path.join(imgtype, filename) + '.png'
  99.     dest = os.path.join(packtype, emote_path)
  100.     if not os.path.isfile(dest):
  101.         print "    -> " + dest
  102.         shutil.copy(cache, dest)
  103.         if packtype in ARCHIVES:
  104.             archive = ARCHIVES[packtype]
  105.             archive.write(dest, emote_path.encode('utf-8'))
  106.     else:
  107.         print "ERR -> " + dest + " (already exists)"
  108.  
  109. def process_one_flair(row):
  110.     display = row['Selectdisplay'].lower() == 'true'
  111.     inline = row['Selectinline'].lower() == 'true'
  112.     width = int(row['Width'])
  113.     filename = row['Filename']
  114.     shortcut = maybe(row['Shortcutinline'])
  115.     letter = maybe(row['Shortcutletter'])
  116.     flair1 = row['Flair1']
  117.     division = row['Division']
  118.     conference = row['Conference']
  119.    
  120.     if not display and not shortcut and not letter:
  121.         return
  122.    
  123.     if display and not (shortcut or inline):
  124.         return
  125.    
  126.     if shortcut and not shortcut.startswith('#'):
  127.         return
  128.    
  129.     cache = get_image_cached(filename, size=width)
  130.    
  131.     if letter:
  132.         copy(cache, 'standard', letter)
  133.         copy(cache, 'mega', letter)
  134.        
  135.     if shortcut:
  136.         if inline:
  137.             copy(cache, 'standard', shortcut)
  138.         copy(cache, 'mega', shortcut) # include discontinued
  139.     elif inline:
  140.         # Relay will ignore everything that follows a dash.
  141.         name = flair1.split('-')[0]
  142.         if division == 'Postseason' or division == 'Rivalries':
  143.             # Include rivalry trophies and bowl logos.
  144.             copy(cache, 'standard', '#f', name)
  145.         copy(cache, 'mega', '#f', name)
  146.  
  147. def process_all():
  148.     print "Downloading flair database... ",
  149.     sys.stdout.flush()
  150.     csvreq = SESSION.get('https://flair.redditcfb.com/teamsheet.csv')
  151.     csvreq.raise_for_status()
  152.     lines = list(csvreq.iter_lines())
  153.     print '%d flairs loaded.' % len(lines)
  154.    
  155.     print "Cleaning up state..."
  156.     remake_all_dirs()
  157.  
  158.     if not os.path.isdir('cache'):
  159.         os.mkdir('cache')
  160.    
  161.     teamsheet_path = os.path.join('cache', 'teamsheet.csv')
  162.     with open(teamsheet_path, 'w') as fh:
  163.         fh.writelines(lines)
  164.  
  165.     try:
  166.         for row in read_utf8_csv(lines):
  167.             process_one_flair(row)
  168.     finally:
  169.         for archive in ARCHIVES.itervalues():
  170.             archive.close()
  171.        
  172. if __name__ == "__main__":
  173.     os.chdir(os.path.dirname(os.path.abspath(__file__)))
  174.     process_all()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement