Beispiel #1
0
def import_mlb(filepath, metapath, event_source='mlb2010', geo_loc="42.63699,-71.549835", limit=100000, **kwargs):
    import csv
    import Image, ImageFont, ImageDraw
    from django.contrib.auth.models import User
    from django.db.models import signals
    from artist.models import ArtistProfile
    from event.models import Event, Venue, Attendee, Stats, recompute_event_stats
    from rdutils.image import get_raw_png_image, resize_in_memory, get_perfect_fit_resize_crop, remove_model_image, close, get_raw_image, str_to_file
    from registration.utils import copy_avatar_from_file_to_profile
    
    print "Script has been disabled to prevent accidental execution :)"
    return False
    
    signals.post_save.disconnect(recompute_event_stats, sender=Attendee)
    signals.post_delete.disconnect(recompute_event_stats, sender=Attendee)
    
    # clear old data first
    '''
    print "Deleting stats"
    Stats.objects.filter(event__ext_event_source=event_source).delete() # delete existing stats
    Stats.objects.filter(event__ext_event_source=event_source).delete()
    print "Deleting events"
    Event.objects.filter(ext_event_source=event_source).delete() # delete existing events first
    print "Deleting users"
    User.objects.filter(first_name='MLB', last_name='Team', email__endswith='@riotvine.com').delete() # delete existing users
    '''
    
    colormap = {
        # 'navy':'#2E2EFE',
        'red': '#DD0000',
    }
    
    secondary_colormap = {}
    
    _ARTIST = ArtistProfile.objects.get(url='riotvine-member')
    _DATE_FORMAT = "%m/%d/%y" # format: 03/17/10
    _TIME_FORMAT = "%H:%M:%S %p"# format: 11:05:00 AM
    
    parent, filename = os.path.split(_DEFAULT_IMAGE)
    profilepath = os.path.join(parent, "baseball.jpg")
    eventbgpath = os.path.join(parent, "baseball_background.png")
    
    # load team meta info    
    team = {}
    reader = csv.reader(open(metapath, "rb"))    
    for row in reader:
        print row
        username = row[6].replace(' ', '')
        team_name = row[0].strip()
        hashtags = ", ".join(row[5].strip().split("~"))
        tz = row[7].strip()
        # create venue
        venue = row[2].decode("utf-8").strip()   
        venue_address = u''
        venue_city, venue_state = row[1].decode("utf-8").strip().split(",")
        venue_city, venue_state = venue_city.strip(), venue_state.strip()
        querystring = urlencode({'q':u'"%s" %s, %s %s' % (venue[:25], venue_address, venue_city, venue_state)})
        map_url = u'http://maps.google.com/?%s' % querystring
        vn, created = Venue.objects.get_or_create(
            name=venue[:255],
            geo_loc=geo_loc,
            source='mlb',
            defaults=dict(
                source='mlb',
                address=venue_address[:255],
                city=venue_city[:255],
                state=venue_state,
                zip_code=u'',
                venue_url=u'',
                map_url=map_url,
            )
        )
        # create user
        a, created = User.objects.get_or_create(
            username=username,
            defaults = dict(
                first_name='MLB',
                last_name='Team',
                email='*****@*****.**' % username.lower(),
                is_staff=False,
                is_active=True
            )
        )
        user_profile = a.get_profile()
        user_profile.send_reminders = False
        user_profile.send_favorites = False
        is_verified = True
        user_profile.save()
        copy_avatar_from_file_to_profile(profilepath, user_profile)
        team[team_name.lower()] = {
            'name':team_name,
            'venue':vn,
            'pri-color':colormap.get(row[3].lower(), row[3]),
            'sec-color':secondary_colormap.get(row[4].lower(), row[4]),
            'user':user_profile,
            'tz':tz,
            'hashtags':hashtags,
        }    
    
    print "Loading schedule"
    # load schedule    
    description = u'''
        <p class="mlb">
            <a href="/sports/baseball/2010/">Baseball 2010&nbsp;&raquo;</a>
        </p>
    '''
    reader = csv.reader(open(filepath, "rb"))    
    num = 0
    for row in reader:
        num += 1
        print num, row
        dt, title, loc, ptime, mtime, ctime, etime = row
        
        # get road and home
        road, home = title.split(' at ')
        road, home = road.strip(), home.strip()
        roadvars = team[road.lower()]
        homevars = team[home.lower()]
        roaduser, homeuser = roadvars['user'], homevars['user']
        roadcolors = roadvars['pri-color'], roadvars['sec-color']
        homecolors = homevars['pri-color'], homevars['sec-color']
        
        hashtags = homevars['hashtags']
        
        # generate 211x211 badge
        raw_image_contents = None
        bg = Image.new("RGB", (211, 211), homecolors[1]) # background is the sec color of home team
        bgimg = Image.open(eventbgpath)
        bg.paste(bgimg, (0, 0))
        t = ImageDraw.Draw(bg)
        # Road team name
        x, y = settings.SPORTS_TEAM_TEXT_START
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT, settings.SPORTS_TEAM_TEXT_FONT_SIZE, encoding='unic')
        tx = roadvars['name']
        w,h = t.textsize(tx, font=font)
        x = (211 - w)/2 # center align
        col = roadcolors[0] # (homecolors[1] == roadcolors[0]) and roadcolors[1] or roadcolors[0]
        t.text((x, y), tx, font=font, fill=col)
        
        # Text = at
        x, y = x, y + settings.SPORTS_TEAM_TEXT_FONT_SIZE + 10
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT, settings.SPORTS_TEAM_TEXT_SMALL_FONT_SIZE, encoding='unic')
        tx = 'at'
        w,h = t.textsize(tx, font=font)
        x = (211 - w)/2 # center align
        t.text((x, y), tx, font=font, fill='#333333')
        
        # Home team name
        x, y = x, y + settings.SPORTS_TEAM_TEXT_SMALL_FONT_SIZE + 10
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT, settings.SPORTS_TEAM_TEXT_FONT_SIZE, encoding='unic')
        tx = homevars['name']
        w,h = t.textsize(tx, font=font)
        x = (211 - w)/2 # center align
        t.text((x, y), tx, font=font, fill=homecolors[0])
        
        raw_image_contents = get_raw_png_image(bg)        
        
        # get venue
        vn = homevars['venue']
        location = settings.STATE_TO_LOCATION_MAP.get(vn.state.lower(), 'user-entered')
        city_state = u'%s|%s' % (vn.city, vn.state)
        location = settings.CITY_STATE_TO_LOCATION_MAP.get(city_state.lower(), location)
        # special cases for locations
        if vn.state == 'NJ':
            location = 'user-defined'
        
        dt = strptime(dt, _DATE_FORMAT)
        event_date = date(*dt[:3])
        
        tz = homevars['tz']
        if tz == 'ET':
            xtime = etime
        elif tz == 'CT':
            xtime = ctime
        elif tz == 'MT':
            xtime = mtime
        elif tz == 'PT':
            xtime = ptime
        else:
            xtime = etime # default timezone is ET
        
        tt = strptime(xtime.strip(), _TIME_FORMAT)
        h, m = tt.tm_hour, tt.tm_min
        if 'PM' in etime.upper() and h < 12:
            h = h + 12
        event_time = u"%s:%s" % (h, m)
        
        title = u"%s! %s" % (title, event_date.strftime("%m/%d"))
        # save event
        ex = Event(
            ext_event_id="999",
            ext_event_source=event_source,
            artist=_ARTIST,
            creator=homeuser,
            description=description,
            is_submitted=True,
            is_approved=True,
            is_free=False,
            title=title[:120],
            url=(u"%s-%s" % (slugify(title)[:30], uuid4().hex[::4]))[:35],
            venue=vn,
            event_date=event_date,
            event_start_time=event_time,
            event_timezone=tz,
            hashtag=hashtags,
            location=location,
            headliner=u'',
            artists=u'',
            has_image=True,
        )
        image_content = ContentFile(raw_image_contents)
        fname, ext = os.path.splitext("default.jpg")
        fname = u'%s%s' % (uuid4().hex[::2], ext)
        ex.image.save(fname, image_content, save=False)
        ex._create_resized_images(raw_field=None, save=False)
        ex.save()
        # favorite event for home users
        ex.attendee_set.get_or_create(attendee_profile=homeuser)
        # ex.attendee_set.get_or_create(attendee_profile=roaduser)        
        if num > limit:
            return
