Ejemplo n.º 1
0
def pixel():
    """
    Send a pixel color, and x and y coordinates to render the pixel.
    """
    try:
        x = int(flask.request.form.get('x'))
        y = int(flask.request.form.get('y'))
        color = flask.request.form.get('color')

        view.screen.tkapp.w.create_rectangle(
            x * config.constants.PIXEL_WIDTH,
            y * config.constants.PIXEL_HEIGHT,
            x * config.constants.PIXEL_WIDTH + config.constants.PIXEL_WIDTH,
            y * config.constants.PIXEL_HEIGHT + config.constants.PIXEL_HEIGHT,
            fill=color,
            width=0,
            outline="")

        parsed_color = webcolors.html5_parse_legacy_color(color)
        write_bmp(x, y, parsed_color.red, parsed_color.green,
                  parsed_color.blue)

        return construct_response()
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        import traceback
        log.error(traceback.format_exc())
        return construct_response(status="Failure",
                                  message="Line:" + exc_tb.tb_lineno + ", " +
                                  str(e))
Ejemplo n.º 2
0
 def test_parse_legacy_color_names(self):
     """
     Test the HTML5 legacy color parsing of SVG/CSS3 color names.
     """
     for name in webcolors.CSS3_NAMES_TO_HEX.keys():
         self.assertEqual(webcolors.name_to_rgb(name),
                          webcolors.html5_parse_legacy_color(name))
Ejemplo n.º 3
0
def say_hello(**payload):
    global my_id
    data = payload['data']

    #print(data)
    text = data.get('text', '')
    if not 'subtype' in data and ('<@' + my_id + '>' in text or data['channel'].startswith('D')):
        text_parts = text.split(' ')
        
        if len(text_parts) > 0:
            try:
                rgb = webcolors.html5_parse_legacy_color(text_parts[-1])
                print(str(rgb))
                #print(str(payload['timestamp']))
            
                conn = http.client.HTTPConnection("127.0.0.1:8080")
                conn.request("GET","/vars/col?set=" + str(int(webcolors.rgb_to_hex((rgb.blue, rgb.green, rgb.red))[1:],16)))
                r1 = conn.getresponse()
                conn.close()
            
                #payload['web_client'].chat_postMessage(
                #    channel=data['channel'],
                #    text="Set color to: " + webcolors.rgb_to_hex((rgb.red, rgb.green, rgb.blue)),
                #    thread_ts=data['ts']
                #)
                payload['web_client'].reactions_add(
                    channel=data['channel'],
                    name='thumbsup',
                    timestamp=data['ts']
                )
            except:
                print("Error: " + str(sys.exc_info()[0]))
Ejemplo n.º 4
0
    def __init__(self, definition, opacity=None):
        if not isinstance(definition, str):
            raise Exception("Unable to parse color %s" % definition)

        color_definition = definition.lower()
        self.opacity = float(1)

        if color_definition == "transparent":
            self.opacity = 0.0
            self.value = '#000000'
        elif color_definition.startswith("rgb("):
            m = RGB_PARSER.match(color_definition)
            color_rgb = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
            self.value = webcolors.rgb_to_hex(color_rgb)
        elif color_definition.startswith("rgba("):
            m = RGBA_PARSER.match(color_definition)
            color_rgb = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
            self.value = webcolors.rgb_to_hex(color_rgb)
            self.opacity = float(m.group(4))
        elif color_definition.startswith("#"):
            self.value = webcolors.normalize_hex(color_definition)
        else:
            self.value = webcolors.rgb_to_hex(
                webcolors.html5_parse_legacy_color(color_definition))

        if opacity is not None:
            self.opacity = opacity
Ejemplo n.º 5
0
 def test_parse_legacy_color_names(self):
     """
     Test the HTML5 legacy color parsing of SVG/CSS3 color names.
     """
     for name in webcolors.CSS3_NAMES_TO_HEX.keys():
         self.assertEqual(webcolors.name_to_rgb(name),
                          webcolors.html5_parse_legacy_color(name))
