Hopefully made this python3 compatible.. Need exhaustive tessting.

This commit is contained in:
Michael Taboada 2024-08-06 09:41:40 -07:00
parent a6f29857c3
commit 7de3708efa
5 changed files with 49 additions and 48 deletions

View File

@ -1,4 +1,4 @@
from io import StringIO from io import BytesIO
import io import io
import base64 import base64
import colorsys import colorsys
@ -43,7 +43,7 @@ def image_to_binary(image, crush=False):
if output == 1: if output == 1:
print("failed to crush") print("failed to crush")
s=bson.binary.Binary(open(outfile).read()) s=bson.binary.Binary(open(outfile).read())
print(time.time()-t_time) print((time.time()-t_time))
return s return s
else: else:
output = StringIO.StringIO() output = StringIO.StringIO()
@ -69,7 +69,7 @@ def load_image(image_data):
image = Image.open(io.BytesIO(byte_data)) image = Image.open(io.BytesIO(byte_data))
except: except:
byte_data = image_data byte_data = image_data
image = Image.open(io.BytesIO(byte_data)) image = Image.open(io.BytesIO(base64.b64decode(byte_data, validate=True)))
image = image.convert("RGBA") image = image.convert("RGBA")
return image return image
@ -87,9 +87,9 @@ def image_to_bmp_string(img):
return base64.b64encode(string) return base64.b64encode(string)
def image_to_string_format(img,format_type, conv="RGB"): def image_to_string_format(img,format_type, conv="RGB"):
output = StringIO.StringIO() output = BytesIO()
img.convert(conv).save(output, format=format_type) img.convert(conv).save(output, format=format_type)
string = output.getvalue() string = output.getbuffer()
return base64.b64encode(string) return base64.b64encode(string)
def color_byte_to_hex(byte_color): def color_byte_to_hex(byte_color):
@ -147,7 +147,7 @@ def rectify_sub(image):
# _ # _
# | # |
curr_pixel = BLACK curr_pixel = BLACK
for i in reversed(range(w)): for i in reversed(list(range(w))):
if i == w-1: if i == w-1:
continue continue
for j in range(h): for j in range(h):
@ -164,7 +164,7 @@ def rectify_sub(image):
# #
# |_ # |_
curr_pixel = BLACK curr_pixel = BLACK
for j in reversed(range(h)): for j in reversed(list(range(h))):
if j == h-1: if j == h-1:
continue continue
for i in range(w): for i in range(w):
@ -181,10 +181,10 @@ def rectify_sub(image):
# #
# #
curr_pixel = BLACK curr_pixel = BLACK
for j in reversed(range(h)): for j in reversed(list(range(h))):
if j == h-1: if j == h-1:
continue continue
for i in reversed(range(w)): for i in reversed(list(range(w))):
last_pixel = curr_pixel last_pixel = curr_pixel
curr_pixel = image.getpixel((i,j)) curr_pixel = image.getpixel((i,j))
@ -258,7 +258,7 @@ def segfill(image, mark_color, target_color):
last_red = False last_red = False
for entry in new_h_range.keys(): for entry in list(new_h_range.keys()):
if entry > 0: if entry > 0:
new_h_range[entry-1] = 1 new_h_range[entry-1] = 1
new_h_range = sorted(new_h_range.keys()) new_h_range = sorted(new_h_range.keys())
@ -348,7 +348,7 @@ def floodfill2(image, center, bg_color):
last_marked = [[0,i] for i in range(h)]#center] last_marked = [[0,i] for i in range(h)]#center]
last_marked2 = list() last_marked2 = list()
rounds = 0 rounds = 0
print(time.time()-t) print((time.time()-t))
a = 0 a = 0
b = 0 b = 0
while last_marked: while last_marked:
@ -367,10 +367,10 @@ def floodfill2(image, center, bg_color):
########## ##########
#print([chr(x) for x in bytes_array]) #print([chr(x) for x in bytes_array])
print(time.time()-t) print((time.time()-t))
print([a,b]) print([a,b])
image_out = Image.frombytes(mode, (w,h),"".join([chr(x) for x in bytes_array])) image_out = Image.frombytes(mode, (w,h),"".join([chr(x) for x in bytes_array]))
print(time.time()-t) print((time.time()-t))
image_out.show() image_out.show()
@ -472,7 +472,7 @@ def reduce_to_multi_color(img, bg, colors_map, threshold):
else: else:
tc, tc_map = entry, entry tc, tc_map = entry, entry
if isinstance(tc, basestring): if isinstance(tc, str):
tc = color_hex_to_byte(tc) tc = color_hex_to_byte(tc)
rr = r-tc[0] rr = r-tc[0]
@ -601,7 +601,7 @@ def fix_bounding_box(img, bounding_box):
w = img.width w = img.width
h = img.height h = img.height
for key in bounding_box: for key in bounding_box:
if isinstance(bounding_box[key], basestring): if isinstance(bounding_box[key], str):
bounding_box[key] = int(bounding_box[key]) bounding_box[key] = int(bounding_box[key])
if 'w' in bounding_box: if 'w' in bounding_box:
if bounding_box['x'] < 0: if bounding_box['x'] < 0:
@ -718,7 +718,7 @@ def tint_image(image, color, border=2):
def black_expand(image, mark_color, target_colors): def black_expand(image, mark_color, target_colors):
w = image.width w = image.width
h = image.height h = image.height
if isinstance(target_colors, basestring): if isinstance(target_colors, str):
target_colors = [target_colors] target_colors = [target_colors]
mark_color = tuple(color_hex_to_byte(mark_color)[0:3]) mark_color = tuple(color_hex_to_byte(mark_color)[0:3])
@ -755,7 +755,7 @@ def black_expand(image, mark_color, target_colors):
if j < h-1 and image.getpixel((i, j+1)) in target_colors: if j < h-1 and image.getpixel((i, j+1)) in target_colors:
image.putpixel((i,j+1), mark_color) image.putpixel((i,j+1), mark_color)
break break
print("Black expand took: "+str(time.time()-t_time)) print(("Black expand took: "+str(time.time()-t_time)))
return image return image
def expand_vertical(img, bg_color, target_color): def expand_vertical(img, bg_color, target_color):
@ -800,7 +800,7 @@ def expand_vertical(img, bg_color, target_color):
upset[j] = 1 upset[j] = 1
for key in upset: for key in upset:
image.putpixel((i, key), target) image.putpixel((i, key), target)
print("vert expand ", time.time()-t_time) print(("vert expand ", time.time()-t_time))
return image return image
def expand_horizontal(img, bg_color, target_color): def expand_horizontal(img, bg_color, target_color):
@ -848,7 +848,7 @@ def expand_horizontal(img, bg_color, target_color):
upset[i] = 1 upset[i] = 1
for key in upset: for key in upset:
image.putpixel((key, j), target) image.putpixel((key, j), target)
print("horizontal expand ", time.time()-t_time) print(("horizontal expand ", time.time()-t_time))
return image return image