Beispiel #2
0
def create_badge(event, badge, special=None, num_attendees=None):
    """Event badge creation routine. Refactored so that it may be reused by a campaign 
    that behaves like an event."""
    _log.debug('Creating badge: %s' % badge.get_badge_type_display())
    special = special or event.special_badge_text
    num_attendees = num_attendees or event.num_attendees
    bg, fg = None, None
    try:
        badge_type, badge_img = badge.badge_type, badge.bg_image_path
        bg = Image.open(badge_img)
        fg = Image.open(event.image_resized.path)
        bg.paste(fg, settings.EVENT_BADGE_IMAGE_POSITION)
        t = ImageDraw.Draw(bg)

        x, y = settings.EVENT_BADGE_SPECIAL_POSITION

        if special and event.is_approved:
            # Special text
            tx = special
            font = ImageFont.truetype(settings.EVENT_BADGE_SPECIAL_FONT,
                                      settings.EVENT_BADGE_SPECIAL_FONT_SIZE,
                                      encoding='unic')
            t.text((x, y), tx, font=font, fill='#dddddd')

        # Event date
        x, y = settings.EVENT_BADGE_DATE_POSITION
        tx = event.event_date.strftime("%m/%d/%y")
        font = ImageFont.truetype(settings.EVENT_BADGE_DATE_FONT,
                                  settings.EVENT_BADGE_DATE_FONT_SIZE,
                                  encoding='unic')
        t.text((x, y), tx, font=font, fill='#666666')

        x, y = settings.EVENT_BADGE_ATTENDEE_POSITION

        # Attendees
        if num_attendees:
            tx = "%s" % num_attendees
            # Pick font size based on the number of attendees.
            idx = 0
            dx = 0
            if num_attendees > 999:
                idx = 2
            elif num_attendees > 99:
                idx = 1
            else:
                if num_attendees < 10:
                    dx = 15
                idx = 0
            font = ImageFont.truetype(
                settings.EVENT_BADGE_ATTENDEE_FONT,
                settings.EVENT_BADGE_ATTENDEE_FONT_SIZES[idx],
                encoding='unic')
            y -= settings.EVENT_BADGE_ATTENDEE_FONT_SIZES[idx] - 1
            t.text((x + dx, y), tx, font=font, fill='#eeeeee')

            # Attending
            x, y = settings.EVENT_BADGE_TEXT_POSITION
            tx = "Attending"
            font = ImageFont.truetype(settings.EVENT_BADGE_TEXT_FONT,
                                      settings.EVENT_BADGE_TEXT_FONT_SIZE,
                                      encoding='unic')
            t.text((x, y), tx, font=font, fill='#c60104')

        # Save generated image
        raw_img = get_raw_png_image(bg)
        if raw_img:
            raw_file = str_to_file(raw_img)
            # file, field_name, name, content_type, size, charset
            raw_badge = InMemoryUploadedFile(raw_file, None, None,
                                             guess_type(".jpg")[0],
                                             len(raw_img), None)
            remove_model_image(badge, 'image')  # remove previous resized copy
            badge.image.save(name='badge-%s-%s-%s.png' %
                             (badge_type, event.pk, int(time())),
                             content=raw_badge,
                             save=False)
            badge.save()
            raw_file.close()
            _log.info('Badge (type: %s) created: %s - %s', badge_type,
                      event.pk, event.title)
        else:
            _log.error('Badge (type: %s) creation failed: %s - %s', badge_type,
                       event.pk, event.title)
    except Exception, e:
        _log.exception(e)
        raise
