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

py_func convert unicode string results to bytes for python2 #16322

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions tensorflow/python/kernel_tests/py_func_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -212,6 +213,16 @@ def testAlias(self):
value.op.run()
self.assertAllEqual(np_array, [1.0, 2.0])

def testReturnUnicodeString(self):
with self.test_session():
correct = u"你好 世界"

def unicode_string():
return correct

z, = script_ops.py_func(unicode_string, [], [dtypes.string])
self.assertEqual(z.eval(), correct.encode("utf8"))

def testBadNumpyReturnType(self):
with self.test_session():

Expand Down
4 changes: 2 additions & 2 deletions tensorflow/python/ops/script_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def _convert(value, dtype=None):
components of a tensor have different lengths. This is bad: ignoring the
padding is wrong for text data, and removing the padding is wrong for binary
data. To avoid this bug, we redo the conversion using an object dtype.
Additionally, we convert unicode strings to (byte-)strings for Python3
Additionally, we convert unicode strings to (byte-)strings for
compatibility.

Args:
Expand All @@ -109,7 +109,7 @@ def _convert(value, dtype=None):
if result.dtype.char == "S" and result is not value:
return np.asarray(value, order="C", dtype=object)
elif result.dtype.char == "U" and result is not value:
value = np.vectorize(lambda x: x.encode())(value)
value = np.vectorize(lambda x: x.encode("utf8"))(value)
Copy link
Member Author

@facaiy facaiy Jan 23, 2018

Choose a reason for hiding this comment

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

The code here is really tricky on Python 2. It lets English word pass, say u'hello', while all Chinese words are blocked, say u'你好'. The inconsistent result is expected?

return np.asarray(value, order="C", dtype=object)
elif result.dtype.char == "U":
return result.astype(np.bytes_)
Expand Down