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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import json 
import re
import sys,os 
# sys.path.append(os.path.join(os.path.dirname(__file__), '../'))


def splitJSONfromTXT(txt:str=""):
    jsons=re.findall(r"```json([\s\S]*)```",txt)
    if len(jsons)==0:
        jsons=re.findall(r"```JSON([\s\S]*)```",txt)
    if len(jsons)==0:
        jsons+=re.findall(r"```([\s\S]*)```",txt)
    if len(jsons)==0:
        jsons+=re.findall(r"({[\s\S]*})",txt)
    # print(re.findall(r"```json([\s\S]+?)```",txt))
    print('find {} JSON para\n'.format(len(jsons)))
    
    for i in range(len(jsons)):
        # jsons[i]=jsons[i].replace(" ","")
        # # 不能这样,会全部都没有空格
        jsons[i]=jsons[i].replace("  ","")
        jsons[i]=jsons[i].replace("\t","")
        # jsons[i]=jsons[i].replace('_','')
        # jsons[i]=jsons[i].replace('.','')
        # 这是为了消除回车后的制表符
        while(jsons[i][0]==" "):
            jsons[i]=jsons[i][1:]
        while(jsons[i][-1]==" "):
            jsons[i]=jsons[i][:-1]
        jsons[i]=jsons[i].replace("\n","")
        left_brace=jsons[i].count('{')
        right_brace=jsons[i].count('}')
        
        if right_brace<left_brace:
            for i in range(left_brace-right_brace):
                jsons[i]+='}'
        if right_brace>left_brace:
            for i in range(right_brace-left_brace):
                jsons[i]=jsons[i][1:]
        # print('jsons[i][0]',jsons[i][0])
        if jsons[i][0]!='{':
            jsons[i]='{'+jsons[0]
            jsons[i]+='}'
        # print(jsons[i])
        # id0=0
        # for id0 in range(len(jsons[i])):
        #     if jsons[i][id0]=='"':
        #         print("**no more curly brace in return\n**")
        #         break 
        #     elif jsons[i][id0]=='{':
        #         jsons[i]=jsons[i][id0+1:]
        #         id=len(jsons[i])
        #         for id in range(len(jsons[i])-1,0,-1): 
        #             if jsons[i][id]=='}':
        #                 break
        #         jsons[i]=jsons[i][:id]
        #         print("**delete extra curly brace in return\n**")
        #         break 
        # id=len(jsons[i])
        # for id in range(len(jsons[i])-1,0,-1): 
        #     if jsons[i][id]=='}':
        #         jsons[i]=jsons[i][:id+1]
        #         print("**delete extra right curly brace in return\n**")
        #         break
        # print("[]",j,"[]")
    # print("splitJSONfromTXT",jsons)
    # print(jsons[0])
    # print(json.loads(jsons[0]))
    return jsons
    pass 
def readMultipleLinesTillException(prompt:str="",log=False,exp_PATH=""):
    # the last line would not be read in 
    print("--"*15)
    lines=[" "]
    try:
        lines.append(input(prompt))
        while True:
            lines.append(input())
    except:
        pass
    ret ="".join(lines)
    if log:
        with open(exp_PATH+'log.txt','a') as f:    #设置文件对象
            f.write("\nINPUT:\n")
            f.write(prompt)                 #将字符串写入文件中
            f.write("\nOUTPUT:\n")
            f.write(ret)
    return ret
# class GPTinterface
# def GPTinterface(prompts:list,log=False,exp_PATH=""):

#     pass 

# # def
# class GPTTranslater():
#     def __init__(self) -> None:
#         pass
#     def translate(self,prompt:str="",log=False,exp_PATH=""):
#         return GPTinterface(prompt=prompt,log=log,exp_PATH=exp_PATH)
    

