AI-MXNet

 view release on metacpan or  search on metacpan

lib/AI/MXNet/RecordIO.pm  view on Meta::CPAN

    Write a string buffer as a record.

    Parameters
    ----------
    $buf : a buffer to write.
=cut

method write(Str $buf)
{
    assert($self->writable);
    check_call(
        AI::MXNetCAPI::RecordIOWriterWriteRecord(
            $self->handle,
            $buf,
            length($buf)
        )
    );
}

=head2 read

    Read a record as a string.

    Returns
    ----------
    $buf : string
=cut

method read()
{
    assert(not $self->writable);
    return scalar(check_call(
        AI::MXNetCAPI::RecordIOReaderReadRecord(
            $self->handle,
        )
    ));
}

method MXRecordIO(@args) { return AI::MXNet::RecordIO->new(uri => $args[0], flag => $args[1]) }
method MXIndexedRecordIO(@args)
{
    return AI::MXNet::IndexedRecordIO->new(
        idx_path => $args[0], uri => $args[1], flag => $args[2]
    )
}

package AI::MXNet::IRHeader;
use Mouse;
has [qw/flag id id2/] => (is => 'rw', isa => 'Int');
has 'label'           => (is => 'rw', isa => 'AcceptableInput');
around BUILDARGS => sub {
    my $orig  = shift;
    my $class = shift;
    if(@_ == 4)
    {
        return $class->$orig(flag => $_[0], label => $_[1], id => $_[2], id2 => $_[3]);
    }
    return $class->$orig(@_);
};
my @order = qw/flag label id id2/;
use overload '@{}' => sub { my $self = shift; [map { $self->$_ } @order] };

package AI::MXNet::RecordIO;

=head2 unpack

    unpack a MXImageRecord to a string

    Parameters
    ----------
    s : str
        string buffer from MXRecordIO.read

    Returns
    -------
    header : AI::MXNet::IRHeader
        header of the image record
    s : str
        unpacked string
=cut

method unpack(Str $s)
{
    my $h;
    my $h_size = 24;
    ($h, $s) = (substr($s, 0, $h_size), substr($s, $h_size));
    my $header = AI::MXNet::IRHeader->new(unpack('IfQQ', $h));
    if($header->flag > 0)
    {
        my $label;
        ($label, $s) = (substr($s, 0, 4*$header->flag), substr($s, 4*$header->flag));
        my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{float32});
        my $pdl = PDL->new_from_specification($pdl_type, $header->flag);
        ${$pdl->get_dataref} = $label;
        $pdl->upd_data;
        $header->label($pdl);
    }
    return ($header, $s)
}

=head2 pack

    pack a string into MXImageRecord

    Parameters
    ----------
    $header : AI::MXNet::IRHeader or ArrayRef suitable for AI::MXNet::IRHeader->new(@{ ArrayRef })
        header of the image record.
        $header->label can be a number or an array ref.
    s : str
        string to pack
=cut

method pack(AI::MXNet::IRHeader|ArrayRef $header, Str $s)
{
    $header = AI::MXNet::IRHeader->new(@$header) unless blessed $header;
    if(not ref $header->label)
    {
        $header->flag(0);
    }
    else



( run in 1.058 second using v1.01-cache-2.11-cpan-39bf76dae61 )