Translator.pm 2.25 KB
Newer Older
priyank's avatar
priyank committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
package ILMT::Translator;
use strict;
use warnings;
use Dir::Self;
use Data::Dumper;
use Exporter qw(import);
use Module::Pluggable::Object;
use Module::Runtime qw(use_module);

our @EXPORT_OK = qw(get_translator get_langpairs);

my %translator_table;

sub new_translator {
    my $class = shift;
    my $self = {
        src => shift,
        tgt => shift,
    };

    my $search_path = "ILMT::$self->{src}::$self->{tgt}";

    @{$self->{plugins}} = map use_module($_),
                            grep /^${search_path}::[^:]+$/,
                              Module::Pluggable::Object->new(search_path => $search_path)->plugins;

    $self->{seq} = shift;

    bless $self, $class;

    # Register this module as a translator service
    $translator_table{$self->{src}}{$self->{tgt}} = $self;

    return $self;
}

sub get_translator {
    my ($src, $tgt) = @_;
    return $translator_table{$src}{$tgt};
}

sub get_langpairs {
    print Dumper(\%translator_table);
    return map +(lc $_ => [ map lc, keys %{$translator_table{$_}} ]), keys %translator_table;
}

sub translate {
    my ($self, %args) = @_;
    my $result = "";
    my @identifiers;
    my %final_result;
    my @dispatch_seq = @{$self->{seq}};
    foreach my $index (0 .. $#dispatch_seq) {
        my $module = $dispatch_seq[$index ++];
        my $identifier = lc("${module}-$index");
        push @identifiers, $identifier;
        my $package = "ILMT::$self->{src}::$self->{tgt}::$module";
        $args{$identifier} = $package->can('process')->(%args);
        $args{'data'} = $args{$identifier};
    }
    @final_result{@identifiers} = @args{@identifiers};
    return \%final_result;
}

sub partial_p {
    my ($self, $start, $end, %args) = @_;
    my $result = "";
    my @dispatch_seq = @{$self->{seq}};
    my @identifiers;
    my %final_result;
    foreach my $index ($start .. $end) {
        my $module = $dispatch_seq[$index - 1];
        my $identifier = lc("${module}-$index");
        push @identifiers, $identifier;
	print "module ##  $module\n";
        my $package = "ILMT::$self->{src}::$self->{tgt}::$module";
        $args{$identifier} = $package->can('process')->(%args);
        $args{'data'} = $args{$identifier};
    }
    @final_result{@identifiers} = @args{@identifiers};
    return \%final_result;
}

1;