import re 
class Task2Preplacer():
    def __init__(self,input:str=""):
        # self.input=input
        self.Task2PDict={}
        self.P2TaskDict={}
        self.count=0
        pass 
    def mapping1(self,name):
        name=name[0]
        while not (name[-1]<='9' and name[-1]>='0'):
            name=name[:-1]
        if not (name in self.Task2PDict):
            self.count+=1
            self.Task2PDict[name]="P{:0>2d}".format(self.count)
            self.P2TaskDict["P{:0>2d}".format(self.count)]=name
        # print('141',self.Task2PDict,self.P2TaskDict)
        return self.Task2PDict[name]
        pass 
    def mapping2(self,name):
        name=name[0]
        return "{}".format(self.P2TaskDict[name])
        pass 
    def reTask2P(self,Taskinput:str=""):
        self.Task2PDict={}
        self.P2TaskDict={}
        self.count=0
        self.Poutput=re.sub("Task[_0-9\.]+",self.mapping1,Taskinput)
        print('self.Poutput',self.Poutput,'\n')
        return self.Poutput
    def reP2Task(self,Pinput:str=""):
        print("self.P2TaskDict",self.P2TaskDict,'\n')
        print("pinput",Pinput,'\n')

        self.Taskoutput=re.sub("P[0-9]{2}",self.mapping2,Pinput)
        return self.Taskoutput

class Func2Preplacer():
    def __init__(self,functionlist,input:str=""):
        # self.input=input
        self.functionlist=functionlist
        self.Func2Tasklist=[]
        pass 
    def reFunc2P(self,Taskinput:str=""):
        def mapping(name):
            name=name[0]
            if not name in self.Task2Plist:
                self.Task2Plist+=[name]
            return "P{:0>2d}".format(self.Task2Plist.index(name))
            pass 
        for i,func in enumerate(self.functionlist):
            Taskinput=re.sub(func[0][:-2]+"\([\S]+]\)",mapping,Taskinput)
            # Taskinput=re.sub(func[0][:-2]+"\([\s\S]+]\)",mapping,Taskinput) 
            # may be this is the proper one
        self.Poutput=Taskinput
        return self.Poutput
    def reP2Func(self,Pinput:str=""):
        def mapping(name):
            name=name[0]
            return "{}".format(self.Task2Plist[int(name[1:])])
            pass 
        self.Taskoutput=re.sub("P[0-9]{2}",mapping,Pinput)
        return self.Taskoutput
    
