Skip to content

Commit 4bba3f8

Browse files
committed
Improve string display from byte array.
1 parent c2f13e2 commit 4bba3f8

8 files changed

Lines changed: 52 additions & 29 deletions

File tree

‎src/TensorFlowNET.Core/Eager/EagerTensor.Creation.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,13 @@ public EagerTensor(string value, string device_name) : base(value)
2525
EagerTensorHandle = c_api.TFE_NewTensorHandle(_handle, tf.status.Handle);
2626
Resolve();
2727
}
28-
28+
29+
public EagerTensor(byte[] value, string device_name, TF_DataType dtype) : base(value, dType: dtype)
30+
{
31+
EagerTensorHandle = c_api.TFE_NewTensorHandle(_handle, tf.status.Handle);
32+
Resolve();
33+
}
34+
2935
public EagerTensor(NDArray value, string device_name) : base(value)
3036
{
3137
EagerTensorHandle = c_api.TFE_NewTensorHandle(_handle, tf.status.Handle);

‎src/TensorFlowNET.Core/Eager/EagerTensor.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using NumSharp;
22
using System;
33
using System.Collections.Generic;
4+
using System.Linq;
45
using System.Text;
56
using static Tensorflow.Binding;
67

@@ -49,7 +50,8 @@ public static string GetFormattedString(TF_DataType dtype, NDArray nd)
4950
switch (dtype)
5051
{
5152
case TF_DataType.TF_STRING:
52-
return $"b'{(string)nd}'";
53+
return string.Join(string.Empty, nd.ToArray<byte>()
54+
.Select(x => x < 32 || x > 127 ? "\\x" + x.ToString("x") : Convert.ToChar(x).ToString()));
5355
case TF_DataType.TF_BOOL:
5456
return (nd.GetByte(0) > 0).ToString();
5557
case TF_DataType.TF_RESOURCE:

‎src/TensorFlowNET.Core/Tensors/Tensor.Creation.cs‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -452,14 +452,14 @@ public unsafe Tensor(Complex value, TF_DataType? dType = null)
452452
public unsafe Tensor(string str)
453453
{
454454
var buffer = Encoding.UTF8.GetBytes(str);
455-
var size = c_api.TF_StringEncodedSize((UIntPtr)buffer.Length);
456-
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, IntPtr.Zero, 0, (UIntPtr)((ulong)size + sizeof(ulong)));
455+
var size = c_api.TF_StringEncodedSize((ulong)buffer.Length);
456+
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, IntPtr.Zero, 0, (UIntPtr)(size + sizeof(ulong)));
457457
AllocationType = AllocationType.Tensorflow;
458458

459459
IntPtr tensor = c_api.TF_TensorData(handle);
460460
Marshal.WriteInt64(tensor, 0);
461461
fixed (byte* src = buffer)
462-
c_api.TF_StringEncode(src, (UIntPtr)buffer.Length, (sbyte*)(tensor + sizeof(long)), size, tf.status.Handle);
462+
c_api.TF_StringEncode(src, (ulong)buffer.Length, (sbyte*)(tensor + sizeof(long)), size, tf.status.Handle);
463463
_handle = handle;
464464
tf.status.Check(true);
465465
}
@@ -474,29 +474,29 @@ public unsafe Tensor(NDArray nd, TF_DataType? tensorDType = null)
474474
{
475475
if (nd.Unsafe.Storage.Shape.IsContiguous)
476476
{
477-
var bytesLength = (UIntPtr) nd.size;
477+
var bytesLength = (ulong)nd.size;
478478
var size = c_api.TF_StringEncodedSize(bytesLength);
479479
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, IntPtr.Zero, 0, (UIntPtr) ((ulong) size + 8));
480480
AllocationType = AllocationType.Tensorflow;
481481

482482
IntPtr tensor = c_api.TF_TensorData(handle);
483483
Marshal.WriteInt64(tensor, 0);
484484

485-
c_api.TF_StringEncode((byte*) nd.Unsafe.Address, bytesLength, (sbyte*) (tensor + sizeof(Int64)), size, tf.status.Handle);
485+
c_api.TF_StringEncode((byte*) nd.Unsafe.Address, bytesLength, (sbyte*) (tensor + sizeof(long)), size, tf.status.Handle);
486486
tf.status.Check(true);
487487
_handle = handle;
488488
} else
489489
{
490490
var buffer = nd.ToArray<byte>();
491-
var size = c_api.TF_StringEncodedSize((UIntPtr) buffer.Length);
491+
var size = c_api.TF_StringEncodedSize((ulong)buffer.Length);
492492
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, IntPtr.Zero, 0, (UIntPtr) ((ulong) size + 8));
493493
AllocationType = AllocationType.Tensorflow;
494494

