/
scratch2python.py
212 lines (165 loc) · 5.84 KB
/
scratch2python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Raul Perula-Martinez"
__copyright__ = "JdeRobot project"
__credits__ = ["Raul Perula-Martinez"]
__license__ = "GPL v3"
__version__ = "0.0.0"
__maintainer__ = "Raul Perula-Martinez"
__email__ = "raules@gmail.com"
__status__ = "Development"
import kurt
import os
import sys
from difflib import SequenceMatcher
from parse import parse, compile
from termcolor import cprint
GENERAL = [
['end', ''],
['forever', 'while True:'],
['if {} then', 'if {l[0]}:'],
['else', 'else:'],
['repeat {}', 'for i in range({l[0]}):'],
['say {}', 'print({l[0]})'],
['set {} to {}', '{l[0]} = {l[1]}'],
['wait {} secs', 'time.sleep({l[0]})'],
['length of {}', 'len({l[0]})'],
['insert {} at {} of {}', '{l[2]}.insert({l[1]}, {l[0]})'],
['item {} of {}', '{l[1]}[{l[0]}]'],
['add {} to {}', '{l[1]}.append({l[0]})'],
['delete {} of {}', '{l[1]}.pop({l[0]})'],
]
ROBOTICS = [
['move robot {}', 'robot.move("{l[0]}")'],
['move drone {}', 'robot.move("{l[0]}")'],
['move robot {} speed {}', 'robot.move("{l[0]}", {l[1]})'],
['stop robot-drone', 'robot.stop()'],
['turn robot-drone {}', 'robot.turn("{l[0]}")'],
['turn robot {} speed {}', 'robot.turn("{l[0]}", {l[1]})'],
['take off drone', 'robot.take_off()'],
['land drone', 'robot.land()'],
['frontal laser distance', 'robot.get_laser_distance()'],
]
def is_conditional(sentence):
"""
Returns if a sentence is conditional or not.
@param sentence: The sentence to check.
@return: True if it has a conditional, False otherwise.
"""
if "if" in sentence:
return True
return False
def similar(a, b):
"""
Returns the ratio value comparing two sentences.
@param a: First sentence.
@param b: Second sentence.
@return: The ratio of the similarity.
"""
return SequenceMatcher(None, a, b).ratio()
def sentence_mapping(sentence, threshold=0.0):
"""
Maps a sentence and returns the original and the mapped.
@param sentence: The sentence to map.
@return: The original sentence and the mapped sentence.
"""
found = False
options = []
original = None
translation = None
# first look for general blocks
for elem in GENERAL:
if elem[0][:3] == sentence.replace(' ', '').replace('(', '')[:3]:
options.append(elem)
found = True
# then look for robotics blocks
if not found:
for elem in ROBOTICS:
if elem[0][:3] == sentence.replace(' ', '').replace('(', '')[:3]:
options.append(elem)
found = True
if found:
# select the option that better fits
l = [(m[0], m[1], similar(sentence, m[0])) for m in options]
original, translation, score = max(l, key=lambda item: item[2])
if score < threshold:
return None, None
# clean sentence
s = sentence.replace(' ', '').replace('(', '').replace(')', '')
# extract arguments
p = compile(original)
args = p.parse(s)
if args:
args_aux = list(args)
# look for more blocks
for idx in range(len(args_aux)):
new_ori, new_trans = sentence_mapping(args_aux[idx], 0.7)
if new_trans != None:
args_aux[idx] = new_trans
#~print translation
#~print args_aux
translation = translation.format(l=args_aux)
return original, translation
if __name__ == "__main__":
# get current working directory
path = os.getcwd()
open_path = path[:path.rfind('scripts')] + 'data/'
save_path = path[:path.rfind('scripts')] + 'src/scratch2jderobot/'
if len(sys.argv) == 2:
# template creation
template = "\
#!/usr/bin/env python\n\
# -*- coding: utf-8 -*-\n\n\
import time\n\n\
def execute(robot):\n\
\ttry:\n\
\t%s\
except KeyboardInterrupt:\n\
\t\traise\n\
"
# load the scratch project
p = kurt.Project.load(open_path + sys.argv[1])
# show the blocks included
for scriptable in p.sprites + [p.stage]:
for script in scriptable.scripts:
# exclude definition scripts
if "define" not in script.blocks[0].stringify():
s = script
print("\nStringify:")
print("-------------------")
sentences = []
for b in s.blocks:
cprint(b.stringify(), 'blue')
sentences += b.stringify().split('\n')
print("-------------------\n")
tab_seq = "\t"
python_program = ""
for s in sentences:
# count number of tabs
num_tabs = s.replace(' ', tab_seq).count(tab_seq)
python_program += tab_seq * (num_tabs + 1)
# pre-processing if there is a condition (operators and types)
if is_conditional(s):
s = s.replace("'", "").replace("=", "==")
# mapping
original, translation = sentence_mapping(s)
# set the code
if translation != None:
python_program += translation
else:
cprint("[WARN] Block <%s> not included yet" % s, 'yellow')
python_program += "\n" + tab_seq
# join the template with the code and replace the tabs
file_text = template % python_program
file_text = file_text.replace(tab_seq, ' ' * 4)
print("\nGenerated code")
print("-------------------")
cprint(file_text, 'green')
print("-------------------\n")
# save the code in a python file
f = open(save_path + "scratch.py", "w")
f.write(file_text)
f.close()
else:
print(
"ERROR: Number of parameters incorrect. Example:\n\tpython scratch2python.py hello_world.sb2")