ipo_noise.html


001| """IPO Implementation -- Add Noise.
001| 
001| Classes:
001|     ipo_proc_inoise (ipo_process)               ~Image Noise Process subclass
001|     ipo_proc_dnoise (ipo_process)               ~8-bit Data Noise Process subclass
001|     ipo_proc_tnoise (ipo_process)               ~Text Noise Process subclass
001| 
001| """

002| ####################################################################################################
003| from random import random, randint
004| from logger import logger
005| from goodies import typename, KWARG
006| from ipo_defs import ipo_token, ipo_input, ipo_process, ipo_output
007| ####################################################################################################
008| Log = logger('Noise')
009| 
010| 
011| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
012| class ipo_proc_inoise (ipo_process):
013|     """\
013| Image Noise Process subclass.
013| 
013| Add a percentage of noise or blanking to an RGB image file.
013| 
013| Parameters:
013|     mode        -type of noise or blanking
013|     pct         -percent of noise (0.0 to 1.0)
013| 
013| Noise Modes:
013|     0           -change X% of pixels to random color pixels
013|     1           -change X% of pixels to random grayscale pixels
013|     2           -change X% of pixels to black pixels
013|     3           -change X% of pixels to gray pixels
013|     4           -change X% of pixels to white pixels
013|     5           -fade all pixels to X% black
013|     6           -fade all pixels to x% gray
013|     7           -fade all pixels to X% white
013|     8           -TODO? fade all pixels to a given color
013| """

014|     tag = 'Image'
015| 
016|     rand_gray_pixel  = lambda pxl,nz: pxl if nz <= random() else 3*(randint(0,255),)
017|     rand_color_pixel = lambda pxl,nz: pxl if nz <= random() else (randint(0,255), randint(0,255), randint(0,255))
018| 
019|     black_pixel = lambda pxl,nz: pxl if nz <= random() else (  0,   0,   0)
020|     gray_pixel  = lambda pxl,nz: pxl if nz <= random() else (127, 127, 127)
021|     white_pixel = lambda pxl,nz: pxl if nz <= random() else (255, 255, 255)
022| 
023|     fade_to_black = lambda pxl,nz: tuple(c+int((  0-c)*nz) for c in pxl)
024|     fade_to_gray  = lambda pxl,nz: tuple(c+int((127-c)*nz) for c in pxl)
025|     fade_to_white = lambda pxl,nz: tuple(c+int((255-c)*nz) for c in pxl)
026| 
027|     def __init__ (self, **kwargs):
028|         """New ImageNoise Process instance."""
029|         super().__init__('I/Noise')
030|         self.mode = KWARG('mode', 0, int, kwargs)
031|         self.noise = KWARG('pct', 0.0, float, kwargs)
032| 
033|     def __call__ (self, datum):
034|         """Process next chunk of data."""
035|         if datum is None:
036|             self.status = -1
037|             return None
038|         super().__call__(datum)
039|         # Process for noise...
040|         for d in datum:
041|             val = d()
042|             match self.mode:
043|                 case 0:
044|                     val = ipo_proc_inoise.rand_color_pixel(val, self.noise)
045|                 case 1:
046|                     val = ipo_proc_inoise.rand_gray_pixel(val, self.noise)
047|                 case 2:
048|                     val = ipo_proc_inoise.black_pixel(val, self.noise)
049|                 case 3:
050|                     val = ipo_proc_inoise.gray_pixel(val, self.noise)
051|                 case 4:
052|                     val = ipo_proc_inoise.white_pixel(val, self.noise)
053|                 case 5:
054|                     val = ipo_proc_inoise.fade_to_black(val, self.noise)
055|                 case 6:
056|                     val = ipo_proc_inoise.fade_to_gray(val, self.noise)
057|                 case 7:
058|                     val = ipo_proc_inoise.fade_to_white(val, self.noise)
059|                 case _:
060|                     raise ValueError('Unknown Noise Mode: {self.mode}')
061|             d(val)
062|         # Return datum...
063|         return datum
064| 
065| 
066| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
067| class ipo_proc_dnoise (ipo_process):
068|     """\
068| 8-bit Data Noise Process subclass.
068| 
068| Add a percentage of noise or blanking to a text file.
068| 
068| Parameters:
068|     mode        -type of noise or blanking
068|     pct         -percent of noise (0.0 to 1.0)
068| 
068| Noise Modes:
068|     0           -change X% of bytes to a random byte [00-ff]
068|     1           -change X% of bytes to a random byte [00-7f]
068|     2           -change X% of bytes to a random byte [20-7e]
068|     3           -change X% of bytes to 0x00 (zero; all bits off)
068|     4           -change X% of bytes to 0x20 (space char)
068|     5           -change X% of bytes to 0x40 (@ char)
068|     6           -change X% of bytes to 0x60 (` char)
068|     7           -change X% of bytes to 0x7f (DEL char)
068|     8           -change X% of bytes to 0xff (all bits on)
068| """

