#!perl
use 5.010;
use strict;
use warnings;
use utf8;

use Encode qw(decode);
use JSON::PP ();
use Lingua::RU::WER qw(score report);

binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';

my $USAGE = join "\n",
    'Использование: wer-cer-ru <эталон.txt> <распознано.txt> [ключи]',
    '',
    '  --json           результат в JSON',
    '  --ops            показать выравнивание по словам',
    '  --keep-case      не приводить к нижнему регистру',
    '  --keep-punct     не убирать знаки препинания',
    '  --keep-yo        различать «ё» и «е»',
    '  --keep-markup    не убирать таймкоды и имена спикеров',
    '  --keep-notes     не убирать пометки в скобках',
    '  --drop-hes       убрать заминки «э», «эм», «ммм», «хм»',
    '  --split-hyphen   считать «как-то» двумя словами';

my @flags = grep { /^--/ || $_ eq '-h' } @ARGV;
my @files = grep { !/^--/ && $_ ne '-h' } @ARGV;
my %has = map { $_ => 1 } @flags;

if ($has{'--help'} || $has{'-h'} || @files != 2) {
    say $USAGE;
    exit(@files == 2 || $has{'--help'} || $has{'-h'} ? 0 : 2);
}

sub read_text {
    my ($path) = @_;
    open my $fh, '<:raw', $path or die "wer-cer-ru: $path: $!\n";
    my $bytes = do { local $/; <$fh> };
    close $fh;
    my $text = decode('UTF-8', $bytes);
    $text =~ s/^\x{FEFF}//;
    return $text;
}

my %options = (
    lower  => !$has{'--keep-case'},
    punct  => !$has{'--keep-punct'},
    yo     => !$has{'--keep-yo'},
    markup => !$has{'--keep-markup'},
    notes  => !$has{'--keep-notes'},
    hes    => $has{'--drop-hes'},
    hyphen => $has{'--split-hyphen'},
);
my $r = score(read_text($files[0]), read_text($files[1]), \%options);

if ($has{'--json'}) {
    my %out = (
        wer              => $r->{wer},
        cer              => $r->{cer},
        cerApprox        => $r->{cer_approx} ? JSON::PP::true : JSON::PP::false,
        words            => $r->{n},
        hypothesisWords  => $r->{m},
        substitutions    => $r->{s},
        deletions        => $r->{d},
        insertions       => $r->{i},
        hits             => $r->{h},
        topSubstitutions => $r->{pairs},
    );
    $out{ops} = $r->{ops} if $has{'--ops'};
    print JSON::PP->new->canonical->pretty->indent_length(2)->encode(\%out);
    exit(defined $r->{wer} ? 0 : 1);
}
if ($r->{too_long}) {
    print STDERR "Тексты слишком длинные для выравнивания: разбейте запись на части примерно по 4 000 слов.\n";
    exit 1;
}
if (!$r->{n}) {
    print STDERR "В эталоне не осталось слов после нормализации.\n";
    exit 1;
}
say report($r);
if (@{ $r->{pairs} }) {
    say 'Частые замены:';
    say "  $_->[1]× $_->[0]" for @{ $r->{pairs} };
}
if ($has{'--ops'}) {
    say join ' ', map {
          $_->[0] eq '=' ? $_->[1]
        : $_->[0] eq 's' ? "[$_->[1]→$_->[2]]"
        : $_->[0] eq 'd' ? "[-$_->[1]]"
        :                  "[+$_->[2]]"
    } @{ $r->{ops} };
}

__END__

=encoding UTF-8

=head1 NAME

wer-cer-ru - WER and CER of a Russian transcript against a reference, from the command line

=head1 SYNOPSIS

    wer-cer-ru etalon.txt raspoznano.txt [--json] [--ops] [--drop-hes] ...

=head1 DESCRIPTION

Сравнивает эталон с расшифровкой и печатает WER, CER и частые замены. Ключи описаны в
L<Lingua::RU::WER/COMMAND LINE>, краткую справку выводит C<wer-cer-ru --help>.

=cut