Binary file not shown.

48
test.py
View File

@ -502,7 +502,7 @@ def main():
plud = {"person_box": person_box, plud = {"person_box": person_box,
"person_dict": {}} "person_dict": {}}
for i, key in enumerate(person_tiles): for i, key in enumerate(person_tiles):
print("p", i,key) print(("p", i,key))
if pmap[i] >= 0: if pmap[i] >= 0:
cropped_pic = person_dict[key] cropped_pic = person_dict[key]
plud['person_dict'][cropped_pic] = { plud['person_dict'][cropped_pic] = {
@ -513,7 +513,7 @@ def main():
} }
for i, key in enumerate(fail_person_tiles): for i, key in enumerate(fail_person_tiles):
print("pp", i,key) print(("pp", i,key))
if pmapf[i] >= 0: if pmapf[i] >= 0:
cropped_pic = fail_person_dict[key] cropped_pic = fail_person_dict[key]
plud['person_dict'][cropped_pic] = { plud['person_dict'][cropped_pic] = {
@ -537,7 +537,7 @@ def main():
t = time.time() t = time.time()
k, map_data = ParseScreenObstructions.parse_screen(im, tile_info, lud, k, map_data = ParseScreenObstructions.parse_screen(im, tile_info, lud,
plud, partial_center=True) plud, partial_center=True)
print(time.time()-t) print((time.time()-t))
import pdb import pdb
pdb.set_trace() pdb.set_trace()
@ -608,7 +608,7 @@ class PathFinder:
path.append((py,px, vy,vx)) path.append((py,px, vy,vx))
py-=vy py-=vy
px-=vx px-=vx
print("path", path[-1]) print(("path", path[-1]))
path = path[::-1] path = path[::-1]
return path return path
@ -669,8 +669,8 @@ class PackageOutput:
spec = " ".join(sp[:i]) spec = " ".join(sp[:i])
break break
if spec not in " ".join(mem): if spec not in " ".join(mem):
print("spec", spec) print(("spec", spec))
print(" ".join(mem).split()) print((" ".join(mem).split()))
specials[spec] = 1 specials[spec] = 1
else: else:
sp = entry.split(" ") sp = entry.split(" ")
@ -684,7 +684,7 @@ class PackageOutput:
if not output: if not output:
output.append("None") output.append("None")
if specials: if specials:
print("____++", mem) print(("____++", mem))
output.append("special,") output.append("special,")
for key in specials: for key in specials:
output.append(key+",") output.append(key+",")
@ -803,7 +803,7 @@ class PackageOutput:
if state_dict.get("paused") == 1: if state_dict.get("paused") == 1:
if self.pause_mode['active'] is True: if self.pause_mode['active'] is True:
output = list() output = list()
print(self.pause_mode) print((self.pause_mode))
if self.pause_mode['active'] is False and clicked.get('start'): if self.pause_mode['active'] is False and clicked.get('start'):
self.pause_mode['active'] = True self.pause_mode['active'] = True
self.pause_mode['goal'] = "menu" self.pause_mode['goal'] = "menu"
@ -820,7 +820,7 @@ class PackageOutput:
elif self.pause_mode['active'] and state_dict.get("start") and self.pause_mode['goal'] != "menu": elif self.pause_mode['active'] and state_dict.get("start") and self.pause_mode['goal'] != "menu":
pass pass
elif self.pause_mode['active'] and not state_dict.get("start") and self.pause_mode['goal'] != "menu": elif self.pause_mode['active'] and not state_dict.get("start") and self.pause_mode['goal'] != "menu":
print(self.pause_mode['goal']) print((self.pause_mode['goal']))
press_output = ["unpause"] press_output = ["unpause"]
elif self.pause_mode['active'] and self.pause_mode['total'] > 0: elif self.pause_mode['active'] and self.pause_mode['total'] > 0:
if state_dict.get("a"):#clicked.get("a"): if state_dict.get("a"):#clicked.get("a"):
@ -860,7 +860,7 @@ class PackageOutput:
break break
if path_data and x is not None and y is not None: if path_data and x is not None and y is not None:
path = PathFinder.find_path(path_data, 6-y,7+x) path = PathFinder.find_path(path_data, 6-y,7+x)
print("X Y ",x,y,target, num, goal) print(("X Y ",x,y,target, num, goal))
if path: if path:
vy = -1*path[0][2] vy = -1*path[0][2]
vx = path[0][3] vx = path[0][3]
@ -873,7 +873,7 @@ class PackageOutput:
press_output.append("left") press_output.append("left")
elif vx > 0: elif vx > 0:
press_output.append("right") press_output.append("right")
print("AAAA ", map_data['tiles'][6-vy][7+vx]['type'], target) print(("AAAA ", map_data['tiles'][6-vy][7+vx]['type'], target))
if map_data['tiles'][6-vy][7+vx]['type'] == target.replace(",", "").strip(): if map_data['tiles'][6-vy][7+vx]['type'] == target.replace(",", "").strip():
press_output.append("a") press_output.append("a")
output = list() output = list()
@ -915,7 +915,7 @@ def main_b():
t = time.time() t = time.time()
k, map_data = ParseScreenObstructions.parse_screen(im, tile_info, lud, k, map_data = ParseScreenObstructions.parse_screen(im, tile_info, lud,
plud, partial_center=True) plud, partial_center=True)
print( time.time()-t) print(( time.time()-t))
import pdb import pdb
pdb.set_trace() pdb.set_trace()
@ -924,9 +924,9 @@ def main_c():
for i in range(10): for i in range(10):
im = Image.open("maps_"+str(2+i)+".png") im = Image.open("maps_"+str(2+i)+".png")
t = time.time() t = time.time()
print ("--", po.memory) print(("--", po.memory))
print (po.run(im)) print((po.run(im)))
print (time.time()-t) print((time.time()-t))
import pdb import pdb
pdb.set_trace() pdb.set_trace()
@ -1165,11 +1165,11 @@ class ParseScreenText:
ch = seen[k] ch = seen[k]
im.paste(load_image(ch), (c*8, 0)) im.paste(load_image(ch), (c*8, 0))
kk = found_tiles.keys() kk = list(found_tiles.keys())
stra = [x for x in " >>ABCDEFGHIJ KLMNOPQRSTUVWXYZ',.123456789abcdefghijklmnopqrstuvwxyz-"] stra = [x for x in " >>ABCDEFGHIJ KLMNOPQRSTUVWXYZ',.123456789abcdefghijklmnopqrstuvwxyz-"]
stra.extend(["..", "!", "?", " "," "," "," "," "," "," "," ",">",">"," "," ", "Mail", "Rod", " ", "Sword", " ", " "," "," "," "," "," ","Nunchucks", " ", " ","Hammer", " ", " ", " ", "Level", "/", "Weapon", " ", " ", " ", " ", "Status", " ", " ", " ", " ", " ", " ", ">", ">", " ", "E", ">", ">", "Fight", " ", " ", " "," ", " ", "Magic", " ", " ", " ", "Drink", " ", " ", " "]) stra.extend(["..", "!", "?", " "," "," "," "," "," "," "," ",">",">"," "," ", "Mail", "Rod", " ", "Sword", " ", " "," "," "," "," "," ","Nunchucks", " ", " ","Hammer", " ", " ", " ", "Level", "/", "Weapon", " ", " ", " ", " ", "Status", " ", " ", " ", " ", " ", " ", ">", ">", " ", "E", ">", ">", "Fight", " ", " ", " "," ", " ", "Magic", " ", " ", " ", "Drink", " ", " ", " "])
output_dict = OrderedDict() output_dict = OrderedDict()
kk2 = [seen[x] for x in seen.keys()] kk2 = [seen[x] for x in list(seen.keys())]
for i, ch in enumerate(kk2): for i, ch in enumerate(kk2):
subi = load_image(ch) subi = load_image(ch)
new_subi = reduce_to_colors(subi.convert("P", palette=Image.ADAPTIVE), ["FFFFFF"], 32) new_subi = reduce_to_colors(subi.convert("P", palette=Image.ADAPTIVE), ["FFFFFF"], 32)
@ -1267,7 +1267,7 @@ class TileTools:
return ress[0][0:2] return ress[0][0:2]
def to_image_key(img): def to_image_key(img):
if isinstance(img, basestring): if isinstance(img, str):
img = load_image(img) img = load_image(img)
key = image_to_string_format(img, "BMP") key = image_to_string_format(img, "BMP")
return key return key
@ -1314,11 +1314,11 @@ class ScreenSelector:
#images have different bmp headers sometimes, so reformat them here. #images have different bmp headers sometimes, so reformat them here.
new_dict = dict() new_dict = dict()
for key, val in cls.luds['plud']['person_dict'].items(): for key, val in list(cls.luds['plud']['person_dict'].items()):
new_dict[image_to_string_format(load_image(key),"BMP")] = val new_dict[image_to_string_format(load_image(key),"BMP")] = val
cls.luds['plud']['person_dict'] = new_dict cls.luds['plud']['person_dict'] = new_dict
new_dict = dict() new_dict = dict()
for key, val in cls.luds['lud'].items(): for key, val in list(cls.luds['lud'].items()):
new_dict[image_to_string_format(load_image(key), "BMP")] = val new_dict[image_to_string_format(load_image(key), "BMP")] = val
cls.luds['lud'] = new_dict cls.luds['lud'] = new_dict
@ -2159,9 +2159,9 @@ def main2():
im = load_image(image['image_data']) im = load_image(image['image_data'])
t = time.time() t = time.time()
tex = ParseScreenText.parse_screen(im, f) tex = ParseScreenText.parse_screen(im, f)
print (time.time()-t) print((time.time()-t))
for coord, line in tex: for coord, line in tex:
print(coord, line) print((coord, line))
if tex: if tex:
import pdb import pdb
pdb.set_trace() pdb.set_trace()
@ -2351,8 +2351,8 @@ def test_person():
po = PackageOutput("ff1_data.lud", "enemy_lookup.dat") po = PackageOutput("ff1_data.lud", "enemy_lookup.dat")
import pdb import pdb
pdb.set_trace() pdb.set_trace()
print ("--", po.memory) print(("--", po.memory))
print (po.run(im, {"paused": 1})) print((po.run(im, {"paused": 1})))
if __name__=='__main__': if __name__=='__main__':

BIN
test.pyc

Binary file not shown.

View File

@ -7,6 +7,7 @@ import time
import accessible_output2.outputs.auto import accessible_output2.outputs.auto
import os import os
import base64 import base64
import test
po = test.PackageOutput("ff1_data.lud", "enemy_lookup.dat") po = test.PackageOutput("ff1_data.lud", "enemy_lookup.dat")
auto_obj = accessible_output2.outputs.auto.Auto() auto_obj = accessible_output2.outputs.auto.Auto()
@ -17,7 +18,7 @@ def text_to_sound(string):
data = base64.b64encode(open("wave_out.wav").read()) data = base64.b64encode(open("wave_out.wav").read())
return data return data
class MainHandler(BaseHTTPServer.BaseHTTPRequestHandler): class MainHandler(BaseHTTPRequestHandler):
def do_GET(self): def do_GET(self):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "text/html") self.send_header("Content-type", "text/html")
@ -57,7 +58,7 @@ class MainHandler(BaseHTTPServer.BaseHTTPRequestHandler):
state = doc.get('state', {}) state = doc.get('state', {})
t_time = time.time() t_time = time.time()
strings, presses = po.run(im, state) strings, presses = po.run(im, state)
print('aaa', time.time()-t_time) print(('aaa', time.time()-t_time))
words = " ".join(strings).replace(">", " ").split(" ") words = " ".join(strings).replace(">", " ").split(" ")
nw = list() nw = list()
for idx, word in enumerate(words): for idx, word in enumerate(words):
@ -88,7 +89,7 @@ class MainHandler(BaseHTTPServer.BaseHTTPRequestHandler):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "text/html") self.send_header("Content-type", "text/html")
output = json.dumps(res) output = json.dumps(res)
print(len(output), time.time()-t_time) print((len(output), time.time()-t_time))
self.send_header("Content-Length", len(output)) self.send_header("Content-Length", len(output))
self.end_headers() self.end_headers()
self.wfile.write(output) self.wfile.write(output)
@ -97,7 +98,7 @@ class MainHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def main(): def main():
host = "localhost" host = "localhost"
port = 4404 port = 4404
server_class = BaseHTTPServer.HTTPServer server_class = HTTPServer
httpd = server_class((host, port), MainHandler) httpd = server_class((host, port), MainHandler)
try: try:
httpd.serve_forever() httpd.serve_forever()