resource_to_cpp.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. ## ======================================================================== ##
  3. ## Copyright 2009-2019 Intel Corporation ##
  4. ## ##
  5. ## Licensed under the Apache License, Version 2.0 (the "License"); ##
  6. ## you may not use this file except in compliance with the License. ##
  7. ## You may obtain a copy of the License at ##
  8. ## ##
  9. ## http://www.apache.org/licenses/LICENSE-2.0 ##
  10. ## ##
  11. ## Unless required by applicable law or agreed to in writing, software ##
  12. ## distributed under the License is distributed on an "AS IS" BASIS, ##
  13. ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ##
  14. ## See the License for the specific language governing permissions and ##
  15. ## limitations under the License. ##
  16. ## ======================================================================== ##
  17. import os
  18. from array import array
  19. # Generates a C++ file from the specified binary resource file
  20. def generate(in_path, out_path):
  21. namespace = "oidn::weights"
  22. scopes = namespace.split("::")
  23. file_name = os.path.basename(in_path)
  24. var_name = os.path.splitext(file_name)[0]
  25. with open(in_path, "rb") as in_file, open(out_path, "w") as out_file:
  26. # Header
  27. out_file.write("// Generated from: %s\n" % file_name)
  28. out_file.write("#include <cstddef>\n\n")
  29. # Open the namespaces
  30. for s in scopes:
  31. out_file.write("namespace %s {\n" % s)
  32. if scopes:
  33. out_file.write("\n")
  34. # Read the file
  35. in_data = array("B", in_file.read())
  36. # Write the size
  37. out_file.write("//const size_t %s_size = %d;\n\n" % (var_name, len(in_data)))
  38. # Write the data
  39. out_file.write("unsigned char %s[] = {" % var_name)
  40. for i in range(len(in_data)):
  41. c = in_data[i]
  42. if i > 0:
  43. out_file.write(",")
  44. if (i + 1) % 20 == 1:
  45. out_file.write("\n")
  46. out_file.write("%d" % c)
  47. out_file.write("\n};\n")
  48. # Close the namespaces
  49. if scopes:
  50. out_file.write("\n")
  51. for scope in reversed(scopes):
  52. out_file.write("} // namespace %s\n" % scope)
  53. def tza_to_cpp(target, source, env):
  54. for x in zip(source, target):
  55. generate(str(x[0]), str(x[1]))