495495
IntPtr tensor = c_api.TF_TensorData(handle);
496496
Marshal.WriteInt64(tensor, 0);
497497

498498
fixed (byte* src = buffer)
499-
c_api.TF_StringEncode(src, (UIntPtr) buffer.Length, (sbyte*) (tensor + sizeof(Int64)), size, tf.status.Handle);
499+
c_api.TF_StringEncode(src, (ulong)buffer.Length, (sbyte*) (tensor + sizeof(Int64)), size, tf.status.Handle);
500500

501501
tf.status.Check(true);
502502
_handle = handle;
@@ -538,7 +538,7 @@ public unsafe Tensor(byte[][] buffer, long[] shape)
538538
int size = 0;
539539
foreach (var b in buffer)
540540
{
541-
size += (int) TF_StringEncodedSize((UIntPtr) b.Length);
541+
size += (int)TF_StringEncodedSize((ulong)b.Length);
542542
}
543543

544544
int totalSize = size + buffer.Length * 8;
@@ -557,7 +557,7 @@ public unsafe Tensor(byte[][] buffer, long[] shape)
557557
{
558558
fixed (byte* src = &buffer[i][0])
559559
{
560-
var written = TF_StringEncode(src, (UIntPtr) buffer[i].Length, (sbyte*) dst, (UIntPtr) (dstLimit.ToInt64() - dst.ToInt64()), status.Handle);
560+
var written = TF_StringEncode(src, (ulong)buffer[i].Length, (sbyte*)dst, (ulong)(dstLimit.ToInt64() - dst.ToInt64()), status.Handle);
561561
status.Check(true);
562562
pOffset += 8;
563563
dst += (int) written;
@@ -592,25 +592,27 @@ public Tensor(Operation op, int value_index, TF_DataType dtype)
592592
/// </remarks>
593593
[MethodImpl(MethodImplOptions.AggressiveInlining)]
594594
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
595-
protected unsafe IntPtr CreateTensorFromArray(TF_DataType dt, long[] shape, Array data, int element_size)
595+
protected IntPtr CreateTensorFromArray(TF_DataType dt, long[] shape, Array data, int element_size)
596596
{
597597
if (dt == TF_DataType.TF_STRING && data is byte[] buffer)
598-
{
599-
var size = c_api.TF_StringEncodedSize((UIntPtr) buffer.Length);
600-
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, IntPtr.Zero, 0, (UIntPtr) ((ulong) size + 8));
601-
AllocationType = AllocationType.Tensorflow;
598+
return CreateStringTensorFromBytes(buffer, shape);
599+
return CreateTensorFromArray(dt, shape, data, 0, data.Length, element_size);
600+
}
602601

603-
IntPtr tensor = c_api.TF_TensorData(handle);
604-
Marshal.WriteInt64(tensor, 0);
602+
protected unsafe IntPtr CreateStringTensorFromBytes(byte[] buffer, long[] shape)
603+
{
604+
var size = c_api.TF_StringEncodedSize((ulong)buffer.Length);
605+
var handle = TF_AllocateTensor(TF_DataType.TF_STRING, shape, 0, size + sizeof(long));
606+
AllocationType = AllocationType.Tensorflow;
605607

606-
fixed (byte* src = buffer)
607-
c_api.TF_StringEncode(src, (UIntPtr) buffer.Length, (sbyte*) (tensor + sizeof(long)), size, tf.status.Handle);
608+
IntPtr tensor = c_api.TF_TensorData(handle);
609+
Marshal.WriteInt64(tensor, 0);
608610

609-
tf.status.Check(true);
610-
return handle;
611-
}
611+
fixed (byte* src = buffer)
612+
c_api.TF_StringEncode(src, (ulong)buffer.Length, (sbyte*)(tensor + sizeof(long)), size, tf.status.Handle);
612613

613-
return CreateTensorFromArray(dt, shape, data, 0, data.Length, element_size);
614+
tf.status.Check(true);
615+
return handle;
614616
}
615617

616618
/// <summary>

‎src/TensorFlowNET.Core/Tensors/Tensor.Value.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ protected unsafe NDArray GetNDArray(TF_DataType dtype)
159159
switch (dtype)
160160
{
161161
case TF_DataType.TF_STRING:
162-
return (NDArray)StringData()[0];
162+
return np.array(StringBytes()[0]);
163163
case TF_DataType.TF_INT32:
164164
storage = new UnmanagedStorage(NPTypeCode.Int32);
165165
break;

‎src/TensorFlowNET.Core/Tensors/c_api.tensor.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ public static unsafe IntPtr TF_NewTensor(TF_DataType dataType, long[] dims, int
170170
/// <param name="len">size_t</param>
171171
/// <returns></returns>
172172
[DllImport(TensorFlowLibName)]
173-
public static extern UIntPtr TF_StringEncodedSize(UIntPtr len);
173+
public static extern ulong TF_StringEncodedSize(ulong len);
174174

175175
/// <summary>
176176
/// Encode the string `src` (`src_len` bytes long) into `dst` in the format
@@ -185,7 +185,7 @@ public static unsafe IntPtr TF_NewTensor(TF_DataType dataType, long[] dims, int
185185
/// <param name="status">TF_Status*</param>
186186
/// <returns>On success returns the size in bytes of the encoded string.</returns>
187187
[DllImport(TensorFlowLibName)]
188-
public static extern unsafe ulong TF_StringEncode(byte* src, UIntPtr src_len, sbyte* dst, UIntPtr dst_len, SafeStatusHandle status);
188+
public static extern unsafe ulong TF_StringEncode(byte* src, ulong src_len, sbyte* dst, ulong dst_len, SafeStatusHandle status);
189189

190190
[DllImport(TensorFlowLibName)]
191191
public static extern unsafe ulong TF_StringEncode(IntPtr src, ulong src_len, IntPtr dst, ulong dst_len, SafeStatusHandle status);

‎src/TensorFlowNET.Core/Tensors/constant_op.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ private static EagerTensor convert_to_eager_tensor(object value, Context ctx, TF
130130
}
131131
}
132132

133+
if(dtype == TF_DataType.TF_STRING && value is byte[] bytes)
134+
{
135+
return new EagerTensor(bytes, ctx.device_name, TF_DataType.TF_STRING);
136+
}
137+
133138
switch (value)
134139
{
135140
case EagerTensor val:

‎test/TensorFlowNET.UnitTest/ConstantTest.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,10 @@ public void StringEncode()
165165
{
166166
string str = "Hello, TensorFlow.NET!";
167167
var handle = Marshal.StringToHGlobalAnsi(str);
168-
ulong dst_len = (ulong)c_api.TF_StringEncodedSize((UIntPtr)str.Length);
168+
var dst_len = c_api.TF_StringEncodedSize((ulong)str.Length);
169169
Assert.AreEqual(dst_len, (ulong)23);
170170
IntPtr dst = Marshal.AllocHGlobal((int)dst_len);
171-
ulong encoded_len = c_api.TF_StringEncode(handle, (ulong)str.Length, dst, dst_len, status.Handle);
171+
var encoded_len = c_api.TF_StringEncode(handle, (ulong)str.Length, dst, dst_len, status.Handle);
172172
Assert.AreEqual((ulong)23, encoded_len);
173173
Assert.AreEqual(status.Code, TF_Code.TF_OK);
174174
string encoded_str = Marshal.PtrToStringUTF8(dst + sizeof(byte));

‎test/TensorFlowNET.UnitTest/TF_API/StringsApiTest.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ namespace Tensorflow.UnitTest.TF_API
99
[TestClass]
1010
public class StringsApiTest
1111
{
12+
[TestMethod]
13+
public void StringFromBytes()
14+
{
15+
var jpg = tf.constant(new byte[] { 0x41, 0xff, 0xd8, 0xff }, tf.@string);
16+
var strings = jpg.ToString();
17+
Assert.AreEqual(strings, @"tf.Tensor: shape=(), dtype=string, numpy=A\xff\xd8\xff");
18+
}
19+
1220
[TestMethod]
1321
public void StringEqual()
1422
{

0 commit comments

Comments
 (0)