예제 #1
0
파일: repl.py 프로젝트: julfy/bci-repl
 def f(dir: str, delay: float, duration: float, rest: float, bg: str,
       seed: int) -> None:
     oldstd = sys.stderr
     with open(os.devnull, "w") as out:
         sys.stderr = out
         slideshow = Slideshow(dir, delay, duration, rest, bg, seed)
         slideshow.start()
     sys.stderr = oldstd
예제 #2
0
def main(image_paths):
    if globals.ON_LINUX:
        if os.environ.get("DISPLAY", None) is None:
            os.environ["DISPLAY"] = ":0"
            logger.info("Setting environment variable: DISPLAY = :0")
        else:
            logger.debug("DISPLAY already set")

    try:
        logger.info("Initializing Slideshow")
        slideshow = Slideshow(image_paths)
        slideshow.start_slideshow()
        slideshow.mainloop()
    except BaseException as e:
        logger.exception(e)
예제 #3
0
    def __init__(self, config_provider):

        text_to_speech = None
        if (config_provider.acting or config_provider.browser or
            config_provider.calculator or config_provider.hand_gesture or
            config_provider.happy_colour or config_provider.mixing_desk or
            config_provider.optical_character_recognition or config_provider.play_your_cards_right or
            config_provider.slideshow or config_provider.weather):
            from texttospeech import TextToSpeech
            text_to_speech = TextToSpeech()

        speech_to_text = None
        if (config_provider.acting or config_provider.browser or
            config_provider.calculator or config_provider.mixing_desk or
            config_provider.phrase_translation or config_provider.play_your_cards_right or
            config_provider.weather):
            from speechtotext import SpeechToText
            speech_to_text = SpeechToText()

        self.acting = None
        if config_provider.acting:
            from acting import Acting
            self.acting = Acting(text_to_speech, speech_to_text)

        self.browser = None
        if config_provider.browser:
            from browser import Browser
            self.browser = Browser(text_to_speech, speech_to_text)

        self.calculator = None
        if config_provider.calculator:
            from calculator import Calculator
            self.calculator = Calculator(text_to_speech, speech_to_text)

        self.hand_gesture = None
        if config_provider.hand_gesture:
            from handgesture import HandGesture
            self.hand_gesture = HandGesture(text_to_speech)

        self.happy_colour = None
        if config_provider.happy_colour:
            from happycolour import HappyColour
            self.happy_colour = HappyColour(text_to_speech)

        self.mixing_desk = None
        if config_provider.mixing_desk:
            from mixingdesk import MixingDesk
            self.mixing_desk = MixingDesk(text_to_speech, speech_to_text)

        self.optical_character_recognition = None
        if config_provider.optical_character_recognition:
            from opticalcharacterrecognition import OpticalCharacterRecognition
            self.optical_character_recognition = OpticalCharacterRecognition(text_to_speech)

        self.phrase_translation = None
        if config_provider.phrase_translation:
            from phrasetranslation import PhraseTranslation
            self.phrase_translation = PhraseTranslation(speech_to_text)

        self.play_your_cards_right = None
        if config_provider.play_your_cards_right:
            from playyourcardsright import PlayYourCardsRight
            self.play_your_cards_right = PlayYourCardsRight(text_to_speech, speech_to_text)

        self.slideshow = None
        if config_provider.slideshow:
            from slideshow import Slideshow
            self.slideshow = Slideshow(text_to_speech)

        self.television = None
        if config_provider.television:
            from television import Television
            self.television = Television()

        self.weather = None
        if config_provider.weather:
            from weather import Weather
            self.weather = Weather(text_to_speech, speech_to_text)