Ejemplo n.º 6
0
def color_html_to_weechat(color):
    # type: (str) -> str
    # yapf: disable
    weechat_basic_colors = {
        (0, 0, 0): "black",             # 0
        (128, 0, 0): "red",             # 1
        (0, 128, 0): "green",           # 2
        (128, 128, 0): "brown",         # 3
        (0, 0, 128): "blue",            # 4
        (128, 0, 128): "magenta",       # 5
        (0, 128, 128): "cyan",          # 6
        (192, 192, 192): "default",     # 7
        (128, 128, 128): "gray",        # 8
        (255, 0, 0): "lightred",        # 9
        (0, 255, 0): "lightgreen",      # 10
        (255, 255, 0): "yellow",        # 11
        (0, 0, 255): "lightblue",       # 12
        (255, 0, 255): "lightmagenta",  # 13
        (0, 255, 255): "lightcyan",     # 14
        (255, 255, 255): "white",       # 15
    }
    # yapf: enable

    try:
        rgb_color = webcolors.html5_parse_legacy_color(color)
    except ValueError:
        return ""

    if rgb_color in weechat_basic_colors:
        return weechat_basic_colors[rgb_color]

    return str(color_find_rgb(*rgb_color))
Ejemplo n.º 7
0
 def test_parse_legacy_color_hex(self):
     """
     Test the HTML5 legacy color parsing of three- and six-digit
     hexadecimal color values.
     """
     test_values = (u'#000', u'#000000', u'#fff', u'#ffffff', u'#000080')
     for value in test_values:
         self.assertEqual(webcolors.hex_to_rgb(value),
                          webcolors.html5_parse_legacy_color(value))
Ejemplo n.º 8
0
def change_group_color(bridge, group, color):
    hue_group = get_group_name(bridge, group)
    if hue_group.islight = 0:
        LOGGER.debug("This is the hue group: {}".format(hue_group[0]))
        color_rgb = webcolors.html5_parse_legacy_color(unicode(color))
        converterc = Converter(GamutC)
        color_xy = converterc.rgb_to_xy(*color_rgb)
        bridge.set_group(hue_group[0], 'xy', *color_xy)
        LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb))
        return hue_group[0]
Ejemplo n.º 9
0
def lighter(color, light=0.3):
	c = webcolors.html5_parse_legacy_color(color)
	
	vals = (c.red, c.green, c.blue)
	
	assert 0 < light <= 1, light
	
	vals = [int(255*light + v * (1 - light)) for v in vals]
	
	return webcolors.rgb_to_hex(webcolors.HTML5SimpleColor(*vals))
Ejemplo n.º 10
0
def dimmer(color, dim=0.3):
	c = webcolors.html5_parse_legacy_color(color)
	
	vals = (c.red, c.green, c.blue)
	
	assert 0 < dim <= 1, dim
	
	vals = [int(v * (1 - dim)) for v in vals]
	
	return webcolors.rgb_to_hex(webcolors.HTML5SimpleColor(*vals))
Ejemplo n.º 11
0
    def test_parse_legacy_color_hex(self):
        """
		Test the HTML5 legacy color parsing of three- and six-digit
		hexadecimal color values.

		"""
        test_values = ("#000", "#000000", "#fff", "#ffffff", "#000080")
        for value in test_values:
            parsed = webcolors.html5_parse_legacy_color(value)
            assert parsed == webcolors.hex_to_rgb(value)
Ejemplo n.º 12
0
def convert_color_to_rrggbb(color):
    """The color in "#RRGGBB" format.

    :return: the :attr:`color` in "#RRGGBB" format
    """
    if not color.startswith("#"):
        rgb = webcolors.html5_parse_legacy_color(color)
        hex_color = webcolors.html5_serialize_simple_color(rgb)
    else:
        hex_color = color
    return webcolors.normalize_hex(hex_color)
Ejemplo n.º 13
0
def convert_color_to_rrggbb(color):
    """The color in "#RRGGBB" format.

    :return: the :attr:`color` in "#RRGGBB" format
    """
    if not color.startswith("#"):
        rgb = webcolors.html5_parse_legacy_color(color)
        hex_color = webcolors.html5_serialize_simple_color(rgb)
    else:
        hex_color = color
    return webcolors.normalize_hex(hex_color)
Ejemplo n.º 14
0
    def change_name(*a):
        name = top.tk.globalgetvar('name')
        try:
            rgb = webcolors.html5_parse_legacy_color(name)
        except:
            return

        for name, val in zip(['red', 'green', 'blue'], rgb):
            top.tk.globalsetvar(name, val)

        change_rgb(None, False)
Ejemplo n.º 15
0
def make_colour(colour_string, opacity=1.0):
    if colour_string.startswith('#'):
        colour = webcolors.hex_to_rgb(colour_string)
    elif colour_string.startswith('rgb('):
        rgb = colour_string[4:-1].split(',')
        if '%' in colour_string:
            colour = webcolors.rgb_percent_to_rgb(rgb)
        else:
            colour = [int(c) for c in rgb]
    else:
        colour = webcolors.html5_parse_legacy_color(colour_string)
    return skia.Color(*tuple(colour), int(255*opacity))
