xrntranslate-cli 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env python3
  2. '''
  3. Software License
  4. Copyright (C) 2021-05-24 Xoronos
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, version 3.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. '''
  15. '''
  16. Liabilities
  17. The software is provided "AS IS" without any warranty of any kind, either expressed,
  18. implied, or statutory, including, but not limited to, any warranty that the software
  19. will conform to specifications, any implied warranties of merchantability, fitness
  20. for a particular purpose, and freedom from infringement, and any warranty that the
  21. documentation will conform to the software, or any warranty that the software will
  22. be error free.
  23. In no event shall Xoronos be liable for any damages, including, but not limited to,
  24. direct, indirect, special or consequential damages, arising out of, resulting from,
  25. or in any way connected with this software, whether or not based upon warranty,
  26. contract, tort, or otherwise, whether or not injury was sustained by persons or
  27. property or otherwise, and whether or not loss was sustained from, or arose out of
  28. the results of, or use of, the software or services provided hereunder.
  29. To request the provided software under a different license you can contact us at
  30. support@xoronos.com
  31. '''
  32. import os
  33. import sys
  34. import re
  35. import json
  36. def string_to_matrix(input_string):
  37. matrix = []
  38. lines = input_string.split('\n')
  39. for line in lines:
  40. words = line.split()
  41. matrix.append(words)
  42. return matrix
  43. def split_list_in_configurations_and_command (input_list):
  44. configurations=[]
  45. command=[]
  46. first_conf = 0
  47. conf_row = 0
  48. conf_cmd = 0
  49. # create arrays for configurations and command
  50. for word in input_list :
  51. # configuration
  52. if re.match("^--.*-conf$", word):
  53. if first_conf == 0:
  54. first_conf = 1
  55. if conf_row >= len(configurations):
  56. configurations.append([])
  57. else :
  58. conf_row = conf_row + 1
  59. if conf_row >= len(configurations):
  60. configurations.append([])
  61. configurations[conf_row].append( word[2:] )
  62. # command
  63. elif re.match("^--", word):
  64. conf_cmd = 1
  65. command.append( word[2:] )
  66. # option
  67. else :
  68. if conf_cmd == 0 :
  69. if conf_row >= len(configurations):
  70. configurations.append([])
  71. configurations[conf_row].append(word[1:])
  72. else :
  73. command.append( word[1:] )
  74. return configurations, command
  75. def create_json_string_template(tool_name,input_list):
  76. configurations, command = split_list_in_configurations_and_command(input_list)
  77. json_str = '{"tool": "'+tool_name+'",\n"configurations":[\n'
  78. if not configurations :
  79. json_str=json_str+'],\n'
  80. else :
  81. # create json for configurations
  82. for j, row in enumerate(configurations) :
  83. for i, word in enumerate(row):
  84. if i == 0 :
  85. json_str = json_str + '{ "name" : "'+row[i]+'",\n"options":[\n'
  86. elif i == len(row) - 1 :
  87. json_str = json_str + '{ "name" : "'+row[i]+'","value":null}\n'
  88. else :
  89. json_str = json_str + '{ "name" : "'+row[i]+'","value":null},\n'
  90. if j != len(configurations) - 1 :
  91. json_str = json_str + ']},\n'
  92. else :
  93. json_str = json_str + ']}],\n'
  94. # create json for command
  95. json_str = json_str + '"command":['
  96. for i, word in enumerate(command) :
  97. if i == 0 :
  98. json_str = json_str + '{ "name" : "'+word+'",\n"options":[\n'
  99. elif i == len(command) - 1 :
  100. json_str = json_str + '{ "name" : "'+word+'","value":null}\n'
  101. else :
  102. json_str = json_str + '{ "name" : "'+word+'","value":null},\n'
  103. json_str = json_str + ']}]}'
  104. return json_str
  105. def populate_json_string(cmd_words,json_str):
  106. for i, word in enumerate(cmd_words) :
  107. # match for options excluding the last word
  108. if (( i != len(cmd_words) - 1 ) and ( not re.match("^--", word) ) and ( re.match("^-", word) )):
  109. # if the following word is not an option or a command
  110. if (( not re.match("^--", cmd_words[i+1]) ) and ( not re.match("^-", cmd_words[i+1]) )):
  111. match = '"name" : "'+word[1:]+'","value":null'
  112. replace = '"name" : "'+word[1:]+'","value":"'+cmd_words[i+1]+'"'
  113. json_str = json_str.replace(match, replace)
  114. else :
  115. match = '"name" : "'+word[1:]+'","value":null'
  116. replace = '"name" : "'+word[1:]+'","value":"void"'
  117. json_str = json_str.replace(match, replace)
  118. return json_str
  119. def str2json_cmd ( cmd_str ) :
  120. cmd_words = cmd_str.split()
  121. if cmd_words[0] == "xrnlib-cli" :
  122. # get matrix of commands options
  123. cmd = "xrnlib-cli --help | sed 's/#.*$//g' | grep xrnlib | xargs -I + sh -c \"eval + | sed -n '/help page associated/,/a valid example could be/p ' | sed '1d;$d' | cut -c 1-51 | grep '-' | tr -d ' ' | tr -s '\\n' ' ' | sed 's/$/\\n/' \""
  124. commands_and_options_str = os.popen( cmd ).read()
  125. matrix = string_to_matrix( commands_and_options_str )
  126. # get the command
  127. command = ""
  128. for word in cmd_words :
  129. if re.match("^--", word) :
  130. command = word
  131. # get the row
  132. cmd_row = []
  133. idx = 0
  134. for row in matrix :
  135. for word in row :
  136. if command == word :
  137. cmd_row = matrix[idx]
  138. idx = idx + 1
  139. # get the json string
  140. json_str = create_json_string_template("xrnlib-cli",cmd_row)
  141. json_str = populate_json_string(cmd_words,json_str)
  142. json_obj = json.loads(json_str)
  143. json_dump = json.dumps(json_obj, sort_keys=False, indent=2)
  144. return json_dump
  145. elif cmd_words[0] == "xrnconv-cli" :
  146. if (( cmd_words[1] != "--std2xrn" ) and (cmd_words[1] != "--xrn2std")) :
  147. return ""
  148. json_str = "{ \"tool\": \"" + cmd_words[0] + "\", \"configurations\": [], \"command\": [ { \"name\": \""
  149. json_str = json_str + cmd_words[1][2:] + "\", \"options\": ["
  150. option_value_content = 0 # 0 -> option 1 -> content
  151. for cmd in cmd_words[2:] :
  152. if option_value_content == 0 :
  153. json_str = json_str + "{ \"name\": \"" + cmd[1:] + "\", "
  154. option_value_content = 1
  155. elif option_value_content == 1 :
  156. json_str = json_str + " \"value\": \"" + cmd + "\" }, "
  157. option_value_content = 0
  158. json_str = json_str[:-2] + " ] } ] }"
  159. json_obj = json.loads(json_str)
  160. json_dump = json.dumps(json_obj, sort_keys=False, indent=2)
  161. return json_dump
  162. elif cmd_words[0] == "xrngen-cli" :
  163. if (( cmd_words[1] != "--text2image" ) and (cmd_words[1] != "--text2speach")) :
  164. return ""
  165. json_str = "{ \"tool\": \"" + cmd_words[0] + "\", \"configurations\": [], \"command\": [ { \"name\": \""
  166. json_str = json_str + cmd_words[1][2:] + "\", \"options\": ["
  167. option_value_content = 0 # 0 -> option 1 -> content
  168. for cmd in cmd_words[2:] :
  169. if option_value_content == 0 :
  170. json_str = json_str + "{ \"name\": \"" + cmd[1:] + "\", "
  171. if cmd != "-auto-prompt" :
  172. option_value_content = 1
  173. else :
  174. json_str = json_str + " \"value\": \"void\" }, "
  175. elif option_value_content == 1 :
  176. json_str = json_str + " \"value\": \"" + cmd + "\" }, "
  177. option_value_content = 0
  178. json_str = json_str[:-2] + " ] } ] }"
  179. json_obj = json.loads(json_str)
  180. json_dump = json.dumps(json_obj, sort_keys=False, indent=2)
  181. return json_dump
  182. def json_cmd2str ( json_cmd ) :
  183. # reformat json string
  184. json_obj = json.loads(json_cmd)
  185. json_cmd = json.dumps(json_obj, sort_keys=False, indent=2)
  186. json_str = json_cmd.replace("\n"," ")
  187. json_str = re.sub(' +', ' ', json_str)
  188. # divide string in three parts
  189. tool_sub_str, reminder_str = json_str.split('"configurations"')
  190. configuration_sub_str, reminder_str = reminder_str.split( '"command"')
  191. command_sub_str = reminder_str
  192. # get tool name
  193. tool_str = re.sub('^.*:','',tool_sub_str).replace('"','').replace(',','').replace(' ','')
  194. cmd_str = tool_str + ' '
  195. # get configurations
  196. if tool_str == "xrnlib-cli" :
  197. configuration_sub_str = configuration_sub_str.split("} ] },")
  198. for configuration in configuration_sub_str:
  199. first_option = 0
  200. # separate name from options
  201. configuration_name_tmp , options_tmp = configuration.split('"options"')
  202. # get configuration name
  203. configuration_name = ('--' + re.sub('^.*:','',configuration_name_tmp).replace('"','').replace(',','')).replace(' ','')
  204. options_split = options_tmp.split("},")
  205. for option in options_split :
  206. if "null" not in option :
  207. if "void" in option :
  208. if ( first_option == 0 ) :
  209. cmd_str = cmd_str + configuration_name + ' '
  210. first_option = 1
  211. option_name_tmp = option.split(',')[0]
  212. option_name = '-'+re.sub('^.*:','',option_name_tmp).replace('"','').replace(',','').replace(' ','')
  213. cmd_str = cmd_str + option_name + ' '
  214. else :
  215. if ( first_option == 0 ) :
  216. cmd_str = cmd_str + configuration_name + ' '
  217. first_option = 1
  218. option_name_tmp, option_value_tmp = option.split(',')
  219. option_name = '-'+re.sub('^.*:','',option_name_tmp).replace('"','').replace(',','').replace(' ','')
  220. cmd_str = cmd_str + option_name + ' '
  221. option_value = re.sub('^.*:','',option_value_tmp).replace('"','').replace(',','').replace(' ','')
  222. cmd_str = cmd_str + option_value + ' '
  223. command_name_tmp, command_options_tmp = command_sub_str.split('", "options":')
  224. command_name = " --" + re.sub('^.*:','',command_name_tmp).replace('"','').replace(',','').replace(' ','')
  225. cmd_str = cmd_str + command_name
  226. options_tmp = command_options_tmp.split('}, {')
  227. for option_tmp in options_tmp :
  228. name_tmp, value_tmp = option_tmp.split(',')
  229. name_str = " -" + re.sub('^.*:','',name_tmp).replace('"','').replace(',','').replace(' ','').replace('[','').replace('}','').replace(']','')
  230. value_str = " " + re.sub('^.*:','',value_tmp).replace('"','').replace(',','').replace(' ','').replace('[','').replace('}','').replace(']','')
  231. if ( value_str != 'null' ):
  232. cmd_str = cmd_str + name_str + value_str
  233. return cmd_str
  234. ################
  235. # Parser lexer #
  236. ################
  237. tool_name_str = "xrntranslate-cli"
  238. json2cmd_str = "--json2cmd"
  239. cmd2json_str = "--cmd2json"
  240. jsoncmd_str = "-json"
  241. def print_help():
  242. print("\nhelp page for the {} command\n".format(tool_name_str))
  243. print("to create a json file from a xrnlib-cli, xrnconv-cli or xrngen-cli command")
  244. print("{} {} {} file.json xrnlib-cli .... ".format(tool_name_str,cmd2json_str, jsoncmd_str))
  245. print("{} {} {} file.json xrnconv-cli .... ".format(tool_name_str,cmd2json_str, jsoncmd_str))
  246. print("{} {} {} file.json xrngen-cli .... \n".format(tool_name_str,cmd2json_str, jsoncmd_str))
  247. print("to create a string command to standard output from a json file")
  248. print("{} {} {} file.json \n".format(tool_name_str, json2cmd_str, jsoncmd_str ))
  249. if ( len(sys.argv) < 4 ):
  250. print("the first argument should be either {} or {}".format(cmd2json_str, json2cmd_str ))
  251. print("the second argument should be {}".format( jsoncmd_str ))
  252. print("the third argument should be a json file")
  253. print_help()
  254. exit(-1)
  255. if (( sys.argv[1] != cmd2json_str ) and ( sys.argv[1] != cmd2json_str ) and ( sys.argv[2] != jsoncmd_str ) ):
  256. print("the first argument should be either {} or {}".format(cmd2json_str, json2cmd_str ))
  257. print("the second argument should be {}".format( jsoncmd_str ))
  258. print("the third argument should be a json file")
  259. print_help()
  260. exit(-1)
  261. if ( sys.argv[1] == cmd2json_str ) :
  262. # Get all the command line arguments except the script name
  263. arguments = sys.argv[4:]
  264. # Concatenate them into a single string
  265. command_string = ' '.join(arguments)
  266. # Create dump
  267. json_dump = str2json_cmd ( command_string )
  268. # Write the concatenated string to the specified file
  269. with open(sys.argv[3], 'w') as file:
  270. file.write(json_dump)
  271. elif ( sys.argv[1] == json2cmd_str ) :
  272. # Open the file in read mode
  273. with open(sys.argv[3], 'r') as file:
  274. # Read the entire file content into a string
  275. json_dump = file.read()
  276. command_string = json_cmd2str ( json_dump )
  277. print ( command_string )