예제 #4
0
class Features:

    # initialise features
    def __init__(self, config_provider):

        text_to_speech = None
        if (config_provider.acting or config_provider.browser or
            config_provider.calculator or config_provider.hand_gesture or
            config_provider.happy_colour or config_provider.mixing_desk or
            config_provider.optical_character_recognition or config_provider.play_your_cards_right or
            config_provider.slideshow or config_provider.weather):
            from texttospeech import TextToSpeech
            text_to_speech = TextToSpeech()

        speech_to_text = None
        if (config_provider.acting or config_provider.browser or
            config_provider.calculator or config_provider.mixing_desk or
            config_provider.phrase_translation or config_provider.play_your_cards_right or
            config_provider.weather):
            from speechtotext import SpeechToText
            speech_to_text = SpeechToText()

        self.acting = None
        if config_provider.acting:
            from acting import Acting
            self.acting = Acting(text_to_speech, speech_to_text)

        self.browser = None
        if config_provider.browser:
            from browser import Browser
            self.browser = Browser(text_to_speech, speech_to_text)

        self.calculator = None
        if config_provider.calculator:
            from calculator import Calculator
            self.calculator = Calculator(text_to_speech, speech_to_text)

        self.hand_gesture = None
        if config_provider.hand_gesture:
            from handgesture import HandGesture
            self.hand_gesture = HandGesture(text_to_speech)

        self.happy_colour = None
        if config_provider.happy_colour:
            from happycolour import HappyColour
            self.happy_colour = HappyColour(text_to_speech)

        self.mixing_desk = None
        if config_provider.mixing_desk:
            from mixingdesk import MixingDesk
            self.mixing_desk = MixingDesk(text_to_speech, speech_to_text)

        self.optical_character_recognition = None
        if config_provider.optical_character_recognition:
            from opticalcharacterrecognition import OpticalCharacterRecognition
            self.optical_character_recognition = OpticalCharacterRecognition(text_to_speech)

        self.phrase_translation = None
        if config_provider.phrase_translation:
            from phrasetranslation import PhraseTranslation
            self.phrase_translation = PhraseTranslation(speech_to_text)

        self.play_your_cards_right = None
        if config_provider.play_your_cards_right:
            from playyourcardsright import PlayYourCardsRight
            self.play_your_cards_right = PlayYourCardsRight(text_to_speech, speech_to_text)

        self.slideshow = None
        if config_provider.slideshow:
            from slideshow import Slideshow
            self.slideshow = Slideshow(text_to_speech)

        self.television = None
        if config_provider.television:
            from television import Television
            self.television = Television()

        self.weather = None
        if config_provider.weather:
            from weather import Weather
            self.weather = Weather(text_to_speech, speech_to_text)

    # indicate whether a feature is speaking
    def is_speaking(self):
        return ((self.acting and self.acting.is_speaking) or
                (self.browser and self.browser.is_speaking) or
                (self.calculator and self.calculator.is_speaking) or           
                (self.hand_gesture and self.hand_gesture.is_speaking) or
                (self.happy_colour and self.happy_colour.is_speaking) or                
                (self.mixing_desk and self.mixing_desk.is_speaking) or
                (self.optical_character_recognition and self.optical_character_recognition.is_speaking) or
                (self.phrase_translation and self.phrase_translation.is_speaking) or
                (self.play_your_cards_right and self.play_your_cards_right.is_speaking) or
                (self.slideshow and self.slideshow.is_speaking) or
                (self.weather and self.weather.is_speaking))

    # provide emotion from a feature
    def get_emotion(self):
        if self.acting: 
            return self.acting.emotion
        elif self.hand_gesture: 
            return self.hand_gesture.emotion
        elif self.happy_colour: 
            return self.happy_colour.emotion
        else:
            return None

    # update background image from a feature
    def update_background_image(self, image):
        if self.slideshow and self.slideshow.background_image.size > 0: 
            return self.slideshow.background_image  
        elif self.television and self.television.background_image.size > 0: 
            return self.television.background_image
        else:
            return image

    # handle features
    def handle(self, rocky_robot, sporty_robot, image):
        self._handle_acting(rocky_robot, sporty_robot)
        self._handle_browser(rocky_robot, sporty_robot)
        self._handle_calculator(rocky_robot, sporty_robot)
        self._handle_hand_gesture(rocky_robot, sporty_robot, image)
        self._handle_happy_colour(rocky_robot, image)
        self._handle_mixing_desk(rocky_robot)
        self._handle_optical_character_recognition(rocky_robot, sporty_robot, image)
        self._handle_phrase_translation(sporty_robot)
        self._handle_play_your_cards_right(sporty_robot)
        self._handle_slideshow(rocky_robot, sporty_robot, image)
        self._handle_television(rocky_robot, sporty_robot, image)
        self._handle_weather(rocky_robot, sporty_robot)

    # handle acting
    def _handle_acting(self, rocky_robot, sporty_robot):
        if not self.acting: return
 
        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.acting.start()
        else:
            self.acting.stop()

    # handle browser
    def _handle_browser(self, rocky_robot, sporty_robot):
        if not self.browser: return

        if rocky_robot.is_facing:
            self.browser.start(ROCK)
        elif sporty_robot.is_facing:
            self.browser.start(SPORT)
        else:
            self.browser.stop()

    # handle calculator
    def _handle_calculator(self, rocky_robot, sporty_robot):
        if not self.calculator: return
 
        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.calculator.start()
        else:
            self.calculator.stop()

    # handle hand gesture
    def _handle_hand_gesture(self, rocky_robot, sporty_robot, image):
        if not self.hand_gesture: return

        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.hand_gesture.start(image)
        else:
            self.hand_gesture.stop()

    # handle happy colour
    def _handle_happy_colour(self, rocky_robot, image):
        if not self.happy_colour: return

        if rocky_robot.is_facing:
            self.happy_colour.start(image)
        else:
            self.happy_colour.stop()

    # handle mixing desk
    def _handle_mixing_desk(self, rocky_robot):
        if not self.mixing_desk: return
 
        if rocky_robot.is_facing:
            self.mixing_desk.start()
        else:
            self.mixing_desk.stop()

    # handle optical character recognition
    def _handle_optical_character_recognition(self, rocky_robot, sporty_robot, image):
        if not self.optical_character_recognition: return

        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.optical_character_recognition.start(image)
        else:
            self.optical_character_recognition.stop()

    # handle phrase translation
    def _handle_phrase_translation(self, sporty_robot):
        if not self.phrase_translation: return

        if sporty_robot.is_facing:
            self.phrase_translation.start()
        else:
            self.phrase_translation.stop()

    # handle play your cards right
    def _handle_play_your_cards_right(self, sporty_robot):
        if not self.play_your_cards_right: return

        if sporty_robot.is_facing:
            self.play_your_cards_right.start()
        else:
            self.play_your_cards_right.stop()

    # handle slideshow
    def _handle_slideshow(self, rocky_robot, sporty_robot, image):
        if not self.slideshow: return

        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.slideshow.start(image)
        else:
            self.slideshow.stop()

    # handle television
    def _handle_television(self, rocky_robot, sporty_robot, image):
        if not self.television: return

        if rocky_robot.is_rendered or sporty_robot.is_rendered:
            self.television.start(image)
        else:
            self.television.stop()

    # handle weather
    def _handle_weather(self, rocky_robot, sporty_robot):
        if not self.weather: return

        if rocky_robot.is_facing or sporty_robot.is_facing:
            self.weather.start()
        else:
            self.weather.stop()