Beispiel #3
0
def create_badge(event, badge, special=None, num_attendees=None):
    """Event badge creation routine. Refactored so that it may be reused by a campaign 
    that behaves like an event."""
    _log.debug('Creating badge: %s' % badge.get_badge_type_display())
    special = special or event.special_badge_text
    num_attendees = num_attendees or event.num_attendees
    bg, fg = None, None
    try:
        badge_type, badge_img = badge.badge_type, badge.bg_image_path
        bg = Image.open(badge_img)
        fg = Image.open(event.image_resized.path)
        bg.paste(fg, settings.EVENT_BADGE_IMAGE_POSITION)
        t = ImageDraw.Draw(bg)

        x, y = settings.EVENT_BADGE_SPECIAL_POSITION

        if special and event.is_approved:
            # Special text
            tx = special
            font = ImageFont.truetype(settings.EVENT_BADGE_SPECIAL_FONT, settings.EVENT_BADGE_SPECIAL_FONT_SIZE, encoding='unic')
            t.text((x, y), tx, font=font, fill='#dddddd')

        # Event date
        x, y = settings.EVENT_BADGE_DATE_POSITION
        tx = event.event_date.strftime("%m/%d/%y")
        font = ImageFont.truetype(settings.EVENT_BADGE_DATE_FONT, settings.EVENT_BADGE_DATE_FONT_SIZE, encoding='unic')
        t.text((x, y), tx, font=font, fill='#666666')

        x, y = settings.EVENT_BADGE_ATTENDEE_POSITION

        # Attendees
        if num_attendees:
            tx =  "%s" % num_attendees
            # Pick font size based on the number of attendees.
            idx = 0
            dx = 0
            if num_attendees > 999:
                idx = 2
            elif num_attendees > 99:
                idx = 1
            else:
                if num_attendees < 10:
                    dx = 15
                idx = 0
            font = ImageFont.truetype(settings.EVENT_BADGE_ATTENDEE_FONT, settings.EVENT_BADGE_ATTENDEE_FONT_SIZES[idx], encoding='unic')
            y -= settings.EVENT_BADGE_ATTENDEE_FONT_SIZES[idx] - 1
            t.text((x+dx, y), tx, font=font,  fill='#eeeeee')

            # Attending
            x, y = settings.EVENT_BADGE_TEXT_POSITION
            tx = "Attending"
            font = ImageFont.truetype(settings.EVENT_BADGE_TEXT_FONT, settings.EVENT_BADGE_TEXT_FONT_SIZE, encoding='unic')
            t.text((x, y), tx, font=font, fill='#c60104')

        # Save generated image
        raw_img = get_raw_png_image(bg)
        if raw_img:
            raw_file = str_to_file(raw_img)
            # file, field_name, name, content_type, size, charset
            raw_badge = InMemoryUploadedFile(raw_file, None, None, guess_type(".jpg")[0], len(raw_img), None)
            remove_model_image(badge, 'image') # remove previous resized copy
            badge.image.save(name='badge-%s-%s-%s.png' % (badge_type, event.pk, int(time())), content=raw_badge, save=False)
            badge.save()
            raw_file.close()
            _log.info('Badge (type: %s) created: %s - %s', badge_type, event.pk, event.title)
        else:
            _log.error('Badge (type: %s) creation failed: %s - %s', badge_type, event.pk, event.title)
    except Exception, e:
        _log.exception(e)
        raise
