<commit_before># ===============================================================================
# Copyright 2011 <NAME>
#
# 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.
#===============================================================================

#============= enthought library imports =======================
from traits.api import Instance, String, Property, Button, \
    Bool, Event, on_trait_change, Str, Int
from apptools.preferences.preference_binding import bind_preference

#============= standard library imports ========================
import time
from threading import Thread, Timer

import os
#============= local library imports  ==========================
from pychron.core.helpers.filetools import unique_path, unique_path2
from pychron.paths import paths
from pychron.image.video import Video
from pychron.canvas.canvas2D.camera import Camera
from stage_manager import StageManager
from pychron.core.ui.stage_component_editor import VideoComponentEditor

try:
    from pychron.canvas.canvas2D.video_laser_tray_canvas import VideoLaserTrayCanvas
except ImportError:
    from pychron.canvas.canvas2D.laser_tray_canvas import LaserTrayCanvas as VideoLaserTrayCanvas


class VideoStageManager(StageManager):
    """
    """
    video = Instance(Video)
    canvas_editor_klass = VideoComponentEditor

    camera_zoom_coefficients = Property(String(enter_set=True, auto_set=False),
                                        depends_on='_camera_zoom_coefficients')
    _camera_zoom_coefficients = String

    use_auto_center_interpolation = Bool(False)

    autocenter_button = Button('AutoCenter')
    configure_autocenter_button = Button('Configure')

    autocenter_manager = Instance('pychron.mv.autocenter_manager.AutoCenterManager')
    autofocus_manager = Instance('pychron.mv.focus.autofocus_manager.AutoFocusManager')
    snapshot_button = Button('Snapshot')
    auto_save_snapshot = Bool(True)

    record = Event
    record_label = Property(depends_on='is_recording')
    is_recording = Bool

    use_db = False

    use_video_archiver = Bool(True)
    video_archiver = Instance('pychron.core.helpers.archiver.Archiver')
    video_identifier = Str
    #     video_identifier = Enum(1, 2)
    use_video_server = Bool(False)
    video_server_port = Int
    video_server_quality = Int
    video_server = Instance('pychron.image.video_server.VideoServer')

    use_media_server = Bool(False)
    auto_upload = Bool(False)

    camera = Instance(Camera)

    render_with_markup = Bool(False)

    _auto_correcting = False
    stop_timer = Event

    def bind_preferences(self, pref_id):
        self.debug('binding preferences')
        super(VideoStageManager, self).bind_preferences(pref_id)
        if self.autocenter_manager:
            bind_preference(self.autocenter_manager, 'use_autocenter', '{}.use_autocenter'.format(pref_id))

        bind_preference(self, 'render_with_markup', '{}.render_with_markup'.format(pref_id))
        bind_preference(self, 'auto_upload', 'pychron.media_server.auto_upload')
        bind_preference(self, 'use_media_server', 'pychron.media_server.use_media_server')
        #        bind_preference(self.pattern_manager,
        #                        'record_patterning',
        #                         '{}.record_patterning'.format(pref_id))
        #
        #        bind_preference(self.pattern_manager,
        #                         'show_patterning',
        #                         '{}.show_patterning'.format(pref_id))

        bind_preference(self, 'use_video_archiver',
                        '{}.use_video_archiver'.format(pref_id))

        bind_preference(self, 'video_identifier',
                        '{}.video_identifier'.format(pref_id))

        bind_preference(self, 'use_video_server',
                        '{}.use_video_server'.format(pref_id))

        if self.use_video_server:
            bind_preference(self.video_server, 'port',
                            '{}.video_server_port'.format(pref_id))
            bind_preference(self.video_server, 'quality',
                            '{}.video_server_quality'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_months',
                        '{}.video_archive_months'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_days',
                        '{}.video_archive_days'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_hours',
                        '{}.video_archive_hours'.format(pref_id))
        bind_preference(self.video_archiver, 'root',
                        '{}.video_directory'.format(pref_id))

        bind_preference(self.video, 'output_mode', '{}.video_output_mode'.format(pref_id))
        bind_preference(self.video, 'ffmpeg_path', '{}.ffmpeg_path'.format(pref_id))

    def start_recording(self, new_thread=True, **kw):
        """
        """
        if new_thread:
            t = Thread(target=self._start_recording, kwargs=kw)
            t.start()
        else:
            self._start_recording(**kw)
        self.is_recording = True

    def stop_recording(self, user='remote', delay=None):
        """
        """

        def close():
            self.is_recording = False
            self.info('stop video recording')

            if self.video.stop_recording(wait=True):
                self._upload(self.video.output_path)

        if self.video._recording:
            if delay:
                t = Timer(delay, close)
                t.start()
            else:
                close()

    def initialize_video(self):
        if self.video:
            self.video.open(
                identifier=self.video_identifier)

    def initialize_stage(self):
        super(VideoStageManager, self).initialize_stage()
        self.initialize_video()

        s = self.stage_controller
        if s.axes:
            xa = s.axes['x'].drive_ratio
            ya = s.axes['y'].drive_ratio

            self._drive_xratio = xa
            self._drive_yratio = ya

        self._update_zoom(0)

    def autocenter(self, *args, **kw):
        return self._autocenter(*args, **kw)

    def snapshot(self, path=None, name=None, auto=False, inform=True, return_blob=False):
        """
            path: abs path to use
            name: base name to use if auto saving in default dir
            auto: force auto save

            returns:
                    path: local abs path
                    upath: remote abs path
        """

        if path is None:
            if self.auto_save_snapshot or auto:

                if name is None:
                    name = 'snapshot'
                path, _cnt = unique_path2(root=paths.snapshot_dir, base=name,
                                         extension='.jpg')
            elif name is not None:
                if not os.path.isdir(os.path.dirname(name)):
                    path,_ = unique_path2(root=paths.snapshot_dir, base=name, extension='.jpg')
                else:
                    path = name

            else:
                path = self.save_file_dialog()

        if path:
            self.info('saving snapshot {}'.format(path))
            # play camera shutter sound
            # play_sound('shutter')

            self._render_snapshot(path)
            upath = self._upload(path)
            if upath is None:
                upath = ''

            if inform:
                self.information_dialog('Snapshot save to {}. Uploaded to'.format(path, upath))

            return path, upath
            #if return_blob:
            #    with open(path, 'rb') as fp:
            #        return path, upath, 'abc' #fp.read()
            #else:
            #    return path, upath

    def kill(self):
        """
        """

        super(VideoStageManager, self).kill()
        if self.camera:
            self.camera.save_calibration()

        self.stop_timer = True<commit_msg>fixed snapshot<commit_after># ===============================================================================