class getFunc2HierarchicalAP():
    def __init__(self,functionlist,input:str=""):
        # self.input=input
        self.functionlist=functionlist
        self.HierarchicalEleList=dict()
        # a dict to save the AP function and AP name 
        # a dict to save the CP Task and CP name 
        self.CP_count=0
        self.CP_start=100
        self.AP_count=0
        self.AP_start=10
    def AsciiLTL2FormalLTL(self,LTLInput:str,task:str,LTLtype:str="CP"):
        # LTLtype=CP/AP means the element in the LTL 
        if LTLtype in ["CP","cp"]:
            return self.reTask2HierarchicalLTL(LTLInput)
            pass 
        elif LTLtype in ["ap","AP"]:
            return self.reFunc2HierarchicalLTL(LTLInput)
        elif LTLtype in ["sp","SP"]:
            self.reTask2HierarchicalLTL(task)
            return LTLInput
            pass
        pass 
    def mapAP2Function(self,AP:int):
        # AP is the int number of the task 
        if AP in self.HierarchicalEleList:
            return self.HierarchicalEleList[AP]
        else:
            return False
    def mapTask2CP(self,TaskName:str):
        return "p{:0>3d}".format(self.HierarchicalEleList[TaskName])
    def mapping1(self,name):
        name=name[0]
        # print('name ',name, name in self.HierarchicalEleList)
        print('mapping',name)
        if not (name in self.HierarchicalEleList):
            self.AP_count+=1
            self.HierarchicalEleList[self.AP_count+self.AP_start]=name
            self.HierarchicalEleList[name]=self.AP_count+self.AP_start
        return "p{:0>2d}".format(self.HierarchicalEleList[name])
        pass 

    def reFunc2HierarchicalLTL(self,Taskinput:str=""):
        for i,func in enumerate(self.functionlist):
            # print('taskinput ',Taskinput)
            # Taskinput=re.sub(func[0][:-2]+"\([\S]+]\)",mapping,Taskinput)
            Taskinput=re.sub(func[0][:-2]+"\([^\)]+\)",self.mapping1,Taskinput)
        self.Poutput=Taskinput
        return self.Poutput
    # def reTask2Func(self,Pinput:str=""):
    #     def mapping(name):
    #         return "{}".format(self.Task2Plist[int(name[1:])])
    #         pass 
    #     self.Taskoutput=re.sub("P[0-9]{2}",mapping,Pinput)
    #     return self.Taskoutput
    def mapping2(self,name):
        name=name[0]
        while not (name[-1]<='9' and name[-1]>='0'):
            name=name[:-1]
        print('mapping2',name)

        if not name in self.HierarchicalEleList:
            self.CP_count+=1
            self.HierarchicalEleList[self.CP_count+self.CP_start]=name
            self.HierarchicalEleList[name]=self.CP_count+self.CP_start
        return "p{:0>3d}".format(self.HierarchicalEleList[name])
        pass 
    def reTask2HierarchicalLTL(self,Taskinput:str=""):

        self.Poutput=re.sub("Task_[0-9\.]+",self.mapping2,Taskinput)
        return self.Poutput
    # def reP2Task(self,Pinput:str=""):
    #     print("self.Task2Plist",self.Task2Plist,'\n')
    #     print("pinput",Pinput,'\n')
    #     def mapping(name):
    #         return "{}".format(self.Task2Plist[int(name[1:])])
    #         pass 
    #     self.Taskoutput=re.sub("P[0-9]{2}",mapping,Pinput)
    #     return self.Taskoutput

# Task_1.1 and Task_1.2 can occur independently and either may be executed without affecting the other."
class FuncParamExtractor():
    def __init__(self,functionDefine) -> None:
        self.functionlist=functionDefine
        self.ParamPattern=re.compile("[\(,]([^,\)]+)")
        pass
    def extractParam(self,inputFunc:str=''):
        return self.ParamPattern.findall(inputFunc)
    def extractFunc(self,inputFunc:str=''):
        for i,func in enumerate(self.functionlist):
            Taskinput=re.search(func[0][:-2],inputFunc)
            if Taskinput:
                break
            # Taskinput=re.sub(func[0][:-2]+"\([\S]+]\)",mapping,Taskinput)
            # Taskinput=re.sub(func[0][:-2]+"\([\s\S]+]\)",mapping,Taskinput) 
            # may be this is the proper one
        return Taskinput.group()
class LTLChecker():
    def __init__(self,APpattern=re.compile("(P[0-9]{2})")) -> None:
        self.APpattern=APpattern
    def AP_CorrCheck(self,natural:str="",ltl:str=""):
        natural_AP=self.APpattern.findall(natural)
        ltl_AP=self.APpattern.findall(ltl)
        # natural_AP.sort()
        # ltl_AP.sort()
        return set(natural_AP)==set(ltl_AP)
    def right_barkets_remover(self,ltl:str):
        ltl=ltl.strip()
        while ltl.count("(")<ltl.count(")"):
            if ltl[-1]==')':
                ltl=ltl[:-1].strip()
            else:
                break
        return ltl
    def brackets_Check(self,ltl:str):
        return ltl.count("(")==ltl.count(")")
    
