0

I am trying to use Mxnet-js library to visualize my Mxnet trained model in browser. I am following Mxnet-js git readme file.

They provided a python script. ./tool/model2json, to convert model to json file. When i am running this script with my model i am getting error:

TypeError: write() argument must be str, not bytes

Getting this error make sense because, how can i write byte to a file that is opened in string mode. At line

model = base64.b64encode(bytes(open(sys.argv[3], 'rb').read()))

they are reading it in bytes but in line

with open(sys.argv1, 'w') as fo:

they are opening file in string mode and in line

fo.write(model)

they are writing bytes to string.

Am i missing something here ? Why they are trying to write bytes to string?

#!/usr/bin/env python
"""Simple util to convert mxnet model to json format."""
import sys
import json
import base64

if len(sys.argv) < 4:
    print('Usage: <output.json> <symbol.json> <model.param> 
                                [mean_image.nd] [synset]')
    exit(0)

symbol_json = open(sys.argv[2]).read()
model = base64.b64encode(bytes(open(sys.argv[3], 'rb').read()))
mean_image = None
synset = None

if len(sys.argv) > 4:
    mean_image = base64.b64encode(bytes(open(sys.argv[4], 
                                      'rb').read()))

if len(sys.argv) > 5:
    synset = [l.strip() for l in open(sys.argv[5]).readlines()]

with open(sys.argv[1], 'w') as fo:

    fo.write('{\n\"symbol\":\n')
    fo.write(symbol_json)
    if synset:
        fo.write(',\n\"synset\": ')
        fo.write(json.dumps(synset))
    fo.write(',\n\"parambase64\": \"')

    fo.write(model)
    fo.write('\"\n')
    if mean_image is not None:
        fo.write(',\n\"meanimgbase64\": \"')
        fo.write(mean_image)
        fo.write('\"\n')
fo.write('}\n')
Sherlock
  • 993
  • 1
  • 10
  • 22

1 Answers1

2

TL;DR Are you using Python3? If so - use Python2 and things should work!

More details: The code opens the model's binary weight file, reads the binary data, constructs a Bytes sequence (Python builtin type), and converts it into String.

Now, while Python 2 implicitly converts Bytes to String, Python 3 does not do it. So I suspect you are using Python 3, and then your conversion is incorrect.

To check your version run python --version If you are indeed using Python 3, you can try and update line 12 of model2json.py to have explicit conversion: model = str(base64.b64encode(bytes(open(sys.argv[3], 'rb').read()))) Note that for Python 3 you will also need to launch the local web server using a different command than the one noted on the readme.md: $ python3 -m http.server

My recommendation is that you use Python 2 since this entire repo is written for it, and using Python3 you might encounter other issues.

Hagay Lupesko
  • 368
  • 1
  • 11