Source

color-stream-viz / src / normalize_colors.py

Full commit
# -*- coding: utf-8 -*-
#
#  normalize_colors.py
#  src
#

"""
Convert colors into a reference set (e.g. X11 or Pantone).
"""

import colors
import sys
import multiprocessing

SENTINEL = 'XXX'

class Referencer(multiprocessing.Process):
    def __init__(self, colorset, q, l, ostream):
        self.ref = colors.KDReferencePalette.from_file(colorset)
        self.q = q
        self.l = l
        self.ostream = ostream
        super(Referencer, self).__init__()

    def run(self):
        ref = self.ref
        while True:
            n = self.q.get()
            if n == SENTINEL:
                break

            t, designid, cols, bgcolor = n
            ref_colors = []
            for c in cols.split(','):
                r = ref[c]
                if r not in ref_colors:
                    ref_colors.append(r)

            ref_bg = ref[bgcolor] if bgcolor else ''

            self.l.acquire()
            print >> self.ostream, '\t'.join([
                    t,
                    designid,
                    ','.join(ref_colors),
                    ref_bg,
                ])
            self.ostream.flush()
            #sys.stderr.write('.'); sys.stderr.flush()
            self.l.release()

def main_mt(colorset):
    queue = multiprocessing.Queue(100)
    lock = multiprocessing.Lock()
    ostream = sys.stdout
    n = 8

    pool = [Referencer(colorset, queue, lock, ostream) for i in xrange(n)]
    for p in pool:
        p.start()

    for line in sys.stdin:
        t, designid, cols, bgcolor = line.rstrip('\n').split('\t')
        queue.put((t, designid, cols, bgcolor))

    for i in xrange(n):
        queue.put(SENTINEL)

    for p in pool:
        p.join()

def main(colorset):
    ref = colors.KDReferencePalette.from_file(colorset)
    for line in sys.stdin:
        t, designid, cols, bgcolor = line.rstrip('\n').split('\t')
        ref_colors = []
        for c in cols.split(','):
            r = ref[c]
            if r not in ref_colors:
                ref_colors.append(r)

        ref_bg = ref[bgcolor] if bgcolor else ''

        print '\t'.join([
                t,
                designid,
                ','.join(ref_colors),
                ref_bg,
            ])
        sys.stderr.write('.'); sys.stderr.flush()

if __name__ == '__main__':
    main_mt(*sys.argv[1:])