<commit_before>#!/usr/bin/env python2
"""blockify

Usage:
    blockify [-l <path>] [-v...] [-q] [-h]

Options:
    -l, --log=<path>  Enables logging to the logfile/-path specified.
    -q, --quiet       Don't print anything to stdout.
    -v                Verbosity of the logging module, up to -vvv.
    -h, --help        Show this help text.
    --version         Show current version of blockify.
"""
import logging
import os
import re
import signal
import subprocess
import sys

import gtk
import pygtk
import wnck

import blockifydbus
import blocklist
import util


log = logging.getLogger("main")
pygtk.require("2.0")


class Blockify(object):

    def __init__(self, blocklist):
        self.blocklist = blocklist
        self.orglist = blocklist[:]
        self.check_for_blockify_process()
        self.check_for_spotify_process()

        self._autodetect = util.CONFIG["general"]["autodetect"]
        self._automute = util.CONFIG["general"]["automute"]
        self.update_interval = util.CONFIG["cli"]["update_interval"]
        self.unmute_delay = util.CONFIG["cli"]["unmute_delay"]
        self.pacmd_muted_value = util.CONFIG["general"]["pacmd_muted_value"]
        self.env = os.environ.copy()
        self.env["LC_ALL"] = "en_US"
        self.found = False
        self.current_song = ""
        self.song_status = ""
        self.is_fully_muted = False
        self.is_sink_muted = False
        self.dbus = self.init_dbus()
        self.channels = self.init_channels()
        # The gst library used by interludeplayer for some reason modifies
        # argv, overwriting some of docopts functionality in the process,
        # so we import gst here, where docopts cannot be broken anymore.
        import interludeplayer
        self.player = interludeplayer.InterludePlayer(self)

        # Determine if we can use sinks or have to use alsa.
        try:
            devnull = open(os.devnull)
            subprocess.check_output(["pacmd", "list-sink-inputs"], stderr=devnull)
            self.mutemethod = self.pulsesink_mute
            log.debug("Mute method is pulse sink.")
        except (OSError, subprocess.CalledProcessError):
            log.info("No pulse sinks found, falling back to system mute via alsa.")
            self.mutemethod = self.alsa_mute

        # Only use interlude music if we use pulse sinks and the interlude playlist is non-empty.
        self.use_interlude_music = util.CONFIG["interlude"]["use_interlude_music"] and \
                                   self.mutemethod == self.pulsesink_mute and \
                                   self.player.max_index >= 0

        log.info("Blockify initialized.")

    def check_for_blockify_process(self):
        try:
            pid = subprocess.check_output(["pgrep", "-f", "python.*blockify"])
        except subprocess.CalledProcessError:
            # No blockify process found. Great, this is what we want.
            pass
        else:
            if pid.strip() != str(os.getpid()):
                log.error("A blockify process is already running. Exiting.")
                sys.exit()

    def check_for_spotify_process(self):
        try:
            pidof_out = subprocess.check_output(["pidof", "spotify"])
            self.spotify_pids = pidof_out.decode("utf-8").strip().split(" ")
        except subprocess.CalledProcessError:
            log.error("No spotify process found. Exiting.")
            sys.exit()

    def init_channels(self):
        channel_list = ["Master"]
        amixer_output = subprocess.check_output("amixer")
        if "'Speaker',0" in amixer_output:
            channel_list.append("Speaker")
        if "'Headphone',0" in amixer_output:
            channel_list.append("Headphone")

        return channel_list

    def init_dbus(self):
        try:
            return blockifydbus.BlockifyDBus()
        except Exception as e:
            log.error("Cannot connect to DBus. Exiting.\n ({}).".format(e))
            sys.exit()

    def start(self):
        self.bind_signals()
        self.toggle_mute()

        gtk.timeout_add(self.update_interval, self.update)
        log.info("Blockify started.")
        gtk.main()

    def update(self):
        "Main update routine, looped every self.update_interval milliseconds."
        # Determine if a commercial is running and act accordingly.
        self.found = self.find_ad()

        # Adjust playback of interlude music.
        if self.use_interlude_music:
            self.player.toggle_music()

        # Always return True to keep looping this method.
        return True

    def find_ad(self):
        "Main loop. Checks for ads and mutes accordingly."
        self.current_song = self.get_current_song()
        self.song_status = self.dbus.get_song_status()
        self.dbus.is_playing = self.song_status == "Playing"

        # Manual control is enabled so we exit here.
        if not self.automute:
            return False<commit_msg>Fix #44, second try<commit_after>#!/usr/bin/env python2
