<commit_before># -*- coding: utf-8 -*-
"""
    profiling.__main__
    ~~~~~~~~~~~~~~~~~~

    The command-line interface.

    .. sourcecode:: console

       $ python -m profiling --help

"""
from __future__ import absolute_import
from datetime import datetime
import importlib
import os
try:
    import cPickle as pickle
except ImportError:
    import pickle
import socket
from stat import S_ISREG, S_ISSOCK
import sys

import click
from six import PY2, exec_
import urwid

from .profiler import Profiler
from .remote import recv_stats
from .viewer import StatisticsViewer


__all__ = ['main', 'profile', 'view']


@click.group()
def main():
    pass


def make_viewer():
    viewer = StatisticsViewer()
    viewer.use_vim_command_map()
    viewer.use_game_command_map()
    return viewer


timers = {
    # timer name: (timer module name, timer class name)
    None: ('.timers', 'Timer'),
    'thread': ('.timers.thread', 'ThreadTimer'),
    'yappi': ('.timers.thread', 'YappiTimer'),
    'greenlet': ('.timers.greenlet', 'GreenletTimer'),
}


def get_timer(ctx, param, value):
    try:
        module_name, class_name = timers[value]
    except KeyError:
        raise ValueError('No such timer: {0}'.format(value))
    module = importlib.import_module(module_name, __package__)
    timer_class = getattr(module, class_name)
    return timer_class()


@main.command()
@click.argument('script', type=click.File('rb'))
@click.option('-t', '--timer', callback=get_timer)
@click.option('-d', '--dump', 'dump_filename', type=click.Path(writable=True))
@click.option('--mono', is_flag=True)
def profile(script, timer=None, dump_filename=None, mono=False):
    """Profile a Python script."""
    code = compile(script.read(), script.name, 'exec')
    script.close()
    sys.argv[:] = [script.name]
    globals_ = {
        '__file__': script.name,
        '__name__': '__main__',
        '__package__': None,
    }
    profiler = Profiler(timer)
    frame = sys._getframe()
    profiler.start(top_frame=frame, top_code=code)
    try:
        exec_(code, globals_)
    finally:
        profiler.stop()
    if PY2:
        # on Python 2, exec's cpu time is duplicated with actual cpu time.
        stat = profiler.stats.get_child(frame.f_code)
        stat.remove_child(exec_.func_code)
    if dump_filename is None:
        viewer = make_viewer()
        viewer.set_stats(profiler.stats)
        loop = viewer.loop()
        if mono:
            loop.screen.set_terminal_properties(1)
        try:
            loop.run()
        except KeyboardInterrupt:
            pass
    else:
        stats = profiler.frozen_stats()
        with open(dump_filename, 'w') as f:
            pickle.dump(stats, f)
        click.echo('To view statistics:')
        click.echo('  $ python -m profiling view ', nl=False)
        click.secho(dump_filename, underline=True)


def parse_src(src):
    """Parses a source string to source type and source name.
<commit_msg>fix typo<commit_after># -*- coding: utf-8 -*-
"""
    profiling.__main__
    ~~~~~~~~~~~~~~~~~~

    The command-line interface.

    .. sourcecode:: console

       $ python -m profiling --help

"""
from __future__ import absolute_import
from datetime import datetime
import importlib
import os
try:
    import cPickle as pickle
except ImportError:
    import pickle
import socket
from stat import S_ISREG, S_ISSOCK
import sys

import click
from six import PY2, exec_
import urwid

from .profiler import Profiler
from .remote import recv_stats
from .viewer import StatisticsViewer


__all__ = ['main', 'profile', 'view']


@click.group()
def main():
    pass


def make_viewer():
    viewer = StatisticsViewer()
    viewer.use_vim_command_map()
    viewer.use_game_command_map()
    return viewer


timers = {
    # timer name: (timer module name, timer class name)
    None: ('.timers', 'Timer'),
    'thread': ('.timers.thread', 'ThreadTimer'),
    'yappi': ('.timers.thread', 'YappiTimer'),
    'greenlet': ('.timers.greenlet', 'GreenletTimer'),
}


def get_timer(ctx, param, value):
    try:
        module_name, class_name = timers[value]
    except KeyError:
        raise ValueError('No such timer: {0}'.format(value))
    module = importlib.import_module(module_name, __package__)
    timer_class = getattr(module, class_name)
    return timer_class()


@main.command()
@click.argument('script', type=click.File('rb'))
@click.option('-t', '--timer', callback=get_timer)
@click.option('-d', '--dump', 'dump_filename', type=click.Path(writable=True))
@click.option('--mono', is_flag=True)
def profile(script, timer=None, dump_filename=None, mono=False):
    """Profile a Python script."""
    code = compile(script.read(), script.name, 'exec')
    script.close()
    sys.argv[:] = [script.name]
    globals_ = {
        '__file__': script.name,
        '__name__': '__main__',
        '__package__': None,
    }
    profiler = Profiler(timer)
    frame = sys._getframe()
    profiler.start(top_frame=frame, top_code=code)
    try:
        exec_(code, globals_)
    finally:
        profiler.stop()
    if PY2:
        # in Python 2, exec's cpu time is duplicated with actual cpu time.
        stat = profiler.stats.get_child(frame.f_code)
        stat.remove_child(exec_.func_code)
    if dump_filename is None:
        viewer = make_viewer()
        viewer.set_stats(profiler.stats)
        loop = viewer.loop()
        if mono:
            loop.screen.set_terminal_properties(1)
        try:
            loop.run()
        except KeyboardInterrupt:
            pass
    else:
        stats = profiler.frozen_stats()
        with open(dump_filename, 'w') as f:
            pickle.dump(stats, f)
        click.echo('To view statistics:')
        click.echo('  $ python -m profiling view ', nl=False)
        click.secho(dump_filename, underline=True)


def parse_src(src):
    """Parses a source string to source type and source name.

{'fraction_non_alphanumeric': 0.1327899473594838, 'fraction_numerical': 0.0020376974019358125, 'mean_word_length': 3.04532967032967, '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': '4401249', 'n_tokens_mistral': 1915, 'n_tokens_neox': 1884, 'n_words': 475}