def reAsciiLTL2EngLTL(AsciiInput:str=''):
    # I > means ->
    # E ^ means <>
    # A means and
    # N means ! ~
    # O means |
    AsciiInput=re.sub('A', 'And', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('O', 'Or', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('I', 'Imply', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('N', 'Not', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('E', 'Equally', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('F', 'Finally', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('G', 'Globally', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('U', 'Until', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('X', 'Next', AsciiInput, count=0, flags=0)
    return AsciiInput
def reEngLTL2FormalLTL(ENGInput:str=''):
    if not isinstance(ENGInput,str):
        return ENGInput
    ENGInput=re.sub('And','&&', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Or','||', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Imply','->', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Not','!', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Equally','<=>', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Finally','<>', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Globally','[]', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Until','U', ENGInput, count=0, flags=0)
    ENGInput=re.sub('Next','X', ENGInput, count=0, flags=0)
    return ENGInput
def reAsciiLTL2FormalLTL(AsciiInput:str=''):
    AsciiInput=re.sub('A','&&', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('O','||', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('I','->', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('N','!', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('E','<=>', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('F','<>', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('G','[]', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('U','U', AsciiInput, count=0, flags=0)
    AsciiInput=re.sub('X','X', AsciiInput, count=0, flags=0)
    return AsciiInput
if __name__=="__main__":
    # print(getFunc2HierarchicalAP([
    # ["Move_raw_ingredient_to_utensile()","name of ingredient", "name of utensil"],
    # ["Move_utensil_to_certain_area()","name of utensil", "area"],
    # ["Move_processed_ingredient_to_utensile()","name of ingredient", "name of utensil"],
    # ["Processing_ingredient()","name of ingredient", "blue_knife/yellow_knife/hand"],
    # ]).reFunc2HierarchicalLTL('Move_raw_ingredient_to_utensile(asd,asd)'))
    # # print(FuncParamExtractor().extractFunc('Processing_ingredient(123,243,dfsa,3,)'))
    # exit()
    print(splitJSONfromTXT("""```json
{
   "Task_1":{
      "task_id":"Task_1",
      "task_instruction":"Prepare dishes by arranging fruit and vegetables and preparing eggs and meats.",
      "task_relied_description":"We have several dishes to create, and there's a specific order for preparation.",
      "sibling_nodes_condition":"",
      "subtasks_of_this_node":["Task_1.1", "Task_1.2"]
   },
   "Task_1.1":{
      "task_id":"Task_1.1",
      "task_instruction":"Arrange fruit on the yellow plate then place vegetables on the blue plate.",
      "task_relied_description":"Start by arranging the fruit on the yellow plate, followed by the vegetables on the blue plate.",
      "sibling_nodes_condition":"",
      "subtasks_of_this_node":["Task_1.1.1", "Task_1.1.2"]
   },
   "Task_1.1.1":{
      "task_id":"Task_1.1.1",
      "task_instruction":"Put half of the sliced tomato and the sliced watermelon on the yellow plate.",
      "task_relied_description":"We have a tomato and a watermelon to serve as fruit.",
      "sibling_nodes_condition":"",
      "subtasks_of_this_node":["Task_1.1.1.1", "Task_1.1.1.2"]
   },
   "Task_1.1.1.1":{
      "task_id":"Task_1.1.1.1",
      "task_instruction":"Place tomato and watermelon on the yellow cutting board and slice each in half.",
      "task_relied_description":"These can go on the yellow cutting board in any sequence. Slice each in half.",
      "sibling_nodes_condition":"",
      "subtasks_of_this_node":[]
   },
   "Task_1.1.1.2":{
      "task_id":"Task_1.1.1.2",
      "task_instruction":"Move one half of the tomato and the watermelon to the yellow plate.",
      "task_relied_description":"then transfer one half of the tomato and the halved watermelon to the yellow plate.",
      "sibling_nodes_condition":"After slicing the fruits",
      "subtasks_of_this_node":[]
   },
   "Task_1.1.2":{
      "task_id":"Task_1.1.2",
      "task_instruction":"Place vegetables on the blue plate, including dividing and placing the broccoli and separating egg yolk.",
      "task_relied_description":"For the vegetables, initially place the ingredients on the cutting board for slicing before transferring them to a plate.",
      "sibling_nodes_condition":"After placing the fruits on the yellow plate",
      "subtasks_of_this_node":["Task_1.1.2.1", "Task_1.1.2.2"]
   },
   "Task_1.1.2.1":{
      "task_id":"Task_1.1.2.1",
      "task_instruction":"Place broccoli on blue cutting board, divide it into two pieces, and then move both pieces to the blue plate.",
      "task_relied_description":"For the broccoli, lay it on the blue cutting board and divide it into two pieces. Afterwards, move both pieces to the blue plate.",
      "sibling_nodes_condition":"",
      "subtasks_of_this_node":[]
   },
   "Task_1.1.2.2":{
      "task_id":"Task_1.1.2.2",
      "task_instruction":"Take an egg, remove its shell, separate the yolk from the egg and put it directly into the blue plate.",
      "task_relied_description":"When it comes to the egg yolk, first take an egg but don't place it on the cutting board, Directly separate the yolk into the blue plate after removing the shell.",
      "sibling_nodes_condition":"After placing the broccoli",
      "subtasks_of_this_node":[]
   },
   "Task_1.2":{
      "task_id":"Task_1.2",
      "task_instruction":"Prepare the eggs and meats.",
      "task_relied_description":"eggs and meats should be prepped last.",
      "sibling_nodes_condition":"After arranging the fruits and vegetables",
      "subtasks_of_this_node":[]
   }
}
```"""))
    print(reAsciiLTL2EngLTL("F ( P11 A ( F P04 ) )"))
    print(splitJSONfromTXT("""
     {
   "Task_1": {
      "task_id": "Task_1",
      "task_instruction": "Prepare and cut banana, apple, onion and pepper. Follow rule: Do not cut fruits on a cutting board that has been used for cutting vegetables.",
      "sibling_nodes_condition": "NA",
      "subtasks_of_this_node":["Task_1.1", "Task_1.2", "Task_1.3"]
   },
   "Task_1.1": {
      "task_id": "Task_1.1",
      "task_instruction": "Prepare and cut banana and apple. Do not use a cutting board that has been used for cutting vegetables.",
      "sibling_nodes_condition": "NA",
      "subtasks_of_this_node":["Task_1.1.1", "Task_1.1.2"]
   },
   "Task_1.1.1": {
      "task_id": "Task_1.1.1",
      "task_instruction": "Prepare and cut banana",
      "sibling_nodes_condition": "NA",
      "subtasks_of_this_node": []
   },
   "Task_1.1.2": {
      "task_id": "Task_1.1.2",
      "task_instruction": "Prepare and cut apple",
      "sibling_nodes_condition": "After preparing and cutting banana",
      "subtasks_of_this_node": []
   },
   "Task_1.2": {
      "task_id": "Task_1.2",
      "task_instruction": "Prepare and cut onion and pepper",
      "sibling_nodes_condition": "Do not use the same cutting board as used for fruits",
      "subtasks_of_this_node": ["Task_1.2.1", "Task_1.2.2"]
   },
   "Task_1.2.1": {
      "task_id": "Task_1.2.1",
      "task_instruction": "Prepare and cut onion",
      "sibling_nodes_condition": "NA",
      "subtasks_of_this_node": []
   },
   "Task_1.2.2": {
      "task_id": "Task_1.2.2",
      "task_instruction": "Prepare and cut pepper",
      "sibling_nodes_condition": "After preparing and cutting onion",
      "subtasks_of_this_node": []
   },
   "Task_1.3": {
      "task_id": "Task_1.3",
      "task_instruction": "Rule: Do not cut fruits on a cutting board that has been used for cutting vegetables.",
      "sibling_nodes_condition": "NA",
      "subtasks_of_this_node": []
   }}"""))