<commit_before>"""
Python module defining a class for creating movies of matplotlib figures.

This code and information is provided 'as is' without warranty of any kind,
either express or implied, including, but not limited to, the implied
warranties of non-infringement, merchantability or fitness for a particular
purpose.
"""

from functools import partial
import shutil
import subprocess
import tempfile

import matplotlib as mpl
import matplotlib.pyplot as plt
from six.moves import range



def invert_color(color):
    """ Returns the inverted value of a matplotlib color """
    # get the color value
    c = invert_color.cc.to_rgba(color)
    # keep alpha value intact!
    return (1-c[0], 1-c[1], 1-c[2], c[3])

# initialize the color converted and keep it as a static variable
invert_color.cc = mpl.colors.ColorConverter()



def invert_colors(fig):
    """ Changes the colors of a figure to their inverted values """

    # keep track of the object that have been changed
    visited = set()

    def get_filter(name):
        """ construct a specific filter for `findobj` """
        return lambda x: (hasattr(x, 'set_%s' % name) and
                          hasattr(x, 'get_%s' % name))

    for o in fig.findobj(get_filter('facecolor')):
        if o not in visited:
            o.set_facecolor(invert_color(o.get_facecolor()))
            if hasattr(o, 'set_edgecolor') and hasattr(o, 'get_edgecolor'):
                o.set_edgecolor(invert_color(o.get_edgecolor()))
            visited.add(o)

    for o in fig.findobj(get_filter('color')):
        if o not in visited:
            o.set_color(invert_color(o.get_color()))
            visited.add(o)



class Movie(object):
    """ Class for creating movies from matplotlib figures using ffmpeg """

    def __init__(self, width=None, filename=None, inverted=False, verbose=True,
                 framerate=None):
        self.width = width          # pixel width of the movie
        self.filename = filename    # filename used to save the movie
        self.inverted = inverted    # colors inverted?
        self.verbose = verbose      # verbose encoding information?
        self.framerate = framerate  # framerate of the movie

        # internal variables
        self.recording = False
        self.tempdir = None
        self.frame = 0
        self._start()


    def __del__(self):
        self._end()


    def __enter__(self):
        return self


    def __exit__(self, exc_type, exc_value, exc_tb):
        if self.filename is not None:
            self.save(self.filename)
        self._end()
        return False


    def _start(self):
        """ initializes the video recording """
        # create temporary directory for the image files of the movie
        self.tempdir = tempfile.mkdtemp(prefix='movie_')
        self.frame = 0
        self.recording = True


    def _end(self):
        """ clear up temporary things if necessary """
        if self.recording:
            shutil.rmtree(self.tempdir)
            self.recording = False


    def clear(self):
        """ delete current status and start from scratch """
        self._end()
        self._start()


    def _add_file(self, save_function):
        """
        Adds a file to the current movie
        """
        if not self.recording:
            raise ValueError('Movie is not initialized.')

        save_function("%s/frame_%09d.png" % (self.tempdir, self.frame))
        self.frame += 1


    def add_image(self, image):
        """
        Adds the data of a PIL image as a frame to the current movie.<commit_msg>Expose tempdir for making movies to redirect image storage<commit_after>"""
Python module defining a class for creating movies of matplotlib figures.

This code and information is provided 'as is' without warranty of any kind,
either express or implied, including, but not limited to, the implied
warranties of non-infringement, merchantability or fitness for a particular
purpose.
"""

from functools import partial
import shutil
import subprocess
import tempfile

import matplotlib as mpl
import matplotlib.pyplot as plt
from six.moves import range



def invert_color(color):
    """ Returns the inverted value of a matplotlib color """
    # get the color value
    c = invert_color.cc.to_rgba(color)
    # keep alpha value intact!
    return (1-c[0], 1-c[1], 1-c[2], c[3])

# initialize the color converted and keep it as a static variable
invert_color.cc = mpl.colors.ColorConverter()



def invert_colors(fig):
    """ Changes the colors of a figure to their inverted values """

    # keep track of the object that have been changed
    visited = set()

    def get_filter(name):
        """ construct a specific filter for `findobj` """
        return lambda x: (hasattr(x, 'set_%s' % name) and
                          hasattr(x, 'get_%s' % name))

    for o in fig.findobj(get_filter('facecolor')):
        if o not in visited:
            o.set_facecolor(invert_color(o.get_facecolor()))
            if hasattr(o, 'set_edgecolor') and hasattr(o, 'get_edgecolor'):
                o.set_edgecolor(invert_color(o.get_edgecolor()))
            visited.add(o)

    for o in fig.findobj(get_filter('color')):
        if o not in visited:
            o.set_color(invert_color(o.get_color()))
            visited.add(o)



class Movie(object):
    """ Class for creating movies from matplotlib figures using ffmpeg """

    def __init__(self, width=None, filename=None, inverted=False, verbose=True,
                 framerate=None, tempdir=None):
        self.width = width          # pixel width of the movie
        self.filename = filename    # filename used to save the movie
        self.inverted = inverted    # colors inverted?
        self.verbose = verbose      # verbose encoding information?
        self.framerate = framerate  # framerate of the movie

        # internal variables
        self.recording = False
        self.tempdir = tempdir
        self.frame = 0
        self._start()


    def __del__(self):
        self._end()


    def __enter__(self):
        return self


    def __exit__(self, exc_type, exc_value, exc_tb):
        if self.filename is not None:
            self.save(self.filename)
        self._end()
        return False


    def _start(self):
        """ initializes the video recording """
        # create temporary directory for the image files of the movie
        if self.tempdir is None:
            self.tempdir = tempfile.mkdtemp(prefix='movie_')
        self.frame = 0
        self.recording = True


    def _end(self):
        """ clear up temporary things if necessary """
        if self.recording:
            shutil.rmtree(self.tempdir)
            self.recording = False


    def clear(self):
        """ delete current status and start from scratch """
        self._end()
        self._start()


    def _add_file(self, save_function):
        """
        Adds a file to the current movie
        """
        if not self.recording:
            raise ValueError('Movie is not initialized.')

        save_function("%s/frame_%09d.png" % (self.tempdir, self.frame))
        self.frame += 1


    def add_image(self, image):
        """
        Adds the data of a PIL image as a frame to the current movie.
{'fraction_non_alphanumeric': 0.091624120325652, 'fraction_numerical': 0.0033117151924934455, 'mean_word_length': 2.420481359131666, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5291754', 'n_tokens_mistral': 2116, 'n_tokens_neox': 2015, 'n_words': 692}