<commit_before>import sublime
import sublime_plugin

import glob
import os
import sys

# Makes sublime_lib package available for all packages.
if not os.path.join(sublime.packages_path(), "AAAPackageDev/Lib") in sys.path:
    sys.path.append(os.path.join(sublime.packages_path(), "AAAPackageDev/Lib"))

from sublime_lib.path import root_at_packages

DEBUG = 1
THIS_PACKAGE = "AAAPackageDev"

status = sublime.status_message
error = sublime.error_message
join_path = os.path.join
path_exists = os.path.exists

DEFAULT_DIRS = (
            "Snippets",
            "Support",
            "Docs",
            "Macros",
            "bin",
            "data"
            )

# name, default template
DEFAULT_FILES = (
    ("LICENSE.txt", None),
    ("README.rst", root_at_packages(THIS_PACKAGE, "data/README.rst")),
    (".hgignore", root_at_packages(THIS_PACKAGE, "data/hgignore.txt")),
    (".gitignore", root_at_packages(THIS_PACKAGE, "data/gitignore.txt")),
    ("bin/MakeRelease.ps1", root_at_packages(THIS_PACKAGE, "data/MakeRelease.ps1")),
    ("bin/CleanUp.ps1", root_at_packages(THIS_PACKAGE, "data/CleanUp.ps1")),
    ("data/html_template.txt", root_at_packages(THIS_PACKAGE, "data/html_template.txt")),
    ("data/main.css", root_at_packages(THIS_PACKAGE, "data/main.css")),
    ("setup.py", root_at_packages(THIS_PACKAGE, "data/setup.py")),
)

class NewPackageCommand(sublime_plugin.WindowCommand):

    def on_done(self, pkg_name):
        pam = PackageManager()
        if pam.exists(pkg_name):
            error("  NewPackage -- Error\n\n"
                  "  Package '" + pkg_name + "' already exists.\n"
                  "  You cannot overwrite an existing package."
            )
            return

        pam.create_new(pkg_name)

    def on_cancel(self):
        status('on_cancel')

    def on_changed(self):
        status('on_changed')

    def run(self):
        self.window.show_input_panel(
                            "New Package Name", '', self.on_done, None, None)

class DeletePackageCommand(sublime_plugin.WindowCommand):
    def run(self):
        pam = PackageManager()
        pam.browse()

class PackageManager(object):

    def is_installed(self, name):
        raise NotImplemented

    def exists(self, name):
        return path_exists(root_at_packages(name))

    def browse(self):
        # Let user choose.
        sublime.active_window().run_command("open_dir",
                                            {"dir": sublime.packages_path()})

    def create_new(self, name):
        print "[NewPackage] Creating new package...",
        print root_at_packages(name)

        if self.dry_run:
            msg = "[NewPackage] ** Nothing done. This was a test. **"
            print msg
            status(msg)
            return

        # Create top folder, default folders, default files.
        map(os.makedirs, [root_at_packages(name, d) for d in DEFAULT_DIRS])

        for f, template in [(root_at_packages(name, fname), template)
                                        for fname, template in DEFAULT_FILES]:
            with open(f, 'w') as fh:
                if template:
                    try:
                        content = "".join(open(template, 'r').readlines()) % \
                                                        {"package_name": name}
                    except:
                        pass
                    finally:
                        content = "".join(open(template, 'r').readlines())

                    fh.write(content)

        msg = "[NewPackage] Created new package '%s'." % name
        print msg
        status(msg)

    def __init__(self, dry_run=False):
        self.dry_run = dry_run<commit_msg>Whitespace<commit_after>import sublime
import sublime_plugin

import glob
import os
import sys

# Makes sublime_lib package available for all packages.
if not os.path.join(sublime.packages_path(), "AAAPackageDev/Lib") in sys.path:
    sys.path.append(os.path.join(sublime.packages_path(), "AAAPackageDev/Lib"))

from sublime_lib.path import root_at_packages

DEBUG = 1
THIS_PACKAGE = "AAAPackageDev"

status = sublime.status_message
error = sublime.error_message
join_path = os.path.join
path_exists = os.path.exists

DEFAULT_DIRS = (
            "Snippets",
            "Support",
            "Docs",
            "Macros",
            "bin",
            "data"
            )

# name, default template
DEFAULT_FILES = (
    ("LICENSE.txt", None),
    ("README.rst", root_at_packages(THIS_PACKAGE, "data/README.rst")),
    (".hgignore", root_at_packages(THIS_PACKAGE, "data/hgignore.txt")),
    (".gitignore", root_at_packages(THIS_PACKAGE, "data/gitignore.txt")),
    ("bin/MakeRelease.ps1", root_at_packages(THIS_PACKAGE, "data/MakeRelease.ps1")),
    ("bin/CleanUp.ps1", root_at_packages(THIS_PACKAGE, "data/CleanUp.ps1")),
    ("data/html_template.txt", root_at_packages(THIS_PACKAGE, "data/html_template.txt")),
    ("data/main.css", root_at_packages(THIS_PACKAGE, "data/main.css")),
    ("setup.py", root_at_packages(THIS_PACKAGE, "data/setup.py")),
)

class NewPackageCommand(sublime_plugin.WindowCommand):

    def on_done(self, pkg_name):
        pam = PackageManager()
        if pam.exists(pkg_name):
            error("  NewPackage -- Error\n\n"
                  "  Package '" + pkg_name + "' already exists.\n"
                  "  You cannot overwrite an existing package."
            )
            return

        pam.create_new(pkg_name)

    def on_cancel(self):
        status('on_cancel')

    def on_changed(self):
        status('on_changed')

    def run(self):
        self.window.show_input_panel(
                            "New Package Name", '', self.on_done, None, None)

class DeletePackageCommand(sublime_plugin.WindowCommand):
    def run(self):
        pam = PackageManager()
        pam.browse()

class PackageManager(object):

    def is_installed(self, name):
        raise NotImplemented

    def exists(self, name):
        return path_exists(root_at_packages(name))

    def browse(self):
        # Let user choose.
        sublime.active_window().run_command("open_dir",
                                            {"dir": sublime.packages_path()})

    def create_new(self, name):
        print "[NewPackage] Creating new package...",
        print root_at_packages(name)

        if self.dry_run:
            msg = "[NewPackage] ** Nothing done. This was a test. **"
            print msg
            status(msg)
            return

        # Create top folder, default folders, default files.
        map(os.makedirs, [root_at_packages(name, d) for d in DEFAULT_DIRS])

        for f, template in [(root_at_packages(name, fname), template)
                                        for fname, template in DEFAULT_FILES]:
            with open(f, 'w') as fh:
                if template:
                    try:
                        content = "".join(open(template, 'r').readlines()) % \
                                                        {"package_name": name}
                    except:
                        pass
                    finally:
                        content = "".join(open(template, 'r').readlines())

                    fh.write(content)

        msg = "[NewPackage] Created new package '%s'." % name
        print msg
        status(msg)

    def __init__(self, dry_run=False):
        self.dry_run = dry_run<|endoftext|>


<commit_before>
# Copyright (C) 2016 Pelagicore AB
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
#
# For further information see LICENSE

import pytest

import os

from testframework import Container

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

##### Configs #####

# These configurations are passed to the Helper to write Service Manifests
# to file which can be read by ConfigStore when initiating the Agent.

# This function is used by the 'agent' fixture to know where the log should be stored
def logfile_path():
    return CURRENT_DIR + "/test.log"

# This function is used by the 'agent' fixture to know where to search for capabilities
def caps_dirs():
    return "{}/caps.d/".format(CURRENT_DIR), "{}/caps.default.d/".format(CURRENT_DIR)

# These default values are used to pass various test specific values and
# configurations to the Container helper. Tests that need to add, remove or
# update entries can simply base their dict on this one for convenience.
DATA = {
    Container.CONFIG: '[{"enableWriteBuffer": false}]',
    Container.BIND_MOUNT_DIR: "/gateways/app",
    Container.HOST_PATH: CURRENT_DIR,
    Container.READONLY: False
}

