This commit is contained in:
.[d]. 2022-02-18 21:47:58 -06:00
parent cc42b3bc86
commit 6421e73036

@ -1,7 +1,141 @@
import sys ############################################################################# SOF
####################################################################################################################### reference="""
class C:
###################################################################################################################
"""
################################################################# CLASS DR1P4NS1
class dr1p4ns1:
############################################################################
commands = { commands = {
'A': 'up', 'A': 'up',
'B': 'down', 'B': 'down',
@ -16,46 +150,53 @@ class C:
'm': 'color', 'm': 'color',
'R': 'report_cursor_position' 'R': 'report_cursor_position'
} }
###################################################################################################################
ascii_table=""" ############################################################################
asc_table="""
ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥ƒ\ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥ƒ\
áíóúñѪº¿¬½¼¡«»\ áíóúñѪº¿¬½¼¡«»\
\ \
αßΓπΣσµτΦΘΩδφε±÷°·ⁿ²  αßΓπΣσµτΦΘΩδφε±÷°·ⁿ² 
""" """
###################################################################################################################
############################################################################
for r in (('\n',''),(' ','')): for r in (('\n',''),(' ','')):
ascii_table=ascii_table.replace(*r) asc_table=asc_table.replace(*r)
###################################################################################################################
asc2uni=dict(zip([i for i in range(128,256)],[ord(c) for c in ascii_table])) ############################################################################
################################################################################################################### asc2uni=dict(zip([i for i in range(128,256)],[ord(c) for c in asc_table]))
asc2chr=dict(zip([i for i in range(128,256)],[c for c in ascii_table]))
################################################################################################################### ############################################################################
def __init__(self,ansifile="",width=80,height=25): asc2chr=dict(zip([i for i in range(128,256)],[c for c in asc_table]))
############################################################################
def __init__(self,ansifile="",width=80,height=25,debug=False):
self.DEBUG=debug
self.width=width self.width=width
self.height=height self.height=height
self.openansi(ansifile) self.openansi(ansifile)
self.code='\x1b[0m' self.code='\x1b[0m'
print("\x1bc\x1b[1;31m[ DR1P LOADED ]\x1b[0m\n") self.cmps=[]
################################################################################################################### print("\x1bc\x1b[1;31m[ DR1P ]\x1b[0m\n")
self.boot()
############################################################################
def openansi(self,s): def openansi(self,s):
try: f=open(s,'rb')
f=open(s,'rb') self.ansifile=f.read().decode('cp437')
self.ansifile=f.read().decode('cp437') f.close()
f.close()
except: ############################################################################
print(f'\n\x1b[1;31m[ ERROR: "{s}" FILE NOT FOUND ] - *USAGE: `python3 {sys.argv[0]} work.ans`\x1b[0m')
sys.exit(1)
###################################################################################################################
def printascii(self): def printascii(self):
for i,_ in enumerate(self.ascii_table): for i,_ in enumerate(self.asc_table):
_int=str(i+128).zfill(3) _int=str(i+128).zfill(3)
_hex=hex(i+128)[2:].upper().zfill(2) _hex=hex(i+128)[2:].upper().zfill(2)
_ord=str(ord(_)).zfill(4) _ord=str(ord(_)).zfill(4)
print(f'{_} - {_int} - {_hex} - {_ord}') print(f'{_} - {_int} - {_hex} - {_ord}')
###################################################################################################################
############################################################################
def printrange(self,n,nn): def printrange(self,n,nn):
for index,_ in enumerate(c.ansifile): for index,_ in enumerate(self.ansifile):
h=hex(_)[2:].upper() h=hex(_)[2:].upper()
i=str(_).zfill(3) i=str(_).zfill(3)
s='' s=''
@ -63,51 +204,49 @@ class C:
s=chr(_) s=chr(_)
else: else:
s='.' s='.'
l=str(index).zfill(len(str(len(c.ansifile)))) l=str(index).zfill(len(str(len(self.ansifile))))
if index >=n and index <=nn: if index >=n and index <=nn:
print(f"{l} {i} {h} {s}") print(f"{l} {i} {h} {s}")
if index==nn: break if index==nn:
################################################################################################################### break
############################################################################
def printhex(self): def printhex(self):
###########################################
theasc=[] theasc=[]
thehex=[] thehex=[]
buffer='' buffer=''
###########################################
for _ in self.ansifile: for _ in self.ansifile:
buffer+=hex(ord(_)).upper()[2:].zfill(2) buffer+=hex(ord(_)).upper()[2:].zfill(2)
###########################################
for _ in self.chunk(buffer,32): for _ in self.chunk(buffer,32):
subchunks='' subchunks=''
for i,__ in enumerate(self.chunk(_,2)): for i,__ in enumerate(self.chunk(_,2)):
if i>0 and i%4==0: subchunks+=" " if i>0 and i%4==0: subchunks+=" "
subchunks+=f'{__} ' subchunks+=f'{__} '
thehex.append(subchunks.strip()) thehex.append(subchunks.strip())
###########################################
for __ in thehex: for __ in thehex:
buffer='' buffer=''
for _ in __.split(): for _ in __.split():
i=int(_,16) i=int(_,16)
if i>47 and i<127: if i>47 and i<127:
buffer+=chr(i) buffer+=chr(i)
else: else:
buffer+='.' buffer+='.'
theasc.append(buffer) theasc.append(buffer)
###########################################
for _ in range(len(thehex)): for _ in range(len(thehex)):
old=buffer old=buffer
buffer={thehex[_]} buffer={thehex[_]}
if not buffer == old: if not buffer == old:
print(f"{hex(16 * _)[2:].zfill(8)} {thehex[_]} {theasc[_]}") print(f"{hex(16 * _)[2:].zfill(8)} {thehex[_]} {theasc[_]}")
###################################################################################################################
def hexdump(self,visible=True): ############################################################################
if visible == True: def hexdump(self):
if self.DEBUG:
print("\n\x1b[1;31m[ HEXDUMP ]\x1b[0m\n")
self.printhex() self.printhex()
self.codes=[] self.codes=[]
code_start=0 code_start=0
code_end=0 code_end=0
code_state=False code_state=False
buffer=''
for i,_ in enumerate(self.ansifile): for i,_ in enumerate(self.ansifile):
if code_state==False: if code_state==False:
if _ == '\x1b': if _ == '\x1b':
@ -123,104 +262,181 @@ class C:
code_end=i+1 code_end=i+1
code=self.ansifile[code_start:code_end] code=self.ansifile[code_start:code_end]
self.codes.append([code,code_start,code_end]) self.codes.append([code,code_start,code_end])
###################################################################################################################
############################################################################
def findall(self,s,w): def findall(self,s,w):
return [i for i in range(len(s)) if s.startswith(w, i)] return [i for i in range(len(s)) if s.startswith(w, i)]
###################################################################################################################
############################################################################
def getsauce(self): def getsauce(self):
SPASS='\x1b[1;31m[ SAUCE INFO FOUND ] - X: {} Y: {}\x1b[0m\n'
SFAIL='\x1b[1;31m[ NO SAUCE INFO FOUND ]\x1b[0m\n'
try: try:
self.ansifile[-128:] if self.ansifile[-129:][0] == '\x1a' \
self.ansifile_xwidth=ord(c.ansifile[-128:][96]) and self.ansifile[-128:][:5] == 'SAUCE':
self.ansifile_yheight=ord(c.ansifile[-128:][98]) self.ansifile_xwidth=ord(self.ansifile[-128:][96])
self.width=self.ansifile_xwidth self.ansifile_yheight=ord(self.ansifile[-128:][98])
self.height=self.ansifile_yheight self.width=self.ansifile_xwidth
print(f'\x1b[31m[ SAUCE INFO FOUND ] - X: {self.width} Y: {self.height}\x1b[0m\n') self.height=self.ansifile_yheight
print(SPASS.format(self.width,self.height))
else:
print(SFAIL)
except: except:
print('\x1b[31m[ NO SAUCE INFO FOUND ]\x1b[0m\n') print(SFAIL)
###################################################################################################################
def chunk(self,s,n): ############################################################################
def cmpans(self,s1,s2,n1=0,n2=0):
_s1=''; _s2=''; _sn1=''; _sn2=''
_s1=self.stripcodes(s1)
_s2=self.stripcodes(s2)
if not n1 == n2:
_sn1=_s1[n1:n2]
_sn2=_s2[n1:n2]
_sn3=''
for i in range(self.width):
try:
if ord(_sn1[i]) == ord(_sn2[i]):
_sn3+='\x1b[32m0\x1b[0m'
else:
_sn3+='\x1b[31m1\x1b[0m'
except Exception as e:
print(e)
self.cmps.append(f'{_sn1}\n{_sn2}\n{_sn3}')
n1+=self.width
n2+=self.width
############################################################################
def chunk(self,s,n):
return [s[i:i+n] for i in range(0,len(s),n)] return [s[i:i+n] for i in range(0,len(s),n)]
###################################################################################################################
############################################################################
def stripcodes(self,s):
buffer=s
code_start=0
code_end=0
code_state=False
for i,_ in enumerate(s):
if code_state==False:
if _ == '\x1b':
code_state=True
code_start=i
else:
if 64 <= ord(_) <= 126:
if _ in self.commands:
code_state=False
code_end=i+1
code=s[code_start:code_end]
buffer=buffer.replace(code,'')
return buffer
############################################################################
def rgb(self,t='',r=0,g=0,b=0): def rgb(self,t='',r=0,g=0,b=0):
"""colorize text with rgb values""" """colorize text with rgb values"""
return f"\033[38;2;{r};{g};{b}m{t}\033[38;2;255;255;255m" return f"\033[38;2;{r};{g};{b}m{t}\033[38;2;255;255;255m"
###################################################################################################################
############################################################################
def vga(self,t='',i=0): def vga(self,t='',i=0):
"""colorize text using vga color set""" """colorize text using vga color set"""
vga = ['#000000','#aa0000','#00aa00','#aa5500','#0000aa','#aa00aa','#00aaaa','#aaaaaa', vga = [ '#000000','#aa0000','#00aa00','#aa5500',
'#555555','#ff5555','#55ff55','#ffff55','#5555ff','#ff55ff','#55ffff','#ffffff',] '#0000aa','#aa00aa','#00aaaa','#aaaaaa',
'#555555','#ff5555','#55ff55','#ffff55',
'#5555ff','#ff55ff','#55ffff','#ffffff', ]
try: try:
r,g,b=int(vga[i][1:][0:2],16),int(vga[i][1:][2:4],16),int(vga[i][1:][4:6],16) r=int(vga[i][1:][0:2],16)
g=int(vga[i][1:][2:4],16)
b=int(vga[i][1:][4:6],16)
except: except:
r,g,b=0,0,0 r,g,b=0,0,0
return f"\033[38;2;{r};{g};{b}m{t}\033[38;2;255;255;255m" return f"\033[38;2;{r};{g};{b}m{t}\033[38;2;255;255;255m"
#######################################################################################################################
if __name__ == "__main__": ############################################################################
################################################################ def invert_dict(self,d):
try: return {v: k for k, v in d.items()}
input_file=sys.argv[1]
except: ############################################################################
input_file='work.ans' def boot(self):
c=C(ansifile=input_file,width=80) self.getsauce()
c.getsauce() self.hexdump()
c.hexdump(visible=False) op=[]
################################################################ fb=self.ansifile
op=[] xnew=0
fb=c.ansifile xold=0
xnew=0 for _ in self.codes:
xold=0 xnew=_[1]
############ distance=xnew-xold
for _ in c.codes: if not distance == 0:
xnew=_[1] gap=fb[xold:xold+distance]
distance=xnew-xold op.append(gap)
if not distance == 0: op.append(_[0])
gap=fb[xold:xold+distance] xold=_[2]
op.append(gap) optype=[]
op.append(_[0]) for i,_op in enumerate(op):
xold=_[2] if _op.startswith('\x1b'):
################################################################ if _op.endswith('m'):
optype=[] optype.append(2)
############ elif _op.endswith('C'):
for i,_op in enumerate(op): optype.append(3)
if _op.startswith('\x1b'): else:
if _op.endswith('m'): optype.append(0)
optype.append(2) elif _op.startswith('\x1a'):
######################################################## optype.append(4)
elif _op.endswith('C'):
optype.append(3)
########################################################
else: else:
optype.append(0) optype.append(1)
############################################################ offset=0
elif _op.startswith('\x1a'): offsets=[]
optype.append(4) processed=[]
############################################################ uniqued=[]
else: uniques=[]
optype.append(1) processing=''
################################################################ for i,_optype in enumerate(optype):
offset=0 if _optype==2:
processed=[] processing+=op[i]
processing='' offset+=len(op[i])
############ elif _optype==3:
for i,_optype in enumerate(optype): count=int(op[i].split('[')[1].split('C')[0])
if _optype==2: processing+=' '*count
processing+=op[i] elif _optype==1:
offset+=len(op[i]) processing+=op[i]
############################################################ _bseq='\r\n'
elif _optype==3: _xpos=processing.find(_bseq)
count=int(op[i].split('[')[1].split('C')[0]) if not _xpos == -1:
processing+=' '*count uniques.append(_bseq)
############################################################ uniques.append(_xpos)
elif _optype==1: processing=processing.replace(_bseq,'',1)
processing+=op[i] gaps=self.width-len(self.stripcodes(processing))
############################################################ processing+=' '*int(gaps)
if len(processing)-offset > c.width: if len(processing)-offset > self.width:
while len(processing)-offset > c.width: while len(processing)-offset > self.width:
deconcatenate=processing[0:c.width+offset] deconcatenate=processing[0:self.width+offset]
processed.append(deconcatenate) processed.append(deconcatenate)
processing=processing.replace(deconcatenate,'',1) if len(uniques) < 2:
offset=0 uniqued.append('')
################################################################# else:
for _ in processed: print(_) uniqued.append(uniques)
print('\x1b[1;31m[ COMPLETED ]\x1b[0m\n') uniqued.append(uniques)
##################################################################### uniques=[]
offsets.append(offset)
processing=processing.replace(deconcatenate,'',1)
offset=0
if self.DEBUG:
print("\n\x1b[1;31m[ COMPARE LINE AGAINST REFERENCE ]\x1b[0m\n")
_r=reference.strip().splitlines()
for i,_ in enumerate(processed):
s1=_r[i]
s2=_
self.cmpans(s1=s1,s2=s2,n1=0,n2=self.width)
if i >= 128:
break
for i,_ in enumerate(self.cmps):
print(_+f' - {str(i).zfill(4)}')
if self.DEBUG:
print("\n \x1b[1;31m[ PROCESSED ANSI ]\x1b[0m\n")
for _ in processed: print(_)
print('\n\x1b[1;31m[ DR0P ]\x1b[0m')
########################################################################### MAIN
if __name__ == "__main__":
d=dr1p4ns1(ansifile='work.ans',width=80,debug=False)
############################################################################ EOF