Ejemplo n.º 16
0
 def test_parse_legacy_color_hex(self):
     """
     Test the HTML5 legacy color parsing of three- and six-digit
     hexadecimal color values.
     """
     test_values = (u'#000',
                    u'#000000',
                    u'#fff',
                    u'#ffffff',
                    u'#000080')
     for value in test_values:
         self.assertEqual(webcolors.hex_to_rgb(value),
                          webcolors.html5_parse_legacy_color(value))
Ejemplo n.º 17
0
def greyit(color, pull=0.5, base=0.1):
	c = webcolors.html5_parse_legacy_color(color)
	
	vals = (c.red, c.green, c.blue)
	
	if base is not None:
		vals = [max(v, base) for v in vals]
	
	avg = sum(vals) / 3
	
	assert 0 < pull <= 1, pull
	
	vals = [max(0, min(int(pull * avg + (1 - pull) * v), 255)) for v in vals]
	
	return webcolors.rgb_to_hex(webcolors.HTML5SimpleColor(*vals))
Ejemplo n.º 18
0
 def test_parse_legacy_color(self):
     """
     Test implementation of the HTML5 legacy color parsing
     algorithm.
     """
     # One of these is the famous "chucknorris" value. Another is a
     # CSS 2 system color. The final two are randomly-generated but
     # believable junk strings. Correct output values obtained
     # manually.
     test_pairs = ((u'chucknorris', (192, 0, 0)), (u'Window', (0, 13, 0)),
                   (u'RE|SXLuAse', (224, 0, 224)), (u'+=@FnnWL!Yb}5Dk',
                                                    (0, 0, 176)))
     for pair in test_pairs:
         self.assertEqual(pair[1],
                          webcolors.html5_parse_legacy_color(pair[0]))
Ejemplo n.º 19
0
 def test_parse_legacy_color(self):
     """
     Test implementation of the HTML5 legacy color parsing
     algorithm.
     """
     # One of these is the famous "chucknorris" value. Another is a
     # CSS 2 system color. The final two are randomly-generated but
     # believable junk strings. Correct output values obtained
     # manually.
     test_pairs = ((u'chucknorris', (192, 0, 0)),
                   (u'Window', (0, 13, 0)),
                   (u'RE|SXLuAse', (224, 0, 224)),
                   (u'+=@FnnWL!Yb}5Dk', (0, 0, 176)))
     for pair in test_pairs:
         self.assertEqual(pair[1],
                          webcolors.html5_parse_legacy_color(pair[0]))
Ejemplo n.º 20
0
    def test_parse_legacy_color(self):
        """
        Test implementation of the HTML5 legacy color parsing
        algorithm.

        """
        # One of these is the famous "chucknorris" value. Another is a
        # CSS 2 system color. The final two are randomly-generated but
        # believable junk strings. Correct output values obtained
        # manually.
        test_pairs = (
            (u'chucknorris', (192, 0, 0)),
            (u'Window', (0, 13, 0)),
            (u'RE|SXLuAse', (224, 0, 224)),
            (u'+=@FnnWL!Yb}5Dk', (0, 0, 176)),
            (u'A' * 129, (170, 170, 170))
        )
        for raw, parsed in test_pairs:
            result = webcolors.html5_parse_legacy_color(raw)
            assert isinstance(result, webcolors.HTML5SimpleColor)
            assert parsed == result
Ejemplo n.º 21
0
    def test_parse_legacy_color(self):
        """
		Test implementation of the HTML5 legacy color parsing
		algorithm.

		"""
        # One of these is the famous "chucknorris" value. Another is a
        # CSS 2 system color. The final two are randomly-generated but
        # believable junk strings. Correct output values obtained
        # manually.
        test_pairs = (
            ("chucknorris", (192, 0, 0)),
            ("Window", (0, 13, 0)),
            ("RE|SXLuAse", (224, 0, 224)),
            ("+=@FnnWL!Yb}5Dk", (0, 0, 176)),
            ('A' * 129, (170, 170, 170)),
        )
        for raw, parsed in test_pairs:
            result = webcolors.html5_parse_legacy_color(raw)
            assert isinstance(result, webcolors.HTML5SimpleColor)
            assert parsed == result
