Commits

Mark Sundstrom committed dd41d3e

general pep8 cleanup and different way to getting the dates

  • Participants
  • Parent commits 7e0601d
  • Branches default

Comments (0)

Files changed (6)

 camera = Camera.objects.get(pk=os.environ['TIMELAPSE_CAMERA_ID'])
 location = Location.objects.get(pk=os.environ['TIMELAPSE_LOCATION_ID'])
 image_src = os.environ['TIMELAPSE_SOURCE']
-camera_center = (camera.width/2, camera.height/2)
+camera_center = (camera.width / 2, camera.height / 2)
 Item = namedtuple('Item', 'dirpath filename date')
 
 
 
         pic.valid = True
 
-        if im.size <> (640,480):
+        if im.size != (640, 480):
             pic.valid = False
 
     except:
 from django.utils.timezone import utc, get_default_timezone, make_aware
 from movies import ImageSequence
 import sky
-from django.db.models import Max, Min
 
 # Choose defaults from the environment.
 # I set these defaults in the postactivate script of the virtualenv
 tzinfo = get_default_timezone()
 observer = sky.observer_from_location(location)
 overwrite = False  # always write the output files?
+include_night = False
 
-def generate_date():
-    "All the dates for which we have pictures"
-    bounds = Picture.objects.filter(
-        camera=camera, location=location).aggregate(
-        Min('timestamp'), Max('timestamp'))
-    date = bounds['timestamp__min'].date()
-    last_date = bounds['timestamp__max'].date()
-    while date <= last_date:
-        yield date
-        date += datetime.timedelta(days=1)
 
+def generate_dates():
+    "Generate all dates for our default camera and location"
+    for date in Picture.objects.dates().filter(
+           camera=camera, location=location):
+        yield date.date()
 
-for date in generate_date():
+
+for date in generate_dates():
     print("Checking", date)
     outpath = os.path.join(os.environ['TIMELAPSE_DAILY'],
         '{:%Y-%m-%d}.mp4'.format(date))
     dirpath = os.path.dirname(outpath)
     if not os.path.exists(dirpath):
         os.makedirs(dirpath)
-    suntimes = sky.suntimes_for_date(observer, date, '-8')
-    print("Choose images from", suntimes.dawn, "to", suntimes.dusk)
-#     start = make_aware(datetime.datetime.combine(date,
-#         datetime.time(0, 0, 0)), tzinfo)
-#     end = start + datetime.timedelta(days=1)
-    start = make_aware(datetime.datetime(*suntimes.dawn.tuple()[:5]), utc)
-    end = make_aware(datetime.datetime(*suntimes.dusk.tuple()[:5]), utc)
+    if include_night:
+        start = make_aware(datetime.datetime.combine(date,
+            datetime.time(0, 0, 0)), tzinfo)
+        end = start + datetime.timedelta(days=1)
+    else:
+        suntimes = sky.suntimes_for_date(observer, date, '-8')
+        # seconds are floating point, so just ignore them
+        start = make_aware(datetime.datetime(*suntimes.dawn.tuple()[:5]), utc)
+        end = make_aware(datetime.datetime(*suntimes.dusk.tuple()[:5]), utc)
     qs = Picture.objects.filter(camera__id=camera.id,
             location__id=location.id,
             timestamp__gte=start, timestamp__lt=end).order_by('timestamp')
 if not os.path.exists(TEMPDIR_BASE):
     os.mkdir(TEMPDIR_BASE)
 
+
 class ImageSequence(object):
     """
         Collect a sequence of images (assumed to be added in the

File pics/models.py

 from django.dispatch import receiver
 import datetime
 
+
 class Camera(models.Model):
     """Now that I'm going to have more than one camera,
        I need to identify which one I used."""
     def __unicode__(self):
         return self.name
 
+
 # TODO - might want to add time zone field
 class Location(models.Model):
     """This is not only a latitude,longitude but also a
     def __unicode__(self):
         return self.name
 
+
 class PictureManager(models.Manager):
-    def filter_by_date(self, date):
-        """TODO this should filter by camera and location also"""
-        return self.get_query_set().filter(
-            timestamp__year=date.year,
-            timestamp__month=date.month,
-            timestamp__day=date.day).order_by('timestamp')
+    def dates(self):
+        "Return a DateQuerySet of all dates"
+        return self.get_query_set().dates('timestamp', 'day')
+
 
 class Picture(models.Model):
     """Mostly copied from Eric Floehr's daystrips project.
 
     objects = PictureManager()
 
+
 @receiver(pre_save, sender=Picture)
 def pre_save_picture(sender, **kwargs):
     pic = kwargs['instance']
     if pic.file_timestamp is not None:
         pic.file_hour = pic.file_timestamp.hour
         pic.file_minute = pic.file_timestamp.minute
-
-
 from pics.models import Location
 import ephem
 
+HORIZON = '-8'
+
 sun = ephem.Sun()
 
+
 def observer_from_location(location):
     "Create an ephem.Observer object from a location"
     observer = ephem.Observer()
 
 SunTimes = namedtuple('SunTimes', 'dawn sunrise sunset dusk')
 
-def suntimes_for_date(observer, date, horizon='-7'):
+
+def suntimes_for_date(observer, date, horizon=HORIZON):
     """
     Calculate rise and set times for a given date and observer,
-    along with the times of twilight using our default horizon
-    of 7°. Civil twilight is usually calculated for 6°.
+    along with the times of twilight using our default horizon.
+    Civil twilight is usually calculated for 6°.
     """
     observer.date = ephem.Date((date.year, date.month, date.day, 12, 0, 0))
     sunrise = observer.previous_rising(sun)
     return SunTimes(dawn, sunrise, sunset, dusk)
 
 if __name__ == '__main__':
-    print("Sun times for today")
+    print("Sun times for today, horizon of {}°".format(HORIZON))
     location = Location.objects.get(pk=os.environ['TIMELAPSE_LOCATION_ID'])
     observer = observer_from_location(location)
-    times = suntimes_for_date(observer, datetime.date.today(), '-8')
+    times = suntimes_for_date(observer, datetime.date.today())
     for field in times._fields:
         value = getattr(times, field)
         print('{:7} {} UTC or {:%H:%M:%S} local'.format(
 from __future__ import print_function
 from collections import namedtuple
 
+
 def rgb_to_int(rgb):
     "(red, green, blue) tuple --> integer"
-    return int(round(rgb[0]*256*256 + rgb[1]*256 + rgb[2]))
+    return int(round(rgb[0] * 256 * 256 + rgb[1] * 256 + rgb[2]))
 
 
 def int_to_rgb(i):