archive

- Random tools & helpful resources for IRC
git clone git://git.acid.vegas/archive.git
Log | Files | Refs | Archive

irc2ansi.py (3586B)

      1 #!/usr/bin/env python
      2 # IRC2ANSI - Developed by acidvegas in Python (https://git.acid.vegas/archive)
      3 
      4 import re
      5 
      6 def IRC2ANSI(text):
      7 	''' Convert IRC art to ANSI art. '''
      8 
      9 	_formats = {
     10 		'\x02': '\033[1m', # Bold
     11 		'\x1D': '\033[3m', # Italic
     12 		'\x1F': '\033[4m', # Underline
     13 		'\x16': '\033[7m', # Reverse
     14 		'\x0f': '\033[0m', # Reset
     15 	}
     16 
     17 	_colors = {
     18 		'00': ('37',  '47'), # White
     19 		'01': ('30',  '40'), # Black
     20 		'02': ('34',  '44'), # Blue
     21 		'03': ('32',  '42'), # Green
     22 		'04': ('91', '101'), # Red
     23 		'05': ('31',  '41'), # Brown
     24 		'06': ('35',  '45'), # Purple
     25 		'07': ('33',  '43'), # Orange
     26 		'08': ('93', '103'), # Yellow
     27 		'09': ('92', '102'), # Light Green
     28 		'10': ('36',  '46'), # Teal
     29 		'11': ('96', '106'), # Cyan
     30 		'12': ('94', '104'), # Light Blue
     31 		'13': ('95', '105'), # Magenta
     32 		'14': ('90', '100'), # Gray
     33 		'15': ('37',  '47')  # Light Gray
     34 	}
     35 
     36 	for i in range(16,100): # Add support for 99 colors
     37 		_colors[str(i)] = (str(i), str(i))
     38 
     39 	irc_color_regex = re.compile(r'\x03((?:\d{1,2})?(?:,\d{1,2})?)?')
     40 
     41 	def replace_irc_color(match):
     42 		''' Replace IRC color codes with ANSI color codes. '''
     43 		if (irc_code := match.group(1)):
     44 			codes = irc_code.split(',')
     45 			foreground = '0'+codes[0] if len(codes[0]) == 1 else codes[0]
     46 			background = ('0'+codes[1] if len(codes[1]) == 1 else codes[1]) if len(codes) == 2 else None
     47 			ansi_foreground = _colors.get(foreground, '37')[0]
     48 			ansi_background = _colors.get(background, '47')[1]
     49 			return f'\033[{ansi_foreground};{ansi_background}m' if background else  f'\033[{ansi_foreground}m'
     50 		return '\033[0m' # Reset colors on no match
     51 
     52 	for item in _formats:
     53 		if item in text:
     54 			text = text.replace(item, _formats[item])
     55 	text = text.replace('\n', '\033[0m\n') # Make sure we end with a reset code
     56 
     57 	return irc_color_regex.sub(replace_irc_color, text) + '\033[0m'
     58 
     59 
     60 if __name__ == '__main__':
     61 
     62 	'''A simple script to test the IRC2ANSI function. (can you tell m using vscode yet...)
     63 	Usage: ./irc2ansi.py <path>, where <path> is a file or directory containing IRC art.
     64 	When using a directory, the script will loop through all files in the directory and play them randomly, acting as a screensaver.'''
     65 
     66 	import os      #
     67 	import sys     # We import these libraries here so they are only loaded when running the script directly
     68 	import time    # This way, the script can still be imported as module for other scripts, without loading these libraries
     69 	import pathlib # This is useful for testing the script directly and shows and example of how to use it in other scripts
     70 	import random  #
     71 
     72 	PRINT_TITLES = True # Set to False to disable printing titles when looping dircetories
     73 
     74 	if len(sys.argv) == 2:
     75 		try:
     76 			import chardet
     77 		except ImportError:
     78 			raise SystemExit('missing chardet module (pip install chardet)')
     79 
     80 		if os.path.exists(sys.argv[1]):
     81 			option = sys.argv[1]
     82 
     83 			def play(path):
     84 				with open(path, 'rb') as art_file:
     85 					data = art_file.read()
     86 					enc  = chardet.detect(data)['encoding']
     87 					lines = IRC2ANSI(data.decode(enc)).split('\n')
     88 					for line in lines:
     89 						print(line)
     90 						time.sleep(0.05)
     91 
     92 			if os.path.isdir(option):
     93 				if (results := list(pathlib.Path(option).rglob('*.[tT][xX][tT]'))):
     94 					while True:
     95 						random.shuffle(results)
     96 						for result in results:
     97 							play(result)
     98 							if PRINT_TITLES:
     99 								print(result)
    100 							time.sleep(3)
    101 
    102 			elif os.path.isfile(option):
    103 				play(option)
    104 
    105 			else:
    106 				raise SystemExit('invalid path')
    107 
    108 		else:
    109 			raise SystemExit('invalid path')
    110 
    111 	else:
    112 		raise SystemExit('missing or invalid arguments (usage: ./irc2ansi.py <path>)')