Ejemplo n.º 22
0
 def __init__(self, *args, **kwargs):
     if args:
         v = args[0]
         try:
             a = args[1]
         except IndexError:
             a = 1.0
         ta = type(v)
         if ta in (tuple, list):
             super().__init__(*Color(*v))
         if v:
             lenargs = len(args)
             if ta is str:
                 r = webcolors.html5_parse_legacy_color(v)
                 super().__init__(glm.vec3(*r) / 255.0, a)
             elif ta in (float, int):
                 super().__init__(glm.vec3(v), a)
             elif ta == glm.vec3:
                 super().__init__(v, a)
             elif ta == glm.vec4:
                 super().__init__(v)
             else:
                 if lenargs == 4:
                     super().__init__(*args)
                 elif lenargs == 3:
                     super().__init__(glm.vec3(v), a)
                     return glm.vec4(glm.vec3(*args), a)
                 elif lenargs == 1:
                     super().__init__(glm.vec3(v), a)
                 elif lenargs == 2:
                     super().__init__(glm.vec3(v), args[1])
                 else:
                     raise ValueError("invalid color")
         else:
             super().__init__(0, 0, 0, 1)
     else:
         super().__init__(0, 0, 0, 1)
Ejemplo n.º 23
0
def change_color(name):
  color = request.args.get('color') or request.args.get('hsv')

  global timer, t_kill, current_color
  if color:
    try:
        # hsv color value e.g. "100,50,100"
        current_color = hsv_to_rgb([float(x) for x in color.split(',')])
    except ValueError:
        # color names e.g. "yellow"
        current_color = webcolors.html5_parse_legacy_color(color)
  else:
    color = request.args.get('rgb')
    # rbg color value e.g. "ff00dd"
    current_color = webcolors.html5_parse_simple_color(u"#" + color)

  stop_timer()

  if timer is None:
    t_kill = threading.Event()
    timer = RepeatingTimer(t_kill, set_color)
    timer.start()

  return color
def change_color(name):
    color = request.args.get('color') or request.args.get('hsv')

    global timer, t_kill, current_color
    if color:
        try:
            # hsv color value e.g. "100,50,100"
            current_color = hsv_to_rgb([float(x) for x in color.split(',')])
        except ValueError:
            # color names e.g. "yellow"
            current_color = webcolors.html5_parse_legacy_color(color)
    else:
        color = request.args.get('rgb')
        # rbg color value e.g. "ff00dd"
        current_color = webcolors.html5_parse_simple_color(u"#" + color)

    stop_timer()

    if timer is None:
        t_kill = threading.Event()
        timer = RepeatingTimer(t_kill, set_color)
        timer.start()

    return color
Ejemplo n.º 25
0
def process_color(raw):
	full = webcolors.HTML5SimpleColor(*raw) if isinstance(raw, (list,tuple)) \
		else webcolors.html5_parse_legacy_color(raw)
	return webcolors.rgb_to_hex(full)
Ejemplo n.º 26
0
    def get_color(self, sp: Union[Specie, Element], site: Optional[Site] = None) -> str:
        """
        Get a color to render a specific species. Optionally, you can provide
        a site for context, since ...

        Args:
            sp: Specie or Element
            site: Site

        Returns: Color

        """

        # allow manual override by user
        if site and "display_color" in site.properties:
            color = site.properties["display_color"]
            # TODO: next two lines due to change in API, will be removed
            if isinstance(color, list) and isinstance(color[0], str):
                color = color[0]
            if isinstance(color, list):
                return html5_serialize_simple_color(color)
            else:
                return html5_serialize_simple_color(html5_parse_legacy_color(color))

        if self.color_scheme in ("VESTA", "Jmol", "accessible"):
            el = sp.as_dict()["element"]
            color = self.el_colors[self.color_scheme].get(
                el, self.el_colors["Extras"].get(el, self.default_color)
            )

        elif self.color_scheme in self.site_prop_types.get("scalar", []):

            if not site:
                raise ValueError(
                    "Requires a site for context to get the "
                    "appropriate site property."
                )

            prop = site.properties[self.color_scheme]

            if prop:

                cmap = get_cmap(self.cmap)

                # normalize in [0, 1] range, as expected by cmap
                prop_min = self.cmap_range[0]
                prop_max = self.cmap_range[1]
                prop_normed = (prop - prop_min) / (prop_max - prop_min)

                color = [int(c * 255) for c in cmap(prop_normed)[0:3]]

            else:

                # fallback if site prop is None
                color = self.default_color

        elif self.color_scheme in self.site_prop_types.get("categorical", []):

            if not site:
                raise ValueError(
                    "Requires a site for context to get the "
                    "appropriate site property."
                )

            prop = site.properties[self.color_scheme]

            color = self.categorical_colors[self.color_scheme].get(
                prop, self.default_color
            )

        else:

            raise ValueError(
                f"Unknown color for {sp} and color scheme {self.color_scheme}."
            )

        return html5_serialize_simple_color(color)