@pytest.mark.usefixtures("dbus_launch", "agent", "assert_no_proxy")
class TestCaps(object):
    """ This suite tests that capabilities can be used with SoftwareContainer with
        expected results.

        The tests use the Agent D-Bus interface to enable gateway configurations,
        for a specified list of capabilities. Default gateway configurations will
        always be applied.

        The purpose is not to test the gatweays or their configs, which is done in
        more specific test suites, but rather to make sure the capabilities result
        in the correct gateway configs being applied.
    """

    def test_set_caps_only_default(self):
        """ Test that setting the default capabilities works when sending
            an empty list of capabilities, i.e. no error is returned
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities([])
            assert caps_set is True

            ## TODO verify that config is valid and can be used
        finally:
            sc.terminate()

    def test_set_caps(self):
        """ Test that setting an existing capability works,
            i.e. no error is returned
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities(["com.pelagicore.sample.simple"])
            assert caps_set is True

            ## TODO verify that config is valid and can be used
        finally:
            sc.terminate()

    def test_evil_caps(self):
        """ Test that setting a non-existing capability works,
            i.e. no error is returned by the D-Bus API.
            Note: Since we do have a default Service Manifest this test
            will still send configuration to D-BUS.
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities(["test.dbus", "test.network"])
            assert caps_set is True ## This may need to be revised if error handling is changed

            ## The default config will be applied.
            ## TODO verify that config is valid and can be used?
        finally:
            sc.terminate()
<commit_msg>Add xfail to service test in test_caps<commit_after>
# Copyright (C) 2016 Pelagicore AB
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
#
# For further information see LICENSE

import pytest

import os

from testframework import Container

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

##### Configs #####

# These configurations are passed to the Helper to write Service Manifests
# to file which can be read by ConfigStore when initiating the Agent.

# This function is used by the 'agent' fixture to know where the log should be stored
def logfile_path():
    return CURRENT_DIR + "/test.log"

# This function is used by the 'agent' fixture to know where to search for capabilities
def caps_dirs():
    return "{}/caps.d/".format(CURRENT_DIR), "{}/caps.default.d/".format(CURRENT_DIR)

# These default values are used to pass various test specific values and
# configurations to the Container helper. Tests that need to add, remove or
# update entries can simply base their dict on this one for convenience.
DATA = {
    Container.CONFIG: '[{"enableWriteBuffer": false}]',
    Container.BIND_MOUNT_DIR: "/gateways/app",
    Container.HOST_PATH: CURRENT_DIR,
    Container.READONLY: False
}

@pytest.mark.usefixtures("dbus_launch", "agent", "assert_no_proxy")
class TestCaps(object):
    """ This suite tests that capabilities can be used with SoftwareContainer with
        expected results.

        The tests use the Agent D-Bus interface to enable gateway configurations,
        for a specified list of capabilities. Default gateway configurations will
        always be applied.

        The purpose is not to test the gatweays or their configs, which is done in
        more specific test suites, but rather to make sure the capabilities result
        in the correct gateway configs being applied.
    """

    def test_set_caps_only_default(self):
        """ Test that setting the default capabilities works when sending
            an empty list of capabilities, i.e. no error is returned
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities([])
            assert caps_set is True

            ## TODO verify that config is valid and can be used
        finally:
            sc.terminate()

    def test_set_caps(self):
        """ Test that setting an existing capability works,
            i.e. no error is returned
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities(["com.pelagicore.sample.simple"])
            assert caps_set is True

            ## TODO verify that config is valid and can be used
        finally:
            sc.terminate()

    @pytest.mark.xfail() # See reported issue
    def test_evil_caps(self):
        """ Test that setting a non-existing capability works,
            i.e. no error is returned by the D-Bus API.
            Note: Since we do have a default Service Manifest this test
            will still send configuration to D-BUS.
        """
        sc = Container()
        try:
            success = sc.start(DATA)
            assert success is True

            caps_set = sc.set_capabilities(["test.dbus", "test.network"])
            assert caps_set is False ## This should fail when error handling is revised
        finally:
            sc.terminate()
<|endoftext|>


<commit_before>#!/usr/bin/env python
from collections import deque
from pygame.locals import *
import numpy as np
import argparse, imutils, cv2, pygame, random, sys

class PistolGame(object):
    FONT_SIZE = 64# font size for words
    SCORE_SIZE = 32# font size for score

    GAME_TIME = 60# number of seconds to complete the game

    BLACK = (0,0,0)
    WHITE = (255,255,255)
    RED = (255,0,0)
    BLUE = (0,162,232)

    def __init__(self):
        pygame.init()
        pygame.mixer.init()

        self.sound_shot = pygame.mixer.Sound('audio\\shot.ogg')
        self.sound_wrong_shot = pygame.mixer.Sound('audio\\nelsonlaugh.ogg')
        self.sound_miss = pygame.mixer.Sound('audio\\ricochet.ogg')
        self.image_shot = pygame.image.load('images\\bang.png')

##        self.object_lower = (89, 230, 230)# HSV color range for object to be tracked
##        self.object_upper = (108, 255, 255)
        self.object_lower = (94, 126, 129)# HSV color range for object to be tracked
        self.object_upper = (131, 255, 255)

        self.translations = {'electrician':'electricista','gardener':'jardinero','mechanic':'mecanico','bus driver':'chofer de autobus',
				'hairdresser':'estilista','construction worker':'obrero','mason':'albail','pump attendant':'despachador',
				'garbage man':'recogedor de basura','mailman':'cartero','architect':'arquitecto','cook':'cocinero',
				'photographer':'fotografo','butcher':'carnicero','waiter':'mesero','waitress':'mesera','dentist':'dentista',
				'baker':'panadero','cleaning lady':'limpiadora','salesman':'vendedor','actress':'actriz','artist':'artista',
				'doctor':'doctor','engineer':'ingeniero','fireman':'bombero','housewife':'ama de casa','nurse':'enfermera',
				'pilot':'piloto','policeman':'policia','cashier':'cajera','painter':'pintor','secretary':'secretaria',
				'singer':'cantante','veterinarian':'veterinario','soldier':'soldado','carpenter':'carpintero',
				'businessman':'hombre de negocios','detective':'detective','plumber':'plomero','surgeon':'cirujano',
				'writer':'escritor','farmer':'campesino','spy':'espia','lawyer':'abogado','judge':'juez','journalist':'periodista',
				'teacher':'maestro','delivery boy':'repartidor'}

		self.professions = ['electrician', 'gardener', 'mechanic', 'bus driver', 'hairdresser', 'construction worker', 'mason',
                'pump attendant', 'garbage man', 'mailman', 'architect', 'cook', 'photographer', 'butcher', 'waiter',
                'waitress', 'dentist', 'baker',	'cleaning lady', 'salesman', 'actress', 'artist', 'doctor', 'engineer',
				'fireman', 'housewife', 'nurse', 'pilot', 'policeman', 'cashier', 'painter', 'secretary', 'singer',
                'veterinarian', 'soldier', 'carpenter', 'businessman', 'detective', 'plumber', 'surgeon', 'writer',
                'farmer', 'spy', 'lawyer', 'judge', 'journalist', 'teacher', 'delivery boy']

        self.finished = False

        self.game_display = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        pygame.display.set_caption('Pistolero Professions Game')
        self.display_width, self.display_height = pygame.display.get_surface().get_size()
        self.game_display.fill(PistolGame.WHITE)
        pygame.display.update()

    def text_objects(self, text, font):
        text_surface = font.render(text, True, PistolGame.BLACK)
        return text_surface, text_surface.get_rect()

    def message_display_center(self, text, tuple_center):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.SCORE_SIZE))
        text_rect.center = tuple_center
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_topleft(self, text, tuple_topleft):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.topleft = tuple_topleft
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_bottomleft(self, text, tuple_bottomleft):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.bottomleft = tuple_bottomleft
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_topright(self, text, tuple_topright):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.topright = tuple_topright
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_bottomright(self, text, tuple_bottomright):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.bottomright = tuple_bottomright
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def new_round(self):
        self.selected_verb_list = self.professions[random.randint(0, len(self.professions)-1)]
        random.shuffle(self.selected_verb_list[1])

    def end_game(self):
        self.game_display.fill(PistolGame.WHITE)
        self.message_display_center("GAME OVER", (self.display_width/2, self.display_height/2))
        self.message_display_center("SCORE: {0}".format(str(self.score)), (self.display_width/2, self.display_height/3))
        pygame.display.update()
        pygame.time.delay(3000)
        self.finished = True
        self.camera.release()
        cv2.destroyAllWindows()
        pygame.quit()
        sys.exit()

    def run(self):
        self.camera = cv2.VideoCapture(0)

        self.selected_verb_list = self.professions[random.randint(0, len(self.professions)-1)]
        random.shuffle(self.selected_verb_list[1])

        self.score = 0
        int_x, int_y = 0, 0
        start_ticks = pygame.time.get_ticks()

        while not self.finished:
            seconds = (pygame.time.get_ticks() - start_ticks)/1000
            if PistolGame.GAME_TIME - seconds == 0:
                self.end_game()

            (grabbed, frame) = self.camera.read()

            frame = imutils.resize(frame, width=self.display_width)
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            mask = cv2.inRange(hsv, self.object_lower, self.object_upper)
            mask = cv2.erode(mask, None, iterations=2)
            mask = cv2.dilate(mask, None, iterations=2)

            cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
            if len(cnts) > 0:
                c = max(cnts, key=cv2.contourArea)
                ((x, y), radius) = cv2.minEnclosingCircle(c)
                int_x, int_y = self.display_width - int(x), self.display_height - int(y)
                # if radius > 10:# left here for troubleshooting purposes
                    # cv2.circle(frame, (int_x, int_y), int(radius), (0, 255, 255), 2)
            # cv2.imshow("Frame", frame)

            self.game_display.fill(PistolGame.WHITE)
            rect0 = self.message_display_topleft(self.selected_verb_list[1][0][0], (100, 100))
            rect1 = self.message_display_bottomleft(self.selected_verb_list[1][1][0], (100, self.display_height - 100))
            rect2 = self.message_display_topright(self.selected_verb_list[1][2][0], (self.display_width - 100, 100))
            rect3 = self.message_display_bottomright(self.selected_verb_list[1][3][0], (self.display_width - 100, self.display_height - 100))
            react_score = self.message_display_center("{0} {1}".format(str(self.score), PistolGame.GAME_TIME - seconds), (self.display_width/2, self.display_height - 50))
            base_verb = self.message_display_center(self.selected_verb_list[0], (self.display_width/2, 50))
            pygame.draw.circle(self.game_display, PistolGame.BLUE, (self.display_width/2, self.display_height/2), 40)# change tracking circle radius as necessary
            if rect0.collidepoint(int_x, int_y) or rect1.collidepoint(int_x, int_y) or rect2.collidepoint(int_x, int_y) or rect3.collidepoint(int_x, int_y):
                pygame.draw.circle(self.game_display, PistolGame.RED,(int_x, int_y), 10)
            else:
                pygame.draw.circle(self.game_display, PistolGame.BLACK,(int_x, int_y), 10)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.finished = True
                if event.type == pygame.KEYUP and event.key == pygame.K_a:
                    # update to use dictionary here?
                    if (rect0.collidepoint(int_x, int_y) and self.selected_verb_list[1][0][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect0.center[0]-self.image_shot.get_width()/2, rect0.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect1.collidepoint(int_x, int_y) and self.selected_verb_list[1][1][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect1.center[0]-self.image_shot.get_width()/2, rect1.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect2.collidepoint(int_x, int_y) and self.selected_verb_list[1][2][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect2.center[0]-self.image_shot.get_width()/2, rect2.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect3.collidepoint(int_x, int_y) and self.selected_verb_list[1][3][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect3.center[0]-self.image_shot.get_width()/2, rect3.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect0.collidepoint(int_x, int_y) and self.selected_verb_list[1][0][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect0.center[0]-self.image_shot.get_width()/2, rect0.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect1.collidepoint(int_x, int_y) and self.selected_verb_list[1][1][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect1.center[0]-self.image_shot.get_width()/2, rect1.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect2.collidepoint(int_x, int_y) and self.selected_verb_list[1][2][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect2.center[0]-self.image_shot.get_width()/2, rect2.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect3.collidepoint(int_x, int_y) and self.selected_verb_list[1][3][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect3.center[0]-self.image_shot.get_width()/2, rect3.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    else:
                        self.sound_miss.play()

                    self.new_round()

            pygame.display.update()

        camera.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    pg = PistolGame()
    pg.run()
<commit_msg>need to unify message display functions<commit_after>#!/usr/bin/env python
from collections import deque
from pygame.locals import *
import numpy as np
import argparse, imutils, cv2, pygame, random, sys

class PistolGame(object):
    FONT_SIZE = 64# font size for words
    SCORE_SIZE = 32# font size for score

    GAME_TIME = 60# number of seconds to complete the game

    BLACK = (0,0,0)
    WHITE = (255,255,255)
    RED = (255,0,0)
    BLUE = (0,162,232)

    def __init__(self):
        pygame.init()
        pygame.mixer.init()

        self.sound_shot = pygame.mixer.Sound('audio\\shot.ogg')
        self.sound_wrong_shot = pygame.mixer.Sound('audio\\nelsonlaugh.ogg')
        self.sound_miss = pygame.mixer.Sound('audio\\ricochet.ogg')
        self.image_shot = pygame.image.load('images\\bang.png')

##        self.object_lower = (89, 230, 230)# HSV color range for object to be tracked
##        self.object_upper = (108, 255, 255)
        self.object_lower = (94, 126, 129)# HSV color range for object to be tracked
        self.object_upper = (131, 255, 255)

        self.translations = {'electrician':'electricista','gardener':'jardinero','mechanic':'mecanico','bus driver':'chofer de autobus',
				'hairdresser':'estilista','construction worker':'obrero','mason':'albail','pump attendant':'despachador',
				'garbage man':'recogedor de basura','mailman':'cartero','architect':'arquitecto','cook':'cocinero',
				'photographer':'fotografo','butcher':'carnicero','waiter':'mesero','waitress':'mesera','dentist':'dentista',
				'baker':'panadero','cleaning lady':'limpiadora','salesman':'vendedor','actress':'actriz','artist':'artista',
				'doctor':'doctor','engineer':'ingeniero','fireman':'bombero','housewife':'ama de casa','nurse':'enfermera',
				'pilot':'piloto','policeman':'policia','cashier':'cajera','painter':'pintor','secretary':'secretaria',
				'singer':'cantante','veterinarian':'veterinario','soldier':'soldado','carpenter':'carpintero',
				'businessman':'hombre de negocios','detective':'detective','plumber':'plomero','surgeon':'cirujano',
				'writer':'escritor','farmer':'campesino','spy':'espia','lawyer':'abogado','judge':'juez','journalist':'periodista',
				'teacher':'maestro','delivery boy':'repartidor'}

		self.professions = ['electrician', 'gardener', 'mechanic', 'bus driver', 'hairdresser', 'construction worker', 'mason',
                'pump attendant', 'garbage man', 'mailman', 'architect', 'cook', 'photographer', 'butcher', 'waiter',
                'waitress', 'dentist', 'baker',	'cleaning lady', 'salesman', 'actress', 'artist', 'doctor', 'engineer',
				'fireman', 'housewife', 'nurse', 'pilot', 'policeman', 'cashier', 'painter', 'secretary', 'singer',
                'veterinarian', 'soldier', 'carpenter', 'businessman', 'detective', 'plumber', 'surgeon', 'writer',
                'farmer', 'spy', 'lawyer', 'judge', 'journalist', 'teacher', 'delivery boy']

        self.finished = False

        self.game_display = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        pygame.display.set_caption('Pistolero Professions Game')
        self.display_width, self.display_height = pygame.display.get_surface().get_size()
        self.game_display.fill(PistolGame.WHITE)
        pygame.display.update()

    def text_objects(self, text, font):
        text_surface = font.render(text, True, PistolGame.BLACK)
        return text_surface, text_surface.get_rect()

    # these message display functions need to be combined!
    def message_display_center(self, text, tuple_center):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.SCORE_SIZE))
        text_rect.center = tuple_center
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_topleft(self, text, tuple_topleft):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.topleft = tuple_topleft
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_bottomleft(self, text, tuple_bottomleft):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.bottomleft = tuple_bottomleft
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_topright(self, text, tuple_topright):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.topright = tuple_topright
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def message_display_bottomright(self, text, tuple_bottomright):
        text_surf, text_rect = self.text_objects(text, pygame.font.Font('arial.ttf', PistolGame.FONT_SIZE))
        text_rect.bottomright = tuple_bottomright
        self.game_display.blit(text_surf, text_rect)
        return text_rect

    def new_round(self):
        self.selected_verb_list = self.professions[random.randint(0, len(self.professions)-1)]
        random.shuffle(self.selected_verb_list[1])

    def end_game(self):
        self.game_display.fill(PistolGame.WHITE)
        self.message_display_center("GAME OVER", (self.display_width/2, self.display_height/2))
        self.message_display_center("SCORE: {0}".format(str(self.score)), (self.display_width/2, self.display_height/3))
        pygame.display.update()
        pygame.time.delay(3000)
        self.finished = True
        self.camera.release()
        cv2.destroyAllWindows()
        pygame.quit()
        sys.exit()

    def run(self):
        self.camera = cv2.VideoCapture(0)

        self.selected_verb_list = self.professions[random.randint(0, len(self.professions)-1)]
        random.shuffle(self.selected_verb_list[1])

        self.score = 0
        int_x, int_y = 0, 0
        start_ticks = pygame.time.get_ticks()

        while not self.finished:
            seconds = (pygame.time.get_ticks() - start_ticks)/1000
            if PistolGame.GAME_TIME - seconds == 0:
                self.end_game()

            (grabbed, frame) = self.camera.read()

            frame = imutils.resize(frame, width=self.display_width)
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            mask = cv2.inRange(hsv, self.object_lower, self.object_upper)
            mask = cv2.erode(mask, None, iterations=2)
            mask = cv2.dilate(mask, None, iterations=2)

            cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
            if len(cnts) > 0:
                c = max(cnts, key=cv2.contourArea)
                ((x, y), radius) = cv2.minEnclosingCircle(c)
                int_x, int_y = self.display_width - int(x), self.display_height - int(y)
                # if radius > 10:# left here for troubleshooting purposes
                    # cv2.circle(frame, (int_x, int_y), int(radius), (0, 255, 255), 2)
            # cv2.imshow("Frame", frame)

            self.game_display.fill(PistolGame.WHITE)
            rect0 = self.message_display_topleft(self.selected_verb_list[1][0][0], (100, 100))
            rect1 = self.message_display_bottomleft(self.selected_verb_list[1][1][0], (100, self.display_height - 100))
            rect2 = self.message_display_topright(self.selected_verb_list[1][2][0], (self.display_width - 100, 100))
            rect3 = self.message_display_bottomright(self.selected_verb_list[1][3][0], (self.display_width - 100, self.display_height - 100))
            react_score = self.message_display_center("{0} {1}".format(str(self.score), PistolGame.GAME_TIME - seconds), (self.display_width/2, self.display_height - 50))
            base_verb = self.message_display_center(self.selected_verb_list[0], (self.display_width/2, 50))
            pygame.draw.circle(self.game_display, PistolGame.BLUE, (self.display_width/2, self.display_height/2), 40)# change tracking circle radius as necessary
            if rect0.collidepoint(int_x, int_y) or rect1.collidepoint(int_x, int_y) or rect2.collidepoint(int_x, int_y) or rect3.collidepoint(int_x, int_y):
                pygame.draw.circle(self.game_display, PistolGame.RED,(int_x, int_y), 10)
            else:
                pygame.draw.circle(self.game_display, PistolGame.BLACK,(int_x, int_y), 10)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.finished = True
                if event.type == pygame.KEYUP and event.key == pygame.K_a:
                    # update to use dictionary here?
                    if (rect0.collidepoint(int_x, int_y) and self.selected_verb_list[1][0][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect0.center[0]-self.image_shot.get_width()/2, rect0.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect1.collidepoint(int_x, int_y) and self.selected_verb_list[1][1][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect1.center[0]-self.image_shot.get_width()/2, rect1.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect2.collidepoint(int_x, int_y) and self.selected_verb_list[1][2][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect2.center[0]-self.image_shot.get_width()/2, rect2.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect3.collidepoint(int_x, int_y) and self.selected_verb_list[1][3][1] == "a"):
                        self.sound_shot.play()
                        self.score+=1
                        self.game_display.blit(self.image_shot, (rect3.center[0]-self.image_shot.get_width()/2, rect3.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect0.collidepoint(int_x, int_y) and self.selected_verb_list[1][0][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect0.center[0]-self.image_shot.get_width()/2, rect0.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect1.collidepoint(int_x, int_y) and self.selected_verb_list[1][1][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect1.center[0]-self.image_shot.get_width()/2, rect1.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect2.collidepoint(int_x, int_y) and self.selected_verb_list[1][2][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect2.center[0]-self.image_shot.get_width()/2, rect2.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    elif (rect3.collidepoint(int_x, int_y) and self.selected_verb_list[1][3][1] == "q"):
                        self.sound_wrong_shot.play()
                        self.score-=1
                        self.game_display.blit(self.image_shot, (rect3.center[0]-self.image_shot.get_width()/2, rect3.center[1]-self.image_shot.get_height()/2))
                        pygame.display.update()
                        pygame.time.delay(300)
                    else:
                        self.sound_miss.play()

                    self.new_round()

            pygame.display.update()

        camera.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    pg = PistolGame()
    pg.run()
<|endoftext|>


<commit_before># Begin configuration
TITLE    = "ESP8266 WiFi Configurator"
GPIO_NUM = 2
# End configuration

import network
import machine
import usocket

import accessPoints as ap
accessPointsFile = 'accessPoints.json'
aPoints = ap.AccessPoints(accessPointsFile)

# do a little test
point = aPoints.getAccessPointData('testSSID')
point['password'] = 'testPW'
aPoints.setAccessPointData('testSSID', point)

import cssStash as cssStash
css = cssStash.CSS()
cssString = css.getCSS()

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
ap_if = network.WLAN(network.AP_IF) # create access-point interface
ap_if.active(True)         # activate it
try:
    # this doesn't work on some devices?
    ap_if.config(essid='ESP-AP') # set the ESSID of the access point
except OSError as ose:
    print(ose)
ifc = ap_if.ifconfig()
print('server at IP', ifc[0])

pin = machine.Pin(GPIO_NUM)

pin.init(pin.OUT)
try:
    pin.low()
except AttributeError:
    pin.off()

pwform = '''

Set access point password

<form method='GET' action='/setpw'>
    SSID: verified = VER

    Password: <input type="text" class="text" name="password" value="PW">

    Name: <input type="text" class="text" name="apName" value="NAME" placeholder="optional">

    <input type="submit" name="testpw" value="Test">
    <input type="submit" name="savepw" value="Save">

    <input type="hidden" name="ssid" value="SSID">
</form>
'''

def makeActionButton(action, query, value):
    buttonStr = "<form method='POST' action='" + action + "?" + query.decode() + "'>"
    buttonStr += "<input type='submit' value='" + value + "'>"
    # <input type="hidden" name="query" value="something">
    buttonStr += "</form>"
    # print(buttonStr)
    return buttonStr

def makeRadio(name, value, mode):
    radioStr = "<input onChange='this.form.submit();' type='radio' name='" + name + "' value='" + value + "'/>"
    # print(radioStr)
    return radioStr

def makeAPtable(points):
    pointsStr = '
Visible access points
'
    pointsStr += '<form action="/getpw"" method="GET">'
    pointsStr += '
SSID	Open	Str	Known	Set
'

    for i, point in enumerate(points):
        # print(point)
        aPoint = aPoints.getAccessPointData(point["ssid"])
        if 'verified' in aPoint and aPoint['verified'] == 1:
            point['verified'] = 'Y'
        else:
            point['verified'] = 'N'
        radioStr = makeRadio('radioSet', point["ssid"], point["authmode"])
        pointsStr += '
' + point["ssid"] + '	' + point["authmode"] + '	' + point["rssi"] + '	' + point["verified"] + '	' + radioStr + '
'
    pointsStr += '
'
    pointsStr += '</form>
'
    return pointsStr

def emitScanTable(socket):
    points = aPoints.doScan(sta_if)
    apTable = makeAPtable(points)
    socket.write(apTable)

def emitPWform(socket, rawQuery):
    asString = str(rawQuery, "utf-8")
    parsedQuery = queryParse(asString)
    # print('emitPWform>>> ', parsedQuery)
    ssid = parsedQuery['radioSet']
    point = aPoints.getAccessPointData(ssid)

    actionButton = "<input type='submit' value='Submit'>"
    pwf = pwform
    pwf = pwf.replace('SSID', ssid)
    if 'password' in point:
        pwf = pwf.replace('PW', point['password'])
    if 'apName' in point:
        pwf = pwf.replace('NAME', point['apName'])
    else:
        pwf = pwf.replace('NAME', '')
    if 'verified' in point and point['verified'] == 1:
        pwf = pwf.replace('VER', 'yes')
    else:
        pwf = pwf.replace('VER', 'no')
    # print(pwf)
    socket.write(pwf)

def queryParse(queryString):
      result = {}
      pairs = queryString.split('&')
      for i, pair in enumerate(pairs):
          if '=' not in pair:
              continue
          key, value = pair.split('=')
          value = value.replace('%2B', ' ')
          value = value.replace('+', ' ')
        #   print('queryParse: ', key, value)
          result[key] = value
      return result

# may have hit the save button or the test button (test and then save)
def handleSetPW(rawQuery):
    asString = str(rawQuery, "utf-8")
    parsedQuery = queryParse(asString)
    # print('>>> ', parsedQuery)

    ssid = parsedQuery['ssid']
    point = aPoints.getAccessPointData(ssid)
    point['password'] = parsedQuery['password']
    point['apName'] = parsedQuery['apName']
    # print(point)

    if 'testpw' in parsedQuery:
        sta_if.active(True)
        sta_if.connect(ssid, point['password'])
        success = aPoints.checkLoop(sta_if, 10000)
        print('checkLoop result:', success)
        if success:
            point['verified'] = 1
        else:
            point['verified'] = 0
        sta_if.active(False)

    aPoints.setAccessPointData(ssid, point)

# this is where we construct the response
def respond(socket, path, query):
    global sta_if
    global aPoints

    print('accessed!')

    socket.write("HTTP/1.1 OK\r\n\r\n")
    socket.write(css.getHeader())
    socket.write(css.getCSS())
    socket.write("<title>"+TITLE+"</title>")
    socket.write("")

    if path == b"/scan":
        emitScanTable(socket)
    elif path == b"/getpw":
        emitPWform(socket, query)
    elif path == b"/setpw":
        emitScanTable(socket)
    else:
        socket.write("
ESP8266 WiFi Configurator
")

    socket.write( makeActionButton('/scan', query, 'Scan') )

    socket.write("

")
    socket.write(" pin " + str(GPIO_NUM) + " status: ")
    if pin.value():
        socket.write("OFF")
    else:
        socket.write("ON")
    socket.write("
")
    if pin.value():
        socket.write( makeActionButton('/off', query, 'turn ON') )
    else:
        socket.write( makeActionButton('/on', query, 'turn OFF') )

    socket.write(css.getFooter())

def err(socket, code, message):
    socket.write("HTTP/1.1 "+code+" "+message+"\r\n\r\n")
    socket.write("
"+message+"
")

# HTTP requests come in here
def handleQuery(socket):
    (method, url, version) = socket.readline().split(b" ")

    if b"?" in url:
        (path, query) = url.split(b"?", 2)
    else:
        (path, query) = (url, b"")
    while True:
        header = socket.readline()
        if header == b"":
            return
        if header == b"\r\n":
            break

    print('path: ', path, 'query:', query)
    if version != b"HTTP/1.0\r\n" and version != b"HTTP/1.1\r\n":
        err(socket, "505", "Version Not Supported")
    elif method == b"GET":
        # print('GET', path, query)
        if path == b"/":
            respond(socket, path, query)
        elif path == b"/getpw":
            # print('received getpw')
            respond(socket, path, query)
        elif path == b"/setpw":
            # print('received setpw')
            # we go ahead and send response so browser doesn't time out
            path = b"/"
            respond(socket, path, query)
            handleSetPW(query)
        else:
            err(socket, "404", "Not Found")
    elif method == b"POST":
        if path == b"/on":
            # print('received ON')
            try:
                pin.high()
            except AttributeError:
                pin.on()
            respond(socket, path, query)
        elif path == b"/off":
            # print('received OFF')
            try:
                pin.low()
            except AttributeError:
                pin.off()
            respond(socket, path, query)
        elif path == b"/scan":
            # print('received scan')
            respond(socket, path, query)
        else:
            err(socket, "404", "Not Found")
    else:
        err(socket, "501", "Not Implemented")

server = usocket.socket()

def mainLoop():
    server.bind(('0.0.0.0', 80))
    server.listen(1)
    while True:
        try:
            (socket, sockaddr) = server.accept()
            handleQuery(socket)
        except OSError as ose:
            print(ose)
            code = ose.args[0]
            if code == 104 or code == 103 or code == 103:
                print('OSError:', code)
                # ECONNRESET or ECONNABORTED or EALREADY
                return code
            socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n")
            socket.write("
Internal Server Error
")
        socket.close()

while True:
    mainLoop()<commit_msg>Added some unescape processing for queries<commit_after># Begin configuration
TITLE    = "ESP8266 WiFi Configurator"
GPIO_NUM = 2
# End configuration

import network
import machine
import usocket

import accessPoints as ap
accessPointsFile = 'accessPoints.json'
aPoints = ap.AccessPoints(accessPointsFile)

# do a little test
point = aPoints.getAccessPointData('testSSID')
point['password'] = 'testPW'
aPoints.setAccessPointData('testSSID', point)

import cssStash as cssStash
css = cssStash.CSS()
cssString = css.getCSS()

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
ap_if = network.WLAN(network.AP_IF) # create access-point interface
ap_if.active(True)         # activate it
try:
    # this doesn't work on some devices?
    ap_if.config(essid='ESP-AP') # set the ESSID of the access point
except OSError as ose:
    print(ose)
ifc = ap_if.ifconfig()
print('server at IP', ifc[0])

pin = machine.Pin(GPIO_NUM)

pin.init(pin.OUT)
try:
    pin.low()
except AttributeError:
    pin.off()

pwform = '''

Set access point password

<form method='GET' action='/setpw'>
    _SSID: verified = _VER

    Password: <input type="text" class="text" name="password" value="_PW">

    Name: <input type="text" class="text" name="apName" value="_NAME" placeholder="optional">

    <input type="submit" name="testpw" value="Test">
    <input type="submit" name="savepw" value="Save">

    <input type="hidden" name="ssid" value="_SSID">
</form>
'''

def makeActionButton(action, query, value):
    buttonStr = "<form method='POST' action='" + action + "?" + query.decode() + "'>"
    buttonStr += "<input type='submit' value='" + value + "'>"
    # <input type="hidden" name="query" value="something">
    buttonStr += "</form>"
    # print(buttonStr)
    return buttonStr

def makeRadio(name, value, mode):
    radioStr = "<input onChange='this.form.submit();' type='radio' name='" + name + "' value='" + value + "'/>"
    # print(radioStr)
    return radioStr

def makeAPtable(points):
    pointsStr = '
Visible access points
'
    pointsStr += '<form action="/getpw"" method="GET">'
    pointsStr += '
SSID	Open	Str	Known	Set
'

    for i, point in enumerate(points):
        # print(point)
        aPoint = aPoints.getAccessPointData(point["ssid"])
        if 'verified' in aPoint and aPoint['verified'] == 1:
            point['verified'] = 'Y'
        else:
            point['verified'] = 'N'
        radioStr = makeRadio('radioSet', point["ssid"], point["authmode"])
        pointsStr += '
' + point["ssid"] + '	' + point["authmode"] + '	' + point["rssi"] + '	' + point["verified"] + '	' + radioStr + '
'
    pointsStr += '
'
    pointsStr += '</form>
'
    return pointsStr

def emitScanTable(socket):
    points = aPoints.doScan(sta_if)
    apTable = makeAPtable(points)
    socket.write(apTable)

def emitPWform(socket, rawQuery):
    asString = str(rawQuery, "utf-8")
    # print('emitPWform>>> ', asString)
    parsedQuery = queryParse(asString)
    # print('emitPWform>>> ', parsedQuery)
    ssid = parsedQuery['radioSet']
    point = aPoints.getAccessPointData(ssid)

    actionButton = "<input type='submit' value='Submit'>"
    pwf = pwform
    # there's probably a more clever way to do the following...
    pwf = pwf.replace('_SSID', ssid)
    if 'password' in point:
        pwf = pwf.replace('_PW', point['password'])
    else:
        pwf = pwf.replace('_PW', '')
    if 'apName' in point:
        pwf = pwf.replace('_NAME', point['apName'])
    else:
        pwf = pwf.replace('_NAME', '')
    if 'verified' in point and point['verified'] == 1:
        pwf = pwf.replace('_VER', 'yes')
    else:
        pwf = pwf.replace('_VER', 'no')
    # print(pwf)
    socket.write(pwf)

reps = {'%20':' ', '%2B':' ', '+':' ', '%27':"'", '%23': '#'}
def unescape(text):
    for i, j in reps.items():
        text = text.replace(i, j)
    return text

def queryParse(queryString):
      result = {}
      pairs = queryString.split('&')
      for i, pair in enumerate(pairs):
          if '=' not in pair:
              continue
          key, value = pair.split('=')
          value = unescape(value)
        #   print('queryParse: ', key, value)
          result[key] = value
      return result

# may have hit the save button or the test button (test and then save)
def handleSetPW(rawQuery):
    asString = str(rawQuery, "utf-8")
    parsedQuery = queryParse(asString)
    # print('>>> ', parsedQuery)

    ssid = parsedQuery['ssid']
    point = aPoints.getAccessPointData(ssid)
    point['password'] = parsedQuery['password']
    point['apName'] = parsedQuery['apName']
    # print(point)

    if 'testpw' in parsedQuery:
        sta_if.active(True)
        sta_if.connect(ssid, point['password'])
        success = aPoints.checkLoop(sta_if, 10000)
        print('checkLoop result:', success)
        if success:
            point['verified'] = 1
        else:
            point['verified'] = 0
        sta_if.active(False)

    aPoints.setAccessPointData(ssid, point)

# this is where we construct the response
def respond(socket, path, query):
    global sta_if
    global aPoints

    print('accessed!')

    socket.write("HTTP/1.1 OK\r\n\r\n")
    socket.write(css.getHeader())
    socket.write(css.getCSS())
    socket.write("<title>"+TITLE+"</title>")
    socket.write("")

    if path == b"/scan":
        emitScanTable(socket)
    elif path == b"/getpw":
        emitPWform(socket, query)
    elif path == b"/setpw":
        emitScanTable(socket)
    else:
        socket.write("
ESP8266 WiFi Configurator
")

    socket.write( makeActionButton('/scan', query, 'Scan') )

    socket.write("

")
    socket.write(" pin " + str(GPIO_NUM) + " status: ")
    if pin.value():
        socket.write("OFF")
    else:
        socket.write("ON")
    socket.write("
")
    if pin.value():
        socket.write( makeActionButton('/off', query, 'turn ON') )
    else:
        socket.write( makeActionButton('/on', query, 'turn OFF') )

    socket.write(css.getFooter())

def err(socket, code, message):
    socket.write("HTTP/1.1 "+code+" "+message+"\r\n\r\n")
    socket.write("
"+message+"
")

# HTTP requests come in here
def handleQuery(socket):
    try:
        (method, url, version) = socket.readline().split(b" ")
    except ValueError:
        print('invalid query')
        return

    if b"?" in url:
        (path, query) = url.split(b"?", 2)
    else:
        (path, query) = (url, b"")
    while True:
        header = socket.readline()
        if header == b"":
            return
        if header == b"\r\n":
            break

    print('path: ', path, 'query:', query)
    if version != b"HTTP/1.0\r\n" and version != b"HTTP/1.1\r\n":
        err(socket, "505", "Version Not Supported")
    elif method == b"GET":
        # print('GET', path, query)
        if path == b"/":
            respond(socket, path, query)
        elif path == b"/getpw":
            # print('received getpw')
            respond(socket, path, query)
        elif path == b"/setpw":
            # print('received setpw')
            # we go ahead and send response so browser doesn't time out
            path = b"/"
            respond(socket, path, query)
            handleSetPW(query)
        else:
            err(socket, "404", "Not Found")
    elif method == b"POST":
        if path == b"/on":
            # print('received ON')
            try:
                pin.high()
            except AttributeError:
                pin.on()
            respond(socket, path, query)
        elif path == b"/off":
            # print('received OFF')
            try:
                pin.low()
            except AttributeError:
                pin.off()
            respond(socket, path, query)
        elif path == b"/scan":
            # print('received scan')
            respond(socket, path, query)
        else:
            err(socket, "404", "Not Found")
    else:
        err(socket, "501", "Not Implemented")

server = usocket.socket()

def mainLoop():
    server.bind(('0.0.0.0', 80))
    server.listen(1)
    while True:
        try:
            (socket, sockaddr) = server.accept()
            handleQuery(socket)
        except OSError as ose:
            print(ose)
            code = ose.args[0]
            if code == 104 or code == 103 or code == 103:
                print('OSError:', code)
                # ECONNRESET or ECONNABORTED or EALREADY
                return code
            socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n")
            socket.write("
Internal Server Error
")
        socket.close()

while True:
    mainLoop()<|endoftext|>


<commit_before># Copyright 2020 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3
"""Library of effects functions."""

from ddsp import core
from ddsp import processors
from ddsp import synths
import gin
import tensorflow.compat.v2 as tf

tf_float32 = core.tf_float32

#------------------ Reverbs ----------------------------------------------------
@gin.register
class Reverb(processors.Processor):
  """Convolutional (FIR) reverb."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               add_dry=True,
               name='reverb'):
    """Takes neural network outputs directly as the impulse response.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response. Only used if
        trainable=True.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, trainable=trainable)
    self._reverb_length = reverb_length
    self._add_dry = add_dry

  def _mask_dry_ir(self, ir):
    """Set first impulse response to zero to mask the dry signal."""
    # Make IR 2-D [batch, ir_size].
    if len(ir.shape) == 1:
      ir = ir[tf.newaxis, :]  # Add a batch dimension
    if len(ir.shape) == 3:
      ir = ir[:, :, 0]  # Remove unnessary channel dimension.
    # Mask the dry signal.
    dry_mask = tf.zeros([int(ir.shape[0]), 1], tf.float32)
    return tf.concat([dry_mask, ir[:, 1:]], axis=1)

  def _match_dimensions(self, audio, ir):
    """Tile the impulse response variable to match the batch size."""
    # Add batch dimension.
    if len(ir.shape) == 1:
      ir = ir[tf.newaxis, :]
    # Match batch dimension.
    batch_size = int(audio.shape[0])
    return tf.tile(ir, [batch_size, 1])

  def build(self, input_shape):
    """Initialize impulse response."""
    super().build(input_shape)
    if self.trainable:
      initializer = tf.random_normal_initializer(mean=0, stddev=1e-6)
      self._ir = self.add_weight(
          name='ir',
          shape=[self._reverb_length],
          dtype=tf.float32,
          initializer=initializer)

  def get_controls(self, audio, ir=None):
    """Convert decoder outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      ir: 3-D Tensor of shape [batch, ir_size, 1] or 2D Tensor of shape
        [batch, ir_size].

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and ir is not provided.
    """
    if self.trainable:
      ir = self._match_dimensions(audio, self._ir)
    else:
      if ir is None:
        raise ValueError('Must provide "ir" tensor if Reverb trainable=False.')

    return {'audio': audio, 'ir': ir}

  def get_signal(self, audio, ir):
    """Apply impulse response.

    Args:
      audio: Dry audio, 2-D Tensor of shape [batch, n_samples].
      ir: 3-D Tensor of shape [batch, ir_size, 1] or 2D Tensor of shape
        [batch, ir_size].

    Returns:
      tensor of shape [batch, n_samples]
    """
    audio, ir = tf_float32(audio), tf_float32(ir)
    ir = self._mask_dry_ir(ir)
    wet = core.fft_convolve(audio, ir, padding='same', delay_compensation=0)
    return (wet + audio) if self._add_dry else wet

@gin.register
class ExpDecayReverb(Reverb):
  """Parameterize impulse response as a simple exponential decay."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               scale_fn=core.exp_sigmoid,
               add_dry=True,
               name='exp_decay_reverb'):
    """Constructor.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response.
      scale_fn: Function by which to scale the network outputs.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, add_dry=add_dry, trainable=trainable)
    self._reverb_length = reverb_length
    self._scale_fn = scale_fn

  def _get_ir(self, gain, decay):
    """Simple exponential decay of white noise."""
    gain = self._scale_fn(gain)
    decay_exponent = 2.0 + tf.exp(decay)
    time = tf.linspace(0.0, 1.0, self._reverb_length)[tf.newaxis, :]
    noise = tf.random.uniform([1, self._reverb_length], minval=-1.0, maxval=1.0)
    ir = gain * tf.exp(-decay_exponent * time) * noise
    return ir

  def build(self, input_shape):
    """Initialize impulse response."""
    super().build(input_shape)
    if self.trainable:
      self._gain = self.add_weight(
          name='gain',
          shape=[1],
          dtype=tf.float32,
          initializer=tf.constant_initializer(2.0))
      self._decay = self.add_weight(
          name='decay',
          shape=[1],
          dtype=tf.float32,
          initializer=tf.constant_initializer(4.0))

  def get_controls(self, audio, gain=None, decay=None):
    """Convert network outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Linear gain of impulse response. Scaled by self._scale_fn.
        2D Tensor of shape [batch, 1]. Not used if trainable=True.
      decay: Exponential decay coefficient. The final impulse response is
        exp(-(2 + exp(decay)) * time) where time goes from 0 to 1.0 over the
        reverb_length samples. 2D Tensor of shape [batch, 1]. Not used if
        trainable=True.

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and gain and decay are not provided.
    """
    if self.trainable:
      gain, decay = self._gain[tf.newaxis, :], self._decay[tf.newaxis, :]
    else:
      if gain is None or decay is None:
        raise ValueError('Must provide "gain" and "decay" tensors if '
                         'ExpDecayReverb trainable=False.')

    ir = self._get_ir(gain, decay)

    if self.trainable:
      ir = self._match_dimensions(audio, ir)

    return {'audio': audio, 'ir': ir}

@gin.register
class FilteredNoiseReverb(Reverb):
  """Parameterize impulse response with outputs of a filtered noise synth."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               window_size=257,
               n_frames=1000,
               n_filter_banks=16,
               scale_fn=core.exp_sigmoid,
               initial_bias=-3.0,
               add_dry=True,
               name='filtered_noise_reverb'):
    """Constructor.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response.
      window_size: Window size for filtered noise synthesizer.
      n_frames: Time resolution of magnitudes coefficients. Only used if
        trainable=True.
      n_filter_banks: Frequency resolution of magnitudes coefficients. Only used
        if trainable=True.
      scale_fn: Function by which to scale the magnitudes.
      initial_bias: Shift the filtered noise synth inputs by this amount
        (before scale_fn) to start generating noise in a resonable range when
        given magnitudes centered around 0.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, add_dry=add_dry, trainable=trainable)
    self._n_frames = n_frames
    self._n_filter_banks = n_filter_banks
    self._synth = synths.FilteredNoise(n_samples=reverb_length,
                                       window_size=window_size,
                                       scale_fn=scale_fn,
                                       initial_bias=initial_bias)

  def build(self, input_shape):
    """Initialize impulse response."""
    super().build(input_shape)
    if self.trainable:
      initializer = tf.random_normal_initializer(mean=0, stddev=1e-2)
      self._magnitudes = self.add_weight(
          name='magnitudes',
          shape=[self._n_frames, self._n_filter_banks],
          dtype=tf.float32,
          initializer=initializer)

  def get_controls(self, audio, magnitudes=None):
    """Convert network outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: Magnitudes tensor of shape [batch, n_frames, n_filter_banks].
        Expects float32 that is strictly positive. Not used if trainable=True.

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and magnitudes are not provided.
    """
    if self.trainable:
      magnitudes = self._magnitudes[tf.newaxis, :]
    else:
      if magnitudes is None:
        raise ValueError('Must provide "magnitudes" tensor if '
                         'FilteredNoiseReverb trainable=False.')

    ir = self._synth(magnitudes)

    if self.trainable:
      ir = self._match_dimensions(audio, ir)

    return {'audio': audio, 'ir': ir}

#------------------ Filters ----------------------------------------------------
@gin.register
class FIRFilter(processors.Processor):
  """Linear time-varying finite impulse response (LTV-FIR) filter."""

  def __init__(self,
               window_size=257,
               scale_fn=core.exp_sigmoid,
               name='fir_filter'):
    super().__init__(name=name)
    self.window_size = window_size
    self.scale_fn = scale_fn

  def get_controls(self, audio, magnitudes):
    """Convert network outputs into magnitudes response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: 3-D Tensor of synthesizer parameters, of shape [batch, time,
        n_filter_banks].

    Returns:
      controls: Dictionary of tensors of synthesizer controls.
    """
    # Scale the magnitudes.
    if self.scale_fn is not None:
      magnitudes = self.scale_fn(magnitudes)

    return  {'audio': audio, 'magnitudes': magnitudes}

  def get_signal(self, audio, magnitudes):
    """Filter audio with LTV-FIR filter.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: Magnitudes tensor of shape [batch, n_frames, n_filter_banks].
        Expects float32 that is strictly positive.

    Returns:
      signal: Filtered audio of shape [batch, n_samples, 1].
    """
    return core.frequency_filter(audio,
                                 magnitudes,
                                 window_size=self.window_size)

#------------------ Modulation -------------------------------------------------
class ModDelay(processors.Processor):
  """Modulated delay times used in chorus, flanger, and vibrato effects."""

  def __init__(self,
               center_ms=15.0,
               depth_ms=10.0,
               sample_rate=16000,
               gain_scale_fn=core.exp_sigmoid,
               phase_scale_fn=tf.nn.sigmoid,
               add_dry=True,
               name='mod_delay'):
    super().__init__(name=name)
    self.center_ms = center_ms
    self.depth_ms = depth_ms
    self.sample_rate = sample_rate
    self.gain_scale_fn = gain_scale_fn
    self.phase_scale_fn = phase_scale_fn
    self.add_dry = add_dry

  def get_controls(self, audio, gain, phase):
    """Convert network outputs into magnitudes response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Amplitude of modulated signal. Shape [batch_size, n_samples, 1].
      phase: Relative delay time. Shape [batch_size, n_samples, 1].

    Returns:
      controls: Dictionary of tensors of synthesizer controls.
    """
    if self.gain_scale_fn is not None:
      gain = self.gain_scale_fn(gain)

    if self.phase_scale_fn is not None:
      phase = self.phase_scale_fn(phase)

    return  {'audio': audio, 'gain': gain, 'phase': phase}

  def get_signal(self, audio, gain, phase):
    """Filter audio with LTV-FIR filter.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Amplitude of modulated signal. Shape [batch_size, n_samples, 1].
      phase: The normlaized instantaneous length of the delay, in the range of
        [center_ms - depth_ms, center_ms + depth_ms] from 0 to 1.0. Shape
        [batch_size, n_samples, 1].

    Returns:
      signal: Modulated audio of shape [batch, n_samples].
    """
    max_delay_ms = self.center_ms + self.depth_ms
    max_length_samples = int(self.sample_rate / 1000.0 * max_delay_ms)

    depth_phase = self.depth_ms / max_delay_ms
    center_phase = self.center_ms / max_delay_ms
    phase = phase * depth_phase + center_phase
    wet_audio = core.variable_length_delay(audio=audio,
                                           phase=phase,
                                           max_length=max_length_samples)
    # Remove channel dimension.
    if len(gain.shape) == 3:
      gain = gain[..., 0]

    wet_audio *= gain
    return (wet_audio + audio) if self.add_dry else wet_audio

<commit_msg>Replace super().build() with self.built=True for reverb children to avoid creating unused self._ir variable.<commit_after># Copyright 2020 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3
"""Library of effects functions."""

from ddsp import core
from ddsp import processors
from ddsp import synths
import gin
import tensorflow.compat.v2 as tf

tf_float32 = core.tf_float32

#------------------ Reverbs ----------------------------------------------------
@gin.register
class Reverb(processors.Processor):
  """Convolutional (FIR) reverb."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               add_dry=True,
               name='reverb'):
    """Takes neural network outputs directly as the impulse response.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response. Only used if
        trainable=True.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, trainable=trainable)
    self._reverb_length = reverb_length
    self._add_dry = add_dry

  def _mask_dry_ir(self, ir):
    """Set first impulse response to zero to mask the dry signal."""
    # Make IR 2-D [batch, ir_size].
    if len(ir.shape) == 1:
      ir = ir[tf.newaxis, :]  # Add a batch dimension
    if len(ir.shape) == 3:
      ir = ir[:, :, 0]  # Remove unnessary channel dimension.
    # Mask the dry signal.
    dry_mask = tf.zeros([int(ir.shape[0]), 1], tf.float32)
    return tf.concat([dry_mask, ir[:, 1:]], axis=1)

  def _match_dimensions(self, audio, ir):
    """Tile the impulse response variable to match the batch size."""
    # Add batch dimension.
    if len(ir.shape) == 1:
      ir = ir[tf.newaxis, :]
    # Match batch dimension.
    batch_size = int(audio.shape[0])
    return tf.tile(ir, [batch_size, 1])

  def build(self, unused_input_shape):
    """Initialize impulse response."""
    if self.trainable:
      initializer = tf.random_normal_initializer(mean=0, stddev=1e-6)
      self._ir = self.add_weight(
          name='ir',
          shape=[self._reverb_length],
          dtype=tf.float32,
          initializer=initializer)
    self.built = True

  def get_controls(self, audio, ir=None):
    """Convert decoder outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      ir: 3-D Tensor of shape [batch, ir_size, 1] or 2D Tensor of shape
        [batch, ir_size].

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and ir is not provided.
    """
    if self.trainable:
      ir = self._match_dimensions(audio, self._ir)
    else:
      if ir is None:
        raise ValueError('Must provide "ir" tensor if Reverb trainable=False.')

    return {'audio': audio, 'ir': ir}

  def get_signal(self, audio, ir):
    """Apply impulse response.

    Args:
      audio: Dry audio, 2-D Tensor of shape [batch, n_samples].
      ir: 3-D Tensor of shape [batch, ir_size, 1] or 2D Tensor of shape
        [batch, ir_size].

    Returns:
      tensor of shape [batch, n_samples]
    """
    audio, ir = tf_float32(audio), tf_float32(ir)
    ir = self._mask_dry_ir(ir)
    wet = core.fft_convolve(audio, ir, padding='same', delay_compensation=0)
    return (wet + audio) if self._add_dry else wet

@gin.register
class ExpDecayReverb(Reverb):
  """Parameterize impulse response as a simple exponential decay."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               scale_fn=core.exp_sigmoid,
               add_dry=True,
               name='exp_decay_reverb'):
    """Constructor.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response.
      scale_fn: Function by which to scale the network outputs.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, add_dry=add_dry, trainable=trainable)
    self._reverb_length = reverb_length
    self._scale_fn = scale_fn

  def _get_ir(self, gain, decay):
    """Simple exponential decay of white noise."""
    gain = self._scale_fn(gain)
    decay_exponent = 2.0 + tf.exp(decay)
    time = tf.linspace(0.0, 1.0, self._reverb_length)[tf.newaxis, :]
    noise = tf.random.uniform([1, self._reverb_length], minval=-1.0, maxval=1.0)
    ir = gain * tf.exp(-decay_exponent * time) * noise
    return ir

  def build(self, unused_input_shape):
    """Initialize impulse response."""
    if self.trainable:
      self._gain = self.add_weight(
          name='gain',
          shape=[1],
          dtype=tf.float32,
          initializer=tf.constant_initializer(2.0))
      self._decay = self.add_weight(
          name='decay',
          shape=[1],
          dtype=tf.float32,
          initializer=tf.constant_initializer(4.0))
    self.built = True

  def get_controls(self, audio, gain=None, decay=None):
    """Convert network outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Linear gain of impulse response. Scaled by self._scale_fn.
        2D Tensor of shape [batch, 1]. Not used if trainable=True.
      decay: Exponential decay coefficient. The final impulse response is
        exp(-(2 + exp(decay)) * time) where time goes from 0 to 1.0 over the
        reverb_length samples. 2D Tensor of shape [batch, 1]. Not used if
        trainable=True.

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and gain and decay are not provided.
    """
    if self.trainable:
      gain, decay = self._gain[tf.newaxis, :], self._decay[tf.newaxis, :]
    else:
      if gain is None or decay is None:
        raise ValueError('Must provide "gain" and "decay" tensors if '
                         'ExpDecayReverb trainable=False.')

    ir = self._get_ir(gain, decay)

    if self.trainable:
      ir = self._match_dimensions(audio, ir)

    return {'audio': audio, 'ir': ir}

@gin.register
class FilteredNoiseReverb(Reverb):
  """Parameterize impulse response with outputs of a filtered noise synth."""

  def __init__(self,
               trainable=False,
               reverb_length=48000,
               window_size=257,
               n_frames=1000,
               n_filter_banks=16,
               scale_fn=core.exp_sigmoid,
               initial_bias=-3.0,
               add_dry=True,
               name='filtered_noise_reverb'):
    """Constructor.

    Args:
      trainable: Learn the impulse_response as a single variable for the entire
        dataset.
      reverb_length: Length of the impulse response.
      window_size: Window size for filtered noise synthesizer.
      n_frames: Time resolution of magnitudes coefficients. Only used if
        trainable=True.
      n_filter_banks: Frequency resolution of magnitudes coefficients. Only used
        if trainable=True.
      scale_fn: Function by which to scale the magnitudes.
      initial_bias: Shift the filtered noise synth inputs by this amount
        (before scale_fn) to start generating noise in a resonable range when
        given magnitudes centered around 0.
      add_dry: Add dry signal to reverberated signal on output.
      name: Name of processor module.
    """
    super().__init__(name=name, add_dry=add_dry, trainable=trainable)
    self._n_frames = n_frames
    self._n_filter_banks = n_filter_banks
    self._synth = synths.FilteredNoise(n_samples=reverb_length,
                                       window_size=window_size,
                                       scale_fn=scale_fn,
                                       initial_bias=initial_bias)

  def build(self, unused_input_shape):
    """Initialize impulse response."""
    if self.trainable:
      initializer = tf.random_normal_initializer(mean=0, stddev=1e-2)
      self._magnitudes = self.add_weight(
          name='magnitudes',
          shape=[self._n_frames, self._n_filter_banks],
          dtype=tf.float32,
          initializer=initializer)
    self.built = True

  def get_controls(self, audio, magnitudes=None):
    """Convert network outputs into ir response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: Magnitudes tensor of shape [batch, n_frames, n_filter_banks].
        Expects float32 that is strictly positive. Not used if trainable=True.

    Returns:
      controls: Dictionary of effect controls.

    Raises:
      ValueError: If trainable=False and magnitudes are not provided.
    """
    if self.trainable:
      magnitudes = self._magnitudes[tf.newaxis, :]
    else:
      if magnitudes is None:
        raise ValueError('Must provide "magnitudes" tensor if '
                         'FilteredNoiseReverb trainable=False.')

    ir = self._synth(magnitudes)

    if self.trainable:
      ir = self._match_dimensions(audio, ir)

    return {'audio': audio, 'ir': ir}

#------------------ Filters ----------------------------------------------------
@gin.register
class FIRFilter(processors.Processor):
  """Linear time-varying finite impulse response (LTV-FIR) filter."""

  def __init__(self,
               window_size=257,
               scale_fn=core.exp_sigmoid,
               name='fir_filter'):
    super().__init__(name=name)
    self.window_size = window_size
    self.scale_fn = scale_fn

  def get_controls(self, audio, magnitudes):
    """Convert network outputs into magnitudes response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: 3-D Tensor of synthesizer parameters, of shape [batch, time,
        n_filter_banks].

    Returns:
      controls: Dictionary of tensors of synthesizer controls.
    """
    # Scale the magnitudes.
    if self.scale_fn is not None:
      magnitudes = self.scale_fn(magnitudes)

    return  {'audio': audio, 'magnitudes': magnitudes}

  def get_signal(self, audio, magnitudes):
    """Filter audio with LTV-FIR filter.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      magnitudes: Magnitudes tensor of shape [batch, n_frames, n_filter_banks].
        Expects float32 that is strictly positive.

    Returns:
      signal: Filtered audio of shape [batch, n_samples, 1].
    """
    return core.frequency_filter(audio,
                                 magnitudes,
                                 window_size=self.window_size)

#------------------ Modulation -------------------------------------------------
class ModDelay(processors.Processor):
  """Modulated delay times used in chorus, flanger, and vibrato effects."""

  def __init__(self,
               center_ms=15.0,
               depth_ms=10.0,
               sample_rate=16000,
               gain_scale_fn=core.exp_sigmoid,
               phase_scale_fn=tf.nn.sigmoid,
               add_dry=True,
               name='mod_delay'):
    super().__init__(name=name)
    self.center_ms = center_ms
    self.depth_ms = depth_ms
    self.sample_rate = sample_rate
    self.gain_scale_fn = gain_scale_fn
    self.phase_scale_fn = phase_scale_fn
    self.add_dry = add_dry

  def get_controls(self, audio, gain, phase):
    """Convert network outputs into magnitudes response.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Amplitude of modulated signal. Shape [batch_size, n_samples, 1].
      phase: Relative delay time. Shape [batch_size, n_samples, 1].

    Returns:
      controls: Dictionary of tensors of synthesizer controls.
    """
    if self.gain_scale_fn is not None:
      gain = self.gain_scale_fn(gain)

    if self.phase_scale_fn is not None:
      phase = self.phase_scale_fn(phase)

    return  {'audio': audio, 'gain': gain, 'phase': phase}

  def get_signal(self, audio, gain, phase):
    """Filter audio with LTV-FIR filter.

    Args:
      audio: Dry audio. 2-D Tensor of shape [batch, n_samples].
      gain: Amplitude of modulated signal. Shape [batch_size, n_samples, 1].
      phase: The normlaized instantaneous length of the delay, in the range of
        [center_ms - depth_ms, center_ms + depth_ms] from 0 to 1.0. Shape
        [batch_size, n_samples, 1].

    Returns:
      signal: Modulated audio of shape [batch, n_samples].
    """
    max_delay_ms = self.center_ms + self.depth_ms
    max_length_samples = int(self.sample_rate / 1000.0 * max_delay_ms)

    depth_phase = self.depth_ms / max_delay_ms
    center_phase = self.center_ms / max_delay_ms
    phase = phase * depth_phase + center_phase
    wet_audio = core.variable_length_delay(audio=audio,
                                           phase=phase,
                                           max_length=max_length_samples)
    # Remove channel dimension.
    if len(gain.shape) == 3:
      gain = gain[..., 0]

    wet_audio *= gain
    return (wet_audio + audio) if self.add_dry else wet_audio

<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import web
import yaml
import generate_kingdom_history

urls = (
  '/', 'index'
)

class index:

  def __init__(self):
    with open("history.yaml") as file:
      self.config = yaml.load(file)
    self.kingdom = generate_kingdom_history.Kingdom(5)

  def GET(self):
    return """
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Create a random kingdom history</title>
<meta name="description" content="Refresh to get a random kingdom history">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://reset5.googlecode.com/hg/reset.min.css">
<link href='https://fonts.googleapis.com/css?family=Cabin' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>

 %s