069|     tag = 'Data'
070| 
071|     def __init__ (self, **kwargs):
072|         """New DataNoise Process instance."""
073|         super().__init__('D/Noise')
074|         self.mode = KWARG('mode', 0, int, kwargs)
075|         self.noise = KWARG('pct', 0.0, float, kwargs)
076| 
077|     def __call__ (self, datum):
078|         """Process next chunk of data."""
079|         if datum is None:
080|             self.status = -1
081|             return None
082|         super().__call__(datum)
083|         # Process for noise...
084|         for d in datum:
085|             if random() < self.noise:
086|                 match self.mode:
087|                     case 0:
088|                         val = chr(randint(0,255))
089|                     case 1:
090|                         val = chr(randint(0,127))
091|                     case 2:
092|                         val = chr(randint(32,126))
093|                     case 3:
094|                         val = chr(0x00)
095|                     case 4:
096|                         val = chr(0x20)
097|                     case 5:
098|                         val = chr(0x40)
099|                     case 6:
100|                         val = chr(0x60)
101|                     case 7:
102|                         val = chr(0x7f)
103|                     case 8:
104|                         val = chr(0xff)
105|                     case _:
106|                         raise ValueError('Unknown Noise Mode: {self.mode}')
107|                 d(val)
108|         # Return datum...
109|         return datum
110| 
111| 
112| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
113| class ipo_proc_tnoise (ipo_process):
114|     """\
114| Text Noise Process subclass.
114| 
114| Add a percentage of noise or blanking to a text file.
114| 
114| Parameters:
114|     mode        -type of noise or blanking
114|     pct         -percent of noise (0.0 to 1.0)
114| 
114| Noise Modes:
114|    <0           -no UTF8 vetting
114|     0           -default
114|     1           -no CC changes
114|     2           -no WS changes
114|     7           -[00-7f] overrides lower modes
114|     8           -[00-ff] overrides lower modes
114|     9           -blanks - overrides lower modes
114| """

115|     tag = 'Text'
116|     CCB = ord('@') # Control Character Base
117|     rand_diff = lambda: (-ndist + randint(0, ndist*2))
118|     ws_test = lambda ch: (ch in '\r\n\f\t')
119| 
120|     def __init__ (self, **kwargs):
121|         """New TextNoise Process instance."""
122|         super().__init__('T/Noise')
123|         self.mode = KWARG('mode', 0, int, kwargs)
124|         self.noise = KWARG('pct', 0.0, float, kwargs)
125| 
126|     def __call__ (self, datum):
127|         """Process next chunk of data."""
128|         if datum is None:
129|             self.status = -1
130|             return None
131|         super().__call__(datum)
132|         # Process for noise...
133|         for d in datum:
134|             if random() < self.noise:
135|                 match self.mode:
136|                     case 0:
137|                         val = chr(randint(32,126))
138|                     case 1:
139|                         val = ' '
140|                     case 2:
141|                         val = 'X'
142|                     case 3:
143|                         val = '_'
144|                     case _:
145|                         raise ValueError('Unknown Noise Mode: {self.mode}')
146|                 d(val)
147|         # Return datum...
148|         return datum
149| 
150|     #TODO: Not being used!
151|     def add_noise (self, char):
152|         '''Add random noise to a character (sometimes).'''
153|         if noise < random(): return char
154| 
155|         # Mode 7: Return any 7-bit random character...
156|         if nmode == 7: return chr(randint(0,127))
157| 
158|         # Mode 8: Return any 8-bit random character...
159|         if nmode == 8: return chr(randint(0,255))
160| 
161|         # Mode 9: Return blanks (spaces by default)...
162|         if nmode == 9: return (char if self.ws_test(char) else blank)
163| 
164|         # Mode 1+: Don't alter certain control characters...
165|         if (1 <= nmode) and self.ws_test(char): return char
166|         # Mode 2+: Also don't alter spaces...
167|         if (2 <= nmode) and char.isspace(): return char
168| 
169|         # Generate a scrambled character (with a given possible delta)...
170|         cx = abs(ord(char) + self.rand_diff())
171|         if nmode < 0: return chr(cx)
172|         # If we went up into Unicode territory, back off...
173|         if 0x7f < cx: cx &= 0x7f
174|         # If we went down into control-code territory, convert to alpha...
175|         if cx < ord(SPC): cx += CCB
176|         # Return scrambled character...
177|         return chr(cx)
178| 
179| 
180| ####################################################################################################
181| if __name__ == '__main__':
182|     print()
183|     ipos = []
184|     kw = {}
185| 
186|     ipos.append(ipo_proc_inoise(**kw))
187|     ipos.append(ipo_proc_dnoise(**kw))
188|     ipos.append(ipo_proc_tnoise(**kw))
189|     ipos.append(None)
190| 
191|     for ix,obj in enumerate(ipos):
192|         if obj is None:
193|             print()
194|             continue
195|         print(f'{ix:2d}: {obj!s}')
196|         obj.start(None)
197|     print()
198| ####################################################################################################
199| """eof"""
200|