예제 #5
0
from sys import argv
from file import read_input_file
from slideshow import Slideshow

slides_list = {}
# for filename in ['a_example', 'b_lovely_landscapes', 'c_memorable_moments', 'd_pet_pictures', 'e_shiny_selfies']:

filename = argv[1]
file_object = read_input_file(f'../files/{filename}.txt')

slides = Slideshow(file_object, output_file_name=filename)
print(slides.directory_name)
slides.arrange2()
slides.to_file(approach=2)
print(f'Arrange 2 score: {slides.score()}')

try:
    tries = int(argv[2])
except:
    tries = 100

max_score = 0
slides_list[filename] = (slides, max_score)
for tr in range(tries):
    print(f'Progress: {round(tr/tries * 100, 2)}% - {max_score}' + ' ' * 80,
          end='\r')
    slides.arrange()
    score = slides.score()
    if score > max_score:
        max_score = score
        slides.to_file(approach=1)
예제 #6
0
import sys
from os.path import join, dirname, realpath
from config_gui import Configuration_Manager
from server_should_run import ServerShouldRun
from slideshow import Slideshow
from remote import Remote

if __name__ == '__main__':
    configuration_manager = Configuration_Manager(
        join(dirname(realpath(__file__)), 'config.ini'))
    skipconfig = '--skipconfig' in sys.argv
    server_should_run = ServerShouldRun(skipconfig)

    if not skipconfig:
        from config_gui import ConfigurationManagerGui
        settings_gui = ConfigurationManagerGui(configuration_manager,
                                               server_should_run)
        settings_gui.run()

    if server_should_run.ask():
        settings = configuration_manager.get_config()
        slideshow = Slideshow(settings['directory'], settings['install'])
        slideshow.start()
        remote = Remote(slideshow)
        remote.run()

    print('Process terminated successfully')
