Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[src,build] Add minimal example to demonstrate pybind11 binding #3668

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/pybind/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ you can cd to here and do:
# make
# python3
>>> import kaldi_pybind as k
>>> str(k.FloatVector(10))
' [ 0 0 0 0 0 0 0 0 0 0 ]\n'
>>>
>>> import numpy as np
>>> a = k.FloatVector(10)
>>> b = np.array(a, copy_data = False)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copy_data is an invalid argument.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be copy

>>> b[5:10] = 2.0
>>> str(a)
[ 0 0 0 0 0 2 2 2 2 2 ]

```
20 changes: 16 additions & 4 deletions src/pybind/kaldi_pybind.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,25 @@ PYBIND11_MODULE(kaldi_pybind, m) {
.value("kCopyData", kCopyData, "Copy any previously existing data")
.export_values();

py::class_<Vector<float> >(m, "FloatVector")
.def(py::init<const MatrixIndexT, MatrixResizeType>(),
py::arg("size"), py::arg("resize_type") = kSetZero)

py::class_<Vector<float> >(m, "FloatVector", pybind11::buffer_protocol())
.def_buffer([](const Vector<float> &v) -> pybind11::buffer_info {
return pybind11::buffer_info(
(void*)v.Data(),
sizeof(float),
pybind11::format_descriptor<float>::format(),
1, // num-axes
{ v.Dim() },
{ 4 }); // strides (in chars)
})
.def("Dim", &Vector<float>::Dim, "Return the dimension of the vector")
.def("__repr__",
[] (const Vector<float> &a) -> std::string {
std::ostringstream str; a.Write(str, false); return str.str();
});
})
.def(py::init<const MatrixIndexT, MatrixResizeType>(),
py::arg("size"), py::arg("resize_type") = kSetZero);

}


Expand Down