Beispiel #4
0
def import_mlb(filepath,
               metapath,
               event_source='mlb2010',
               geo_loc="42.63699,-71.549835",
               limit=100000,
               **kwargs):
    import csv
    import Image, ImageFont, ImageDraw
    from django.contrib.auth.models import User
    from django.db.models import signals
    from artist.models import ArtistProfile
    from event.models import Event, Venue, Attendee, Stats, recompute_event_stats
    from rdutils.image import get_raw_png_image, resize_in_memory, get_perfect_fit_resize_crop, remove_model_image, close, get_raw_image, str_to_file
    from registration.utils import copy_avatar_from_file_to_profile

    print "Script has been disabled to prevent accidental execution :)"
    return False

    signals.post_save.disconnect(recompute_event_stats, sender=Attendee)
    signals.post_delete.disconnect(recompute_event_stats, sender=Attendee)

    # clear old data first
    '''
    print "Deleting stats"
    Stats.objects.filter(event__ext_event_source=event_source).delete() # delete existing stats
    Stats.objects.filter(event__ext_event_source=event_source).delete()
    print "Deleting events"
    Event.objects.filter(ext_event_source=event_source).delete() # delete existing events first
    print "Deleting users"
    User.objects.filter(first_name='MLB', last_name='Team', email__endswith='@riotvine.com').delete() # delete existing users
    '''

    colormap = {
        # 'navy':'#2E2EFE',
        'red': '#DD0000',
    }

    secondary_colormap = {}

    _ARTIST = ArtistProfile.objects.get(url='riotvine-member')
    _DATE_FORMAT = "%m/%d/%y"  # format: 03/17/10
    _TIME_FORMAT = "%H:%M:%S %p"  # format: 11:05:00 AM

    parent, filename = os.path.split(_DEFAULT_IMAGE)
    profilepath = os.path.join(parent, "baseball.jpg")
    eventbgpath = os.path.join(parent, "baseball_background.png")

    # load team meta info
    team = {}
    reader = csv.reader(open(metapath, "rb"))
    for row in reader:
        print row
        username = row[6].replace(' ', '')
        team_name = row[0].strip()
        hashtags = ", ".join(row[5].strip().split("~"))
        tz = row[7].strip()
        # create venue
        venue = row[2].decode("utf-8").strip()
        venue_address = u''
        venue_city, venue_state = row[1].decode("utf-8").strip().split(",")
        venue_city, venue_state = venue_city.strip(), venue_state.strip()
        querystring = urlencode({
            'q':
            u'"%s" %s, %s %s' %
            (venue[:25], venue_address, venue_city, venue_state)
        })
        map_url = u'http://maps.google.com/?%s' % querystring
        vn, created = Venue.objects.get_or_create(
            name=venue[:255],
            geo_loc=geo_loc,
            source='mlb',
            defaults=dict(
                source='mlb',
                address=venue_address[:255],
                city=venue_city[:255],
                state=venue_state,
                zip_code=u'',
                venue_url=u'',
                map_url=map_url,
            ))
        # create user
        a, created = User.objects.get_or_create(
            username=username,
            defaults=dict(first_name='MLB',
                          last_name='Team',
                          email='*****@*****.**' %
                          username.lower(),
                          is_staff=False,
                          is_active=True))
        user_profile = a.get_profile()
        user_profile.send_reminders = False
        user_profile.send_favorites = False
        is_verified = True
        user_profile.save()
        copy_avatar_from_file_to_profile(profilepath, user_profile)
        team[team_name.lower()] = {
            'name': team_name,
            'venue': vn,
            'pri-color': colormap.get(row[3].lower(), row[3]),
            'sec-color': secondary_colormap.get(row[4].lower(), row[4]),
            'user': user_profile,
            'tz': tz,
            'hashtags': hashtags,
        }

    print "Loading schedule"
    # load schedule
    description = u'''
        <p class="mlb">
            <a href="/sports/baseball/2010/">Baseball 2010&nbsp;&raquo;</a>
        </p>
    '''
    reader = csv.reader(open(filepath, "rb"))
    num = 0
    for row in reader:
        num += 1
        print num, row
        dt, title, loc, ptime, mtime, ctime, etime = row

        # get road and home
        road, home = title.split(' at ')
        road, home = road.strip(), home.strip()
        roadvars = team[road.lower()]
        homevars = team[home.lower()]
        roaduser, homeuser = roadvars['user'], homevars['user']
        roadcolors = roadvars['pri-color'], roadvars['sec-color']
        homecolors = homevars['pri-color'], homevars['sec-color']

        hashtags = homevars['hashtags']

        # generate 211x211 badge
        raw_image_contents = None
        bg = Image.new(
            "RGB", (211, 211),
            homecolors[1])  # background is the sec color of home team
        bgimg = Image.open(eventbgpath)
        bg.paste(bgimg, (0, 0))
        t = ImageDraw.Draw(bg)
        # Road team name
        x, y = settings.SPORTS_TEAM_TEXT_START
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT,
                                  settings.SPORTS_TEAM_TEXT_FONT_SIZE,
                                  encoding='unic')
        tx = roadvars['name']
        w, h = t.textsize(tx, font=font)
        x = (211 - w) / 2  # center align
        col = roadcolors[
            0]  # (homecolors[1] == roadcolors[0]) and roadcolors[1] or roadcolors[0]
        t.text((x, y), tx, font=font, fill=col)

        # Text = at
        x, y = x, y + settings.SPORTS_TEAM_TEXT_FONT_SIZE + 10
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT,
                                  settings.SPORTS_TEAM_TEXT_SMALL_FONT_SIZE,
                                  encoding='unic')
        tx = 'at'
        w, h = t.textsize(tx, font=font)
        x = (211 - w) / 2  # center align
        t.text((x, y), tx, font=font, fill='#333333')

        # Home team name
        x, y = x, y + settings.SPORTS_TEAM_TEXT_SMALL_FONT_SIZE + 10
        font = ImageFont.truetype(settings.SPORTS_TEAM_TEXT_FONT,
                                  settings.SPORTS_TEAM_TEXT_FONT_SIZE,
                                  encoding='unic')
        tx = homevars['name']
        w, h = t.textsize(tx, font=font)
        x = (211 - w) / 2  # center align
        t.text((x, y), tx, font=font, fill=homecolors[0])

        raw_image_contents = get_raw_png_image(bg)

        # get venue
        vn = homevars['venue']
        location = settings.STATE_TO_LOCATION_MAP.get(vn.state.lower(),
                                                      'user-entered')
        city_state = u'%s|%s' % (vn.city, vn.state)
        location = settings.CITY_STATE_TO_LOCATION_MAP.get(
            city_state.lower(), location)
        # special cases for locations
        if vn.state == 'NJ':
            location = 'user-defined'

        dt = strptime(dt, _DATE_FORMAT)
        event_date = date(*dt[:3])

        tz = homevars['tz']
        if tz == 'ET':
            xtime = etime
        elif tz == 'CT':
            xtime = ctime
        elif tz == 'MT':
            xtime = mtime
        elif tz == 'PT':
            xtime = ptime
        else:
            xtime = etime  # default timezone is ET

        tt = strptime(xtime.strip(), _TIME_FORMAT)
        h, m = tt.tm_hour, tt.tm_min
        if 'PM' in etime.upper() and h < 12:
            h = h + 12
        event_time = u"%s:%s" % (h, m)

        title = u"%s! %s" % (title, event_date.strftime("%m/%d"))
        # save event
        ex = Event(
            ext_event_id="999",
            ext_event_source=event_source,
            artist=_ARTIST,
            creator=homeuser,
            description=description,
            is_submitted=True,
            is_approved=True,
            is_free=False,
            title=title[:120],
            url=(u"%s-%s" % (slugify(title)[:30], uuid4().hex[::4]))[:35],
            venue=vn,
            event_date=event_date,
            event_start_time=event_time,
            event_timezone=tz,
            hashtag=hashtags,
            location=location,
            headliner=u'',
            artists=u'',
            has_image=True,
        )
        image_content = ContentFile(raw_image_contents)
        fname, ext = os.path.splitext("default.jpg")
        fname = u'%s%s' % (uuid4().hex[::2], ext)
        ex.image.save(fname, image_content, save=False)
        ex._create_resized_images(raw_field=None, save=False)
        ex.save()
        # favorite event for home users
        ex.attendee_set.get_or_create(attendee_profile=homeuser)
        # ex.attendee_set.get_or_create(attendee_profile=roaduser)
        if num > limit:
            return