"""blockify

Usage:
    blockify [-l <path>] [-v...] [-q] [-h]

Options:
    -l, --log=<path>  Enables logging to the logfile/-path specified.
    -q, --quiet       Don't print anything to stdout.
    -v                Verbosity of the logging module, up to -vvv.
    -h, --help        Show this help text.
    --version         Show current version of blockify.
"""
import logging
import os
import re
import signal
import subprocess
import sys

import gtk
import pygtk
import wnck

import blockifydbus
import blocklist
import util


log = logging.getLogger("main")
pygtk.require("2.0")


class Blockify(object):

    def __init__(self, blocklist):
        self.blocklist = blocklist
        self.orglist = blocklist[:]
        self.check_for_blockify_process()
        self.check_for_spotify_process()

        self._autodetect = util.CONFIG["general"]["autodetect"]
        self._automute = util.CONFIG["general"]["automute"]
        self.update_interval = util.CONFIG["cli"]["update_interval"]
        self.unmute_delay = util.CONFIG["cli"]["unmute_delay"]
        self.pacmd_muted_value = util.CONFIG["general"]["pacmd_muted_value"]
        self.env = os.environ.copy()
        self.env["LC_ALL"] = "en_US"
        self.found = False
        self.current_song = ""
        self.song_status = ""
        self.is_fully_muted = False
        self.is_sink_muted = False
        self.dbus = self.init_dbus()
        self.channels = self.init_channels()
        # The gst library used by interludeplayer for some reason modifies
        # argv, overwriting some of docopts functionality in the process,
        # so we import gst here, where docopts cannot be broken anymore.
        import interludeplayer
        self.player = interludeplayer.InterludePlayer(self)

        # Determine if we can use sinks or have to use alsa.
        try:
            devnull = open(os.devnull)
            subprocess.check_output(["pacmd", "list-sink-inputs"], stderr=devnull)
            self.mutemethod = self.pulsesink_mute
            log.debug("Mute method is pulse sink.")
        except (OSError, subprocess.CalledProcessError):
            log.info("No pulse sinks found, falling back to system mute via alsa.")
            self.mutemethod = self.alsa_mute

        # Only use interlude music if we use pulse sinks and the interlude playlist is non-empty.
        self.use_interlude_music = util.CONFIG["interlude"]["use_interlude_music"] and \
                                   self.mutemethod == self.pulsesink_mute and \
                                   self.player.max_index >= 0

        log.info("Blockify initialized.")

    def check_for_blockify_process(self):
        try:
            pid = subprocess.check_output(["pgrep", "-f", "python.*blockify"])
        except subprocess.CalledProcessError:
            # No blockify process found. Great, this is what we want.
            pass
        else:
            if pid.strip() != str(os.getpid()):
                log.error("A blockify process is already running. Exiting.")
                sys.exit()

    def check_for_spotify_process(self):
        try:
            pidof_out = subprocess.check_output(["pidof", "spotify"])
            self.spotify_pids = pidof_out.decode("utf-8").strip().split(" ")
        except subprocess.CalledProcessError:
            log.error("No spotify process found. Exiting.")
            sys.exit()

    def init_channels(self):
        channel_list = ["Master"]
        amixer_output = subprocess.check_output("amixer")
        if "'Speaker',0" in amixer_output:
            channel_list.append("Speaker")
        if "'Headphone',0" in amixer_output:
            channel_list.append("Headphone")

        return channel_list

    def init_dbus(self):
        try:
            return blockifydbus.BlockifyDBus()
        except Exception as e:
            log.error("Cannot connect to DBus. Exiting.\n ({}).".format(e))
            sys.exit()

    def start(self):
        self.bind_signals()
        self.toggle_mute()

        gtk.timeout_add(self.update_interval, self.update)
        log.info("Blockify started.")
        gtk.main()

    def update(self):
        "Main update routine, looped every self.update_interval milliseconds."
        # Determine if a commercial is running and act accordingly.
        self.found = self.find_ad()

        # Adjust playback of interlude music.
        if self.use_interlude_music:
            self.player.toggle_music()

        # Always return True to keep looping this method.
        return True

    def find_ad(self):
        "Main loop. Checks for ads and mutes accordingly."
        if self.current_song != self.get_current_song() and self.player.is_playing() and not self.dbus.is_playing:
            self.player.pause()
        self.current_song = self.get_current_song()
        self.song_status = self.dbus.get_song_status()
        self.dbus.is_playing = self.song_status == "Playing"

        # Manual control is enabled so we exit here.
        if not self.automute:
            return False
{'fraction_non_alphanumeric': 0.10291919896383382, 'fraction_numerical': 0.0015941018232539603, 'mean_word_length': 2.265452179570592, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7350089', 'n_tokens_mistral': 3010, 'n_tokens_neox': 2912, 'n_words': 751}