%s

""" % ( self.is_growing(), self.events() )

  def events(self):
    event_list = ''
    for event in self.kingdom.events:
      #print "%d %d" % (event._rank, event._suit)
      event_list += "
%s" % (event.desc)
      if event.tag:
        event_list += "

%s: %s

" % (event.tag, event.tag_desc)
      event_list += "
"
    return '
' + event_list + '
'

  def is_growing(self):
    if self.kingdom.growth > 1:
      return "A growing kingdom"
    elif self.kingdom.growth < -1:
      return "A kingdom in decline"
    else:
      return "A stable kingdom"

if __name__ == "__main__":
  app = web.application(urls, globals())
  app.run()

<commit_msg>added footer with copyright info<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import web
import yaml
import generate_kingdom_history

urls = (
  '/', 'index'
)

class index:

  def __init__(self):
    with open("history.yaml") as file:
      self.config = yaml.load(file)
    self.kingdom = generate_kingdom_history.Kingdom(5)

  def GET(self):
    return """
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Create a random kingdom history</title>
<meta name="description" content="Refresh to get a random kingdom history">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://reset5.googlecode.com/hg/reset.min.css">
<link href='https://fonts.googleapis.com/css?family=Cabin' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>

 %s

%s

All content copyright Johnn Four. Code by Justin McGuire.

""" % ( self.is_growing(), self.events() )

  def events(self):
    event_list = ''
    for event in self.kingdom.events:
      #print "%d %d" % (event._rank, event._suit)
      event_list += "
%s" % (event.desc)
      if event.tag:
        event_list += "

%s: %s

" % (event.tag, event.tag_desc)
      event_list += "
"
    return '
' + event_list + '
'

  def is_growing(self):
    if self.kingdom.growth > 1:
      return "A growing kingdom"
    elif self.kingdom.growth < -1:
      return "A kingdom in decline"
    else:
      return "A stable kingdom"

if __name__ == "__main__":
  app = web.application(urls, globals())
  app.run()

<|endoftext|>