Ejemplo n.º 27
0
def hex_to_rgb(raw):
	if isinstance(raw, str):
		full = webcolors.html5_parse_legacy_color(raw)
		return [full.red, full.green, full.blue]
	return raw
Ejemplo n.º 28
0
def parse_color(input):
    if input == 'off':
        return [0, 0, 0]
    if input in ('rnd', 'random'):
        return random_color()
    return webcolors.html5_parse_legacy_color(input)
Ejemplo n.º 29
0
def color_to_linear(color):
    return hex_to_linear(sum(html5_parse_legacy_color(color)) / 3)
Ejemplo n.º 30
0
    def post(self, request, *args, **kwargs):

        files = request.FILES.getlist("filee")
        file_list = []
        for f in files:
            css_file_name = re.findall('.*\.css$', f.name)
            jpg_file_name = re.findall('.*\.jpg$|.*\.JPG$', f.name)

            if len(css_file_name) == 0 and len(jpg_file_name) == 0:
                return
            else:
                instance = File(name_field=f.name, file_field=f)
                instance.save()

                if len(css_file_name) > 0:
                    with open(
                            '/Users/hande/Desktop/Project/themaMaker/uploads/'
                            + css_file_name[0],
                            newline='') as myFile:
                        colors = re.findall(r'color:\s(#[a-zA-Z0-9]*|[a-z]*)',
                                            myFile.read(), re.DOTALL)

                    colors = [
                        elem for elem in colors if (elem != "transparent")
                    ]

                    for x in range(0, len(colors)):
                        if (colors[x][0] != '#'):
                            temp = webcolors.html5_parse_legacy_color(
                                colors[x])
                            temp_r = str(hex(temp.red))[2:] if (len(
                                str(hex(temp.red))) == 4) else (
                                    '0' + str(hex(temp.red))[2])
                            temp_g = str(hex(temp.green))[2:] if (len(
                                str(hex(temp.green))) == 4) else (
                                    '0' + str(hex(temp.green))[2])
                            temp_b = str(hex(temp.blue))[2:] if (len(
                                str(hex(temp.blue))) == 4) else (
                                    '0' + str(hex(temp.blue))[2])
                            colors[x] = '#' + temp_r + temp_g + temp_b

                        elif (len(colors[x]) < 7):
                            temp_r = colors[x][1]
                            temp_g = colors[x][2]
                            temp_b = colors[x][3]
                            colors[
                                x] = '#' + temp_r + temp_r + temp_g + temp_g + temp_b + temp_b

                else:
                    cols = self.dominantColors(jpg_file_name[0], 5)
                    colors = [webcolors.rgb_to_hex(tuple(t)) for t in cols]
                    #print(colors)

                color_no_list = list(range(len(colors)))
                print(instance.file_field.name)
                file_list.append({
                    "name": f.name,
                    "uploaded_fname": instance.file_field.path,
                    "color_list": colors,
                    "color_no_list": color_no_list
                })

        return render(request, 'more.html', {"files": file_list})
Ejemplo n.º 31
0
def rgb_to_hex(raw):
	full = webcolors.html5_parse_legacy_color(raw)
	return webcolors.rgb_to_hex(full)
Ejemplo n.º 32
0
        bridge.set_light(all_lights, 'on', False)
        LOGGER.debug("Turning off all lights")

def change_group_color(bridge, group, color):
    hue_group = get_group_name(bridge, group)
    if hue_group.islight = 0:
        LOGGER.debug("This is the hue group: {}".format(hue_group[0]))
        color_rgb = webcolors.html5_parse_legacy_color(unicode(color))
        converterc = Converter(GamutC)
        color_xy = converterc.rgb_to_xy(*color_rgb)
        bridge.set_group(hue_group[0], 'xy', *color_xy)
        LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb))
        return hue_group[0]
    else:
        LOGGER.debug("This is the light: {}".format(hue_group[0]))
        color_rgb = webcolors.html5_parse_legacy_color(unicode(color))
        converterc = Converter(GamutC)
        color_xy = converterc.rgb_to_xy(*color_rgb)
        bridge.set_light(hue_group[0], 'xy', *color_xy)
        LOGGER.debug("Setting group {} to color {}".format(hue_group[0], *color_rgb))
        return hue_group[0]


# The logic of each skill is contained within its own class, which inherits
# base methods from the MycroftSkill class with the syntax you can see below:
# "class ____Skill(MycroftSkill)"
class GeekHueSkill(MycroftSkill):
    def __init__(self):
        super(GeekHueSkill, self).__init__(name='GeekHueSkill')
        self.ip = self.config.get('bridge_ip')
        self.bridge = Bridge(self.ip)