# Copyright 2011 <NAME>
#
# 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.
#===============================================================================

#============= enthought library imports =======================
from traits.api import Instance, String, Property, Button, \
    Bool, Event, on_trait_change, Str, Int
from apptools.preferences.preference_binding import bind_preference

#============= standard library imports ========================
import time
from threading import Thread, Timer

import os
#============= local library imports  ==========================
from pychron.core.helpers.filetools import unique_path, unique_path2
from pychron.paths import paths
from pychron.image.video import Video
from pychron.canvas.canvas2D.camera import Camera
from stage_manager import StageManager
from pychron.core.ui.stage_component_editor import VideoComponentEditor

try:
    from pychron.canvas.canvas2D.video_laser_tray_canvas import VideoLaserTrayCanvas
except ImportError:
    from pychron.canvas.canvas2D.laser_tray_canvas import LaserTrayCanvas as VideoLaserTrayCanvas


class VideoStageManager(StageManager):
    """
    """
    video = Instance(Video)
    canvas_editor_klass = VideoComponentEditor

    camera_zoom_coefficients = Property(String(enter_set=True, auto_set=False),
                                        depends_on='_camera_zoom_coefficients')
    _camera_zoom_coefficients = String

    use_auto_center_interpolation = Bool(False)

    autocenter_button = Button('AutoCenter')
    configure_autocenter_button = Button('Configure')

    autocenter_manager = Instance('pychron.mv.autocenter_manager.AutoCenterManager')
    autofocus_manager = Instance('pychron.mv.focus.autofocus_manager.AutoFocusManager')
    snapshot_button = Button('Snapshot')
    auto_save_snapshot = Bool(True)

    record = Event
    record_label = Property(depends_on='is_recording')
    is_recording = Bool

    use_db = False

    use_video_archiver = Bool(True)
    video_archiver = Instance('pychron.core.helpers.archiver.Archiver')
    video_identifier = Str
    #     video_identifier = Enum(1, 2)
    use_video_server = Bool(False)
    video_server_port = Int
    video_server_quality = Int
    video_server = Instance('pychron.image.video_server.VideoServer')

    use_media_server = Bool(False)
    auto_upload = Bool(False)

    camera = Instance(Camera)

    render_with_markup = Bool(False)

    _auto_correcting = False
    stop_timer = Event

    def bind_preferences(self, pref_id):
        self.debug('binding preferences')
        super(VideoStageManager, self).bind_preferences(pref_id)
        if self.autocenter_manager:
            bind_preference(self.autocenter_manager, 'use_autocenter', '{}.use_autocenter'.format(pref_id))

        bind_preference(self, 'render_with_markup', '{}.render_with_markup'.format(pref_id))
        bind_preference(self, 'auto_upload', 'pychron.media_server.auto_upload')
        bind_preference(self, 'use_media_server', 'pychron.media_server.use_media_server')
        #        bind_preference(self.pattern_manager,
        #                        'record_patterning',
        #                         '{}.record_patterning'.format(pref_id))
        #
        #        bind_preference(self.pattern_manager,
        #                         'show_patterning',
        #                         '{}.show_patterning'.format(pref_id))

        bind_preference(self, 'use_video_archiver',
                        '{}.use_video_archiver'.format(pref_id))

        bind_preference(self, 'video_identifier',
                        '{}.video_identifier'.format(pref_id))

        bind_preference(self, 'use_video_server',
                        '{}.use_video_server'.format(pref_id))

        if self.use_video_server:
            bind_preference(self.video_server, 'port',
                            '{}.video_server_port'.format(pref_id))
            bind_preference(self.video_server, 'quality',
                            '{}.video_server_quality'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_months',
                        '{}.video_archive_months'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_days',
                        '{}.video_archive_days'.format(pref_id))
        bind_preference(self.video_archiver, 'archive_hours',
                        '{}.video_archive_hours'.format(pref_id))
        bind_preference(self.video_archiver, 'root',
                        '{}.video_directory'.format(pref_id))

        bind_preference(self.video, 'output_mode', '{}.video_output_mode'.format(pref_id))
        bind_preference(self.video, 'ffmpeg_path', '{}.ffmpeg_path'.format(pref_id))

    def start_recording(self, new_thread=True, **kw):
        """
        """
        if new_thread:
            t = Thread(target=self._start_recording, kwargs=kw)
            t.start()
        else:
            self._start_recording(**kw)
        self.is_recording = True

    def stop_recording(self, user='remote', delay=None):
        """
        """

        def close():
            self.is_recording = False
            self.info('stop video recording')

            if self.video.stop_recording(wait=True):
                self._upload(self.video.output_path)

        if self.video._recording:
            if delay:
                t = Timer(delay, close)
                t.start()
            else:
                close()

    def initialize_video(self):
        if self.video:
            self.video.open(
                identifier=self.video_identifier)

    def initialize_stage(self):
        super(VideoStageManager, self).initialize_stage()
        self.initialize_video()

        s = self.stage_controller
        if s.axes:
            xa = s.axes['x'].drive_ratio
            ya = s.axes['y'].drive_ratio

            self._drive_xratio = xa
            self._drive_yratio = ya

        self._update_zoom(0)

    def autocenter(self, *args, **kw):
        return self._autocenter(*args, **kw)

    def snapshot(self, path=None, name=None, auto=False, inform=True, return_blob=False):
        """
            path: abs path to use
            name: base name to use if auto saving in default dir
            auto: force auto save

            returns:
                    path: local abs path
                    upath: remote abs path
        """

        if path is None:
            if self.auto_save_snapshot or auto:

                if name is None:
                    name = 'snapshot'
                path, _cnt = unique_path2(root=paths.snapshot_dir, base=name,
                                         extension='.jpg')
            elif name is not None:
                if not os.path.isdir(os.path.dirname(name)):
                    path,_ = unique_path2(root=paths.snapshot_dir, base=name, extension='.jpg')
                else:
                    path = name

            else:
                path = self.save_file_dialog()

        if path:
            self.info('saving snapshot {}'.format(path))
            # play camera shutter sound
            # play_sound('shutter')

            self._render_snapshot(path)
            upath = self._upload(path)
            if upath is None:
                upath = ''

            if inform:
                self.information_dialog('Snapshot save to {}. Uploaded to'.format(path, upath))

            #return path, upath
            if return_blob:
                with open(path, 'rb') as fp:
                    return path, upath, fp.read()
            else:
                return path, upath

    def kill(self):
        """
        """

        super(VideoStageManager, self).kill()
        if self.camera:
            self.camera.save_calibration()

        self.stop_timer = True
{'fraction_non_alphanumeric': 0.12395758875387182, 'fraction_numerical': 0.002025256135334763, 'mean_word_length': 2.376030565051277, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6715153', 'n_tokens_mistral': 4728, 'n_tokens_neox': 4550, 'n_words': 949}