예제 #7
0
class Photobooth:
    """The main class.

    It contains all the logic for the photobooth.
    """

    def __init__(self, display_size, picture_basename, picture_size,
                 pose_time_first, pose_time, display_time, trigger_channel,
                 shutdown_channel, lamp_channel, idle_slideshow,
                 slideshow_display_time):
        self.display      = GuiModule('Photobooth', display_size)
        self.pictures     = PictureList(picture_basename)
        self.prints       = PictureList(print_basename)
        self.camera       = CameraModule(picture_size)

        self.pic_size     = picture_size
        self.pose_time_first = pose_time_first
        self.pose_time    = pose_time
        self.display_time = display_time

        self.trigger_channel  = trigger_channel
        self.shutdown_channel = shutdown_channel
        self.lamp_channel     = lamp_channel

        self.idle_slideshow = idle_slideshow
        if self.idle_slideshow:
            self.slideshow_display_time = slideshow_display_time
            self.slideshow = Slideshow(display_size, display_time, 
                                       os.path.dirname(os.path.realpath(picture_basename)))

        input_channels    = [ trigger_channel, shutdown_channel ]
        output_channels   = [ lamp_channel ]
        self.gpio         = GPIO(self.handle_gpio, input_channels, output_channels)
        self.bt1          = BTMon(btaddr1, 1, self.handle_bt)
        self.bt2          = BTMon(btaddr2, 2, self.handle_bt)

    def teardown(self):
        self.display.clear()
        self.display.show_message(u"Stänger av...")
        self.display.apply()
        self.gpio.set_output(self.lamp_channel, 0)
        self.display.cancel_events()
        self.display.teardown()
        self.gpio.teardown()
        exit(0)

    def _run_plain(self):
        while True:
            self.camera.set_idle()

            # Display default message
            self.display.clear()
            #self.display.show_message(u"Tryck på knappen!")
            self.display.show_message(u"                    Ta bild\n\n\n\n\n\n\n\n\n", color=(255,0,0))
            self.display.show_message(u"\n\n\n\n\n\n\n\nPreview                   ")
            #self.display.show_message(u"Ta bild       Preview           \n   |         |                 \n   |         |                 \n    v       v                 \n   R        S                 \n")
            self.display.apply()

            # Wait for an event and handle it
            event = self.display.wait_for_event()
            self.handle_event(event)

    def _run_slideshow(self):
        while True:
            self.camera.set_idle()
            #self.slideshow.display_next(u"Tryck på knappen!")
            #self.slideshow.display_next(u"Ta bild       Preview           \n   |         |                 \n   |         |                 \n   v         v                 \n   R        S                 \n")
            self.slideshow.display_next(u"\n\n\n\n\n\n\n\nPreview                   "
                                       ,u"                    Ta bild\n\n\n\n\n\n\n\n\n")
            tic = time()
            while time() - tic < self.slideshow_display_time:
                self.check_and_handle_events()

    def run(self):
        while True:
            try:
                # Enable lamp
                self.gpio.set_output(self.lamp_channel, 1)

                # Select idle screen type
                if self.idle_slideshow:
                    self._run_slideshow()
                else:
                    self._run_plain()

            # Catch exceptions and display message
            except CameraException as e:
                self.handle_exception(e.message)
            # Do not catch KeyboardInterrupt and SystemExit
            except (KeyboardInterrupt): #, SystemExit):
                raise
            except Exception as e:
                print('SERIOUS ERROR: ' + repr(e))
                traceback.print_exc();
                self.handle_exception("SERIOUS ERROR!")

    def check_and_handle_events(self):
        r, e = self.display.check_for_event()
        while r:
            self.handle_event(e)
            r, e = self.display.check_for_event()

    def handle_gpio(self, channel):
        if channel in [ self.trigger_channel, self.shutdown_channel ]:
            self.display.trigger_event(channel)

    def handle_bt(self, channel):
        self.display.trigger_event(channel)

    def convert_event(self, event):
        if event.type == 0:
            return 0
        elif event.type == 1:
            key = event.value
            if key == ord('q'):
                return 0
            elif key == ord('c'):
                return 1
            elif key == ord('u'):
                return 2
            elif key == ord('r'):
                return 1
            elif key == ord('s'):
                return 2
        elif event.type == 2:
            if event.value[0] == 1:
                return 1
        elif event.type == 3:
            if event.value == 1:
                return 1
            if event.value == 2:
                return 2
        return -1

    def handle_event(self, event):
        code = self.convert_event(event)
        if code == 0:
            self.teardown()
        elif code == 1:
            # Take pictures
            self.take_picture()
            self.display.cancel_events()
        elif code == 2:
            self.show_preview(20, False)
            self.display.cancel_events()

    def handle_exception(self, msg):
        """Displays an error message and returns"""
        self.display.clear()
        print("Error: " + msg)
        self.display.show_message(u"FEL:\n\n" + msg)
        self.display.apply()
        self.display.cancel_events()
        exit(1)


    def assemble_pictures(self, input_filenames, size):
        """Assembles four pictures into a 2x2 grid

        It assumes, all original pictures have the same aspect ratio as
        the resulting image.

        For the thumbnail sizes we have:
        h = (H - 2 * a - 2 * b) / 2
        w = (W - 2 * a - 2 * b) / 2

                                    W
               |---------------------------------------|

          ---  +---+-------------+---+-------------+---+  ---
           |   |                                       |   |  a
           |   |   +-------------+   +-------------+   |  ---
           |   |   |             |   |             |   |   |
           |   |   |      0      |   |      1      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
         H |   |                                       |   |  2*b
           |   |   +-------------+   +-------------+   |  ---
           |   |   |             |   |             |   |   |
           |   |   |      2      |   |      3      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
           |   |                                       |   |  a
          ---  +---+-------------+---+-------------+---+  ---

               |---|-------------|---|-------------|---|
                 a        w       2*b       w        a
        """

        # Thumbnail size of pictures
        outer_border = 40
        inner_border = 20
        thumb_box = ( int( size[0] / 2 ) ,
                      int( size[1] / 2 ) )
        thumb_size = ( thumb_box[0] - outer_border - inner_border ,
                       thumb_box[1] - outer_border - inner_border )

        # Create output image with white background
        output_image = Image.new('RGB', size, (0, 0, 0))

        # Image 0
        img = Image.open(input_filenames[0])
        img.thumbnail(thumb_size)
        offset = ( thumb_box[0] - inner_border - img.size[0] ,
                   thumb_box[1] - inner_border - img.size[1] )
        output_image.paste(img, offset)

        # Image 1
        img = Image.open(input_filenames[1])
        img.thumbnail(thumb_size)
        offset = ( thumb_box[0] + inner_border,
                   thumb_box[1] - inner_border - img.size[1] )
        output_image.paste(img, offset)

        # Image 2
        img = Image.open(input_filenames[2])
        img.thumbnail(thumb_size)
        offset = ( thumb_box[0] - inner_border - img.size[0] ,
                   thumb_box[1] + inner_border )
        output_image.paste(img, offset)

        # Image 3
        img = Image.open(input_filenames[3])
        img.thumbnail(thumb_size)
        offset = ( thumb_box[0] + inner_border ,
                   thumb_box[1] + inner_border )
        output_image.paste(img, offset)

        output_image = output_image.convert(mode)

        # Save assembled image
        output_filename = self.pictures.get_next()
        sleep(0.01)
        output_image.save(output_filename, "JPEG")
        sleep(0.01)
        return output_filename

    def assemble_print(self, input_filenames, size):
        """Assembles four pictures into a 2x2 grid

        It assumes, all original pictures have the same aspect ratio as
        the resulting image.

        For the thumbnail sizes we have:
        h = (H - 2*a - 6*b) / 4
        w = (W - 2*a - 2*b) / 2

                                    W
               |---------------------------------------|
                   w0                w1
          ---  +---+-------------+---+-------------+---+  ---
           |   |                                       |   |  a
           |   |   +-------------+   +-------------+   |  --- h0
           |   |   |             |   |             |   |   |
           |   |   |      0      |   |      0      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
           |   |                                       |   |  b
           |   |   +-------------+   +-------------+   |  --- h1
           |   |   |             |   |             |   |   |
           |   |   |      1      |   |      1      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
         H |   |                                       |   |  b
           |   |   +-------------+   +-------------+   |  --- h2
           |   |   |             |   |             |   |   |
           |   |   |      2      |   |      2      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
           |   |                                       |   |  b
           |   |   +-------------+   +-------------+   |  --- h3
           |   |   |             |   |             |   |   |
           |   |   |      3      |   |      3      |   |   |  h
           |   |   |             |   |             |   |   |
           |   |   +-------------+   +-------------+   |  ---
           |   |                                       |   |  a
          ---  +---+-------------+---+-------------+---+  ---

               |---|-------------|---|-------------|---|
                 a        w        b        w        a
        """

        # Thumbnail size of pictures
        outer_borderx = 0
        outer_bordery = 110
        inner_borderx = 20
        inner_bordery = 10
        thumb_size = ( int((size[0] - 2*outer_borderx - inner_borderx)/2) ,
                       int((size[1] - 2*outer_bordery - 3*inner_bordery)/4) )
        w = [outer_borderx
            ,outer_borderx+thumb_size[0]+inner_borderx
            ]
        h = [outer_bordery
            ,outer_bordery+1*(thumb_size[1]+inner_bordery)
            ,outer_bordery+2*(thumb_size[1]+inner_bordery)
            ,outer_bordery+3*(thumb_size[1]+inner_bordery)
            ]

        # Create output image with white background
        output_image = Image.new('RGB', size, (255, 255, 255))

        # Image 0
        img = Image.open(input_filenames[0])
        img.thumbnail(thumb_size, Image.ANTIALIAS)
        output_image.paste(img, (w[0],h[0]))
        output_image.paste(img, (w[1],h[0]))

        # Image 1
        img = Image.open(input_filenames[1])
        img.thumbnail(thumb_size, Image.ANTIALIAS)
        output_image.paste(img, (w[0],h[1]))
        output_image.paste(img, (w[1],h[1]))

        # Image 2
        img = Image.open(input_filenames[2])
        img.thumbnail(thumb_size, Image.ANTIALIAS)
        output_image.paste(img, (w[0],h[2]))
        output_image.paste(img, (w[1],h[2]))

        # Image 3
        img = Image.open(input_filenames[3])
        img.thumbnail(thumb_size, Image.ANTIALIAS)
        output_image.paste(img, (w[0],h[3]))
        output_image.paste(img, (w[1],h[3]))

        sleep(0.01)
        output_image = output_image.convert(mode)

        # Text
        draw = ImageDraw.Draw(output_image)
        font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 80, encoding="unic")

        def drawTextCentered(x, y, W, text):
            w, h = font.getsize(text)
            draw.text((x+(W-w)/2,y), text, "black", font)
        #drawTextCentered(0, 0, thumb_size[0], "Ylva & Simon")
        #drawTextCentered(w[1], 0, thumb_size[0], "Ylva & Simon")
        #bottom = outer_bordery+4*(thumb_size[1]+inner_bordery)
        #drawTextCentered(0, bottom, thumb_size[0], "2018-06-09")
        #drawTextCentered(w[1], bottom, thumb_size[0], "2018-06-09")

        # Save assembled image
        sleep(0.01)
        output_filename = self.prints.get_next()
        output_image.save(output_filename, "JPEG")
        sleep(0.01)
        return output_filename

    def show_preview(self, seconds, should_count=True):
        secs = abs(seconds)
        if secs == 1:
            sleep(1)
            self.display.cancel_events()
        elif self.camera.has_preview() and not seconds < 0:
            tic = time()
            toc = time() - tic
            while toc < secs:
                self.display.clear()
                buff = self.camera.take_preview_buff()
                img = Image.open(StringIO.StringIO(buff))
                sleep(0.01)
                img = img.convert(mode)
                img = img.convert("RGB")
                pygameimg = pygame.image.frombuffer(img.tobytes(), img.size, img.mode)
                self.display.show_picture(image=pygameimg, flip=True) 
                self.display.show_message(str(secs - int(toc)) + "                                    ")
                if toc < 10 and not should_count:
                    self.display.show_message(u"\n\n\n\n\n\n\n\nAvbryt                    ")

                self.display.apply()
                sleep(0.01)

                # Limit progress to 1 "second" per preview (e.g., too slow on Raspi 1)
                toc = min(toc + 1, time() - tic)

                r, e = self.display.check_for_event()
                if not should_count and r and self.convert_event(e) == 2:
                    self.display.cancel_events()
                    sleep(0.01)
                    return
        else:
            for i in range(secs):
                self.display.clear()
                sleep(0.01)
                self.display.show_message(str(secs - i))
                self.display.apply()
                sleep(1)

    def take_picture(self):
        """Implements the picture taking routine"""
        # Disable lamp
        self.gpio.set_output(self.lamp_channel, 0)

        # Show pose message
        self.display.clear()
        self.display.show_message(u"POSERA!\n\nTar fyra bilder...");
        self.display.apply()
        sleep(2)

        # Extract display and image sizes
        display_size = self.display.get_size()
        outsize = (int(display_size[0]/2), int(display_size[1]/2))

        # Take pictures
        filenames = [i for i in range(4)]
        for x in range(4):
            # Countdown
            if x==0:
                self.show_preview(self.pose_time_first)
            else:
                self.show_preview(self.pose_time)

            # Try each picture up to 3 times
            remaining_attempts = 3
            while remaining_attempts > 0:
                remaining_attempts = remaining_attempts - 1

                self.display.clear()
                self.display.show_message(u"OMELETT!!!\n\n" + str(x+1) + " av 4")
                self.display.apply()

                tic = time()

                try:
                    filenames[x] = self.camera.take_picture("/tmp/photobooth_%02d.jpg" % x)
                    remaining_attempts = 0
                except CameraException as e:
                    # On recoverable errors: display message and retry
                    if e.recoverable:
                        if remaining_attempts > 0:
                            self.display.clear()
                            self.display.show_message(e.message)  
                            self.display.apply()
                            sleep(5)
                        else:
                            raise CameraException("Giving up! Please start over!", False)
                    else:
                       raise e

                # Measure used time and sleep a second if too fast 
                toc = time() - tic
                if toc < 1.0:
                    sleep(1.0 - toc)

        # Show 'Wait'
        self.display.clear()
        self.display.show_message(u"Vänta!\n\nLaddar...")
        self.display.apply()
        sleep(0.01)

        self.camera.set_idle()
        sleep(0.01)

        # Assemble them
        outfile = self.assemble_pictures(filenames, display_size)
        sleep(0.01)

        # Show pictures for 10 seconds
        self.display.clear()
        self.display.show_picture(outfile, display_size, (0,0))
        self.display.apply()
        sleep(0.01)

        self.display.clear()
        self.display.show_picture(outfile, display_size, (0,0))
        self.display.show_message(u"                    Skriv ut\n\n\n\n\n\n\n\n\n", color=(255,0,0))
        self.display.show_message(u"\n\n\n\n\n\n\n\nAvbryt                 ")
        self.display.apply()
        self.run_after(filenames)

        #self.display.clear()
        #self.display.show_picture(outfile, display_size, (0,0))
        #self.display.show_message(u"Laddar upp")
        #self.display.apply()
        #self.upload(filenames)

        # Reenable lamp
        self.gpio.set_output(self.lamp_channel, 1)

    def run_after(self,filenames):
        while True:
            event = self.display.wait_for_event()
            if not self.handle_event_after(event,filenames):
                return

    def handle_event_after(self, event, filesnames):
        code = self.convert_event(event)
        if code == 0:
            self.teardown()
        elif code == 1:
            self.print_out(filesnames)
            self.display.cancel_events()
            return False
        elif code == 2:
            self.display.cancel_events()
            return False

        return True

    def print_out(self, filenames):
        display_size = self.display.get_size()

        # Show 'Wait'
        self.display.clear()
        self.display.show_message(u"Vänta!\n\nLaddar...")
        self.display.apply()
        sleep(0.01)

        # Assemble them
        outfile = self.assemble_print(filenames, (self.pic_size[1],self.pic_size[0]))
        sleep(0.01)

        # Show pictures for 10 seconds
        self.display.clear()
        self.display.show_picture(outfile, display_size, (0,0))
        self.display.show_message(u"Vänta!\n\nSkriver ut...")
        self.display.apply()
        sleep(0.01)

        os.system("lp -o fit-to-page %s" % outfile)
        sleep(10)

    def upload(self, filenames):
        sleep(10)