Politrees commited on
Commit
1d000a8
·
verified ·
1 Parent(s): 44bd5dc

Rename txt2spec.py to steganography.py

Browse files
Files changed (1) hide show
  1. txt2spec.py → steganography.py +88 -48
txt2spec.py → steganography.py RENAMED
@@ -7,35 +7,30 @@ import gradio as gr
7
  import soundfile as sf
8
  import os
9
 
10
- # Function for creating a spectrogram image with text
11
  def text_to_spectrogram_image(text, base_width=512, height=256, max_font_size=80, margin=10, letter_spacing=5):
12
- # Font and text size
13
  font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
14
  if os.path.exists(font_path):
15
  font = ImageFont.truetype(font_path, max_font_size)
16
  else:
17
  font = ImageFont.load_default()
18
 
19
- # Determine the width of the text, taking into account the distance between letters
20
  image = Image.new('L', (base_width, height), 'black')
21
  draw = ImageDraw.Draw(image)
22
  text_width = 0
23
  for char in text:
24
  text_bbox = draw.textbbox((0, 0), char, font=font)
25
  text_width += text_bbox[2] - text_bbox[0] + letter_spacing
26
- text_width -= letter_spacing # Remove the extra spacing after the last letter
27
 
28
- # Increase the width of the image if the text does not fit
29
  if text_width + margin * 2 > base_width:
30
  width = text_width + margin * 2
31
  else:
32
  width = base_width
33
 
34
- # Create an image with a new width
35
  image = Image.new('L', (width, height), 'black')
36
  draw = ImageDraw.Draw(image)
37
 
38
- # Writing text in the center of the image
39
  text_x = (width - text_width) // 2
40
  text_y = (height - (text_bbox[3] - text_bbox[1])) // 2
41
  for char in text:
@@ -43,78 +38,123 @@ def text_to_spectrogram_image(text, base_width=512, height=256, max_font_size=80
43
  char_bbox = draw.textbbox((0, 0), char, font=font)
44
  text_x += char_bbox[2] - char_bbox[0] + letter_spacing
45
 
46
- # Increase text contrast
47
  image = np.array(image)
48
- image = np.where(image > 0, 255, image) # Setting the text to "maximum white"
49
  return image
50
 
51
- # Converting an image to audio
52
  def spectrogram_image_to_audio(image, sr=22050):
53
- # Rotate the image vertically
54
  flipped_image = np.flipud(image)
55
-
56
- # Преобразуем изображение в амплитуды спектрограммы
57
  S = flipped_image.astype(np.float32) / 255.0 * 100.0
58
-
59
- # Converting the spectrogram to an audio signal
60
  y = librosa.griffinlim(S)
61
  return y
62
 
63
- # Function for creating an audio file and spectrogram from text
64
  def create_audio_with_spectrogram(text, base_width, height, max_font_size, margin, letter_spacing):
65
- # Create spectrogram image with normal text
66
  spec_image = text_to_spectrogram_image(text, base_width, height, max_font_size, margin, letter_spacing)
67
-
68
- # Generate audio signal with inverted text
69
  y = spectrogram_image_to_audio(spec_image)
70
-
71
- # Save audio signal and spectrogram image
72
  audio_path = 'output.wav'
73
  sf.write(audio_path, y, 22050)
74
-
75
  image_path = 'spectrogram.png'
76
  plt.imsave(image_path, spec_image, cmap='gray')
77
-
78
  return audio_path, image_path
79
 
80
- # Gradio interface
81
- with gr.Blocks(title='Audio Steganography', theme=gr.themes.Soft(primary_hue="green", secondary_hue="green", spacing_size="sm", radius_size="lg")) as iface:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  with gr.Group():
84
  with gr.Row(variant='panel'):
85
  with gr.Column():
86
- gr.HTML("<center><h2><a href='https://t.me/pol1trees'>Telegram Channel</a></h2></center>")
87
  with gr.Column():
88
- gr.HTML("<center><h2><a href='https://t.me/+GMTP7hZqY0E4OGRi'>Telegram Chat</a></h2></center>")
89
  with gr.Column():
90
  gr.HTML("<center><h2><a href='https://www.youtube.com/channel/UCHb3fZEVxUisnqLqCrEM8ZA'>YouTube</a></h2></center>")
91
  with gr.Column():
92
  gr.HTML("<center><h2><a href='https://github.com/Bebra777228/Audio-Steganography'>GitHub</a></h2></center>")
93
 
94
- with gr.Group():
95
- text = gr.Textbox(lines=2, placeholder="Enter your text:", label="Text")
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- with gr.Row(variant='panel'):
98
- base_width = gr.Slider(value=512, label="Image Width", visible=False)
99
- height = gr.Slider(value=256, label="Image Height", visible=False)
100
- max_font_size = gr.Slider(minimum=10, maximum=130, step=5, value=80, label="Font Size")
101
- margin = gr.Slider(minimum=0, maximum=50, step=1, value=10, label="Indent")
102
- letter_spacing = gr.Slider(minimum=0, maximum=50, step=1, value=5, label="Letter spacing")
103
 
104
- generate_button = gr.Button("Generate")
 
 
 
 
105
 
106
- with gr.Column(variant='panel'):
107
- output_audio = gr.Audio(type="filepath", label="Generated audio")
108
- output_image = gr.Image(type="filepath", label="Spectrogram")
 
 
 
 
 
109
 
110
- def gradio_interface_fn(text, base_width, height, max_font_size, margin, letter_spacing):
111
- print("\n", text)
112
- return create_audio_with_spectrogram(text, base_width, height, max_font_size, margin, letter_spacing)
113
-
114
- generate_button.click(
115
- gradio_interface_fn,
116
- inputs=[text, base_width, height, max_font_size, margin, letter_spacing],
117
- outputs=[output_audio, output_image]
118
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  iface.launch(share=True)
 
7
  import soundfile as sf
8
  import os
9
 
10
+ # Функция для создания изображения спектрограммы с текстом
11
  def text_to_spectrogram_image(text, base_width=512, height=256, max_font_size=80, margin=10, letter_spacing=5):
 
12
  font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
13
  if os.path.exists(font_path):
14
  font = ImageFont.truetype(font_path, max_font_size)
15
  else:
16
  font = ImageFont.load_default()
17
 
 
18
  image = Image.new('L', (base_width, height), 'black')
19
  draw = ImageDraw.Draw(image)
20
  text_width = 0
21
  for char in text:
22
  text_bbox = draw.textbbox((0, 0), char, font=font)
23
  text_width += text_bbox[2] - text_bbox[0] + letter_spacing
24
+ text_width -= letter_spacing
25
 
 
26
  if text_width + margin * 2 > base_width:
27
  width = text_width + margin * 2
28
  else:
29
  width = base_width
30
 
 
31
  image = Image.new('L', (width, height), 'black')
32
  draw = ImageDraw.Draw(image)
33
 
 
34
  text_x = (width - text_width) // 2
35
  text_y = (height - (text_bbox[3] - text_bbox[1])) // 2
36
  for char in text:
 
38
  char_bbox = draw.textbbox((0, 0), char, font=font)
39
  text_x += char_bbox[2] - char_bbox[0] + letter_spacing
40
 
 
41
  image = np.array(image)
42
+ image = np.where(image > 0, 255, image)
43
  return image
44
 
45
+ # Преобразовываем изображение в аудиосигнал
46
  def spectrogram_image_to_audio(image, sr=22050):
 
47
  flipped_image = np.flipud(image)
 
 
48
  S = flipped_image.astype(np.float32) / 255.0 * 100.0
 
 
49
  y = librosa.griffinlim(S)
50
  return y
51
 
52
+ # Функция для создания аудиофайла и спектрограммы из текста
53
  def create_audio_with_spectrogram(text, base_width, height, max_font_size, margin, letter_spacing):
 
54
  spec_image = text_to_spectrogram_image(text, base_width, height, max_font_size, margin, letter_spacing)
 
 
55
  y = spectrogram_image_to_audio(spec_image)
 
 
56
  audio_path = 'output.wav'
57
  sf.write(audio_path, y, 22050)
 
58
  image_path = 'spectrogram.png'
59
  plt.imsave(image_path, spec_image, cmap='gray')
 
60
  return audio_path, image_path
61
 
62
+ # Функция для отображения спектрограммы аудиофайла
63
+ def display_audio_spectrogram(audio_path):
64
+ y, sr = librosa.load(audio_path)
65
+ S = librosa.feature.melspectrogram(y=y, sr=sr)
66
+ S_dB = librosa.power_to_db(S, ref=np.max)
67
+
68
+ plt.figure(figsize=(10, 4))
69
+ librosa.display.specshow(S_dB)
70
+ plt.tight_layout()
71
+
72
+ spectrogram_path = 'uploaded_spectrogram.png'
73
+ plt.savefig(spectrogram_path)
74
+ plt.close()
75
+ return spectrogram_path
76
+
77
+ # Преобразование загруженного изображения в спектрограмму звука
78
+ def image_to_spectrogram_audio(image_path, sr=22050):
79
+ image = Image.open(image_path).convert('L')
80
+ image = np.array(image)
81
+ y = spectrogram_image_to_audio(image, sr)
82
+ audio_path = 'image_to_audio_output.wav'
83
+ sf.write(audio_path, y, sr)
84
+ return audio_path
85
+
86
+ # Интерфейс Gradio
87
+ with gr.Blocks(title='Аудио-Стеганография', theme=gr.themes.Soft(primary_hue="green", secondary_hue="green", spacing_size="sm", radius_size="lg")) as iface:
88
 
89
  with gr.Group():
90
  with gr.Row(variant='panel'):
91
  with gr.Column():
92
+ gr.HTML("<center><h2><a href='https://t.me/pol1trees'>Telegram Канал</a></h2></center>")
93
  with gr.Column():
94
+ gr.HTML("<center><h2><a href='https://t.me/+GMTP7hZqY0E4OGRi'>Telegram Чат</a></h2></center>")
95
  with gr.Column():
96
  gr.HTML("<center><h2><a href='https://www.youtube.com/channel/UCHb3fZEVxUisnqLqCrEM8ZA'>YouTube</a></h2></center>")
97
  with gr.Column():
98
  gr.HTML("<center><h2><a href='https://github.com/Bebra777228/Audio-Steganography'>GitHub</a></h2></center>")
99
 
100
+ with gr.Tab("Текст в Спектрограмму"):
101
+ with gr.Group():
102
+ text = gr.Textbox(lines=2, placeholder="Введите свой текст:", label="Текст")
103
+ with gr.Row(variant='panel'):
104
+ base_width = gr.Slider(value=512, label="Ширина изображения", visible=False)
105
+ height = gr.Slider(value=256, label="Высота изображения", visible=False)
106
+ max_font_size = gr.Slider(minimum=10, maximum=130, step=5, value=80, label="Размер шрифта")
107
+ margin = gr.Slider(minimum=0, maximum=50, step=1, value=10, label="Отступ")
108
+ letter_spacing = gr.Slider(minimum=0, maximum=50, step=1, value=5, label="Расстояние между буквами")
109
+ generate_button = gr.Button("Сгенерировать")
110
+
111
+ with gr.Column(variant='panel'):
112
+ output_audio = gr.Audio(type="filepath", label="Сгенерированный звук")
113
+ output_image = gr.Image(type="filepath", label="Спектрограмма")
114
 
115
+ def gradio_interface_fn(text, base_width, height, max_font_size, margin, letter_spacing):
116
+ return create_audio_with_spectrogram(text, base_width, height, max_font_size, margin, letter_spacing)
 
 
 
 
117
 
118
+ generate_button.click(
119
+ gradio_interface_fn,
120
+ inputs=[text, base_width, height, max_font_size, margin, letter_spacing],
121
+ outputs=[output_audio, output_image]
122
+ )
123
 
124
+ with gr.Tab("Изображение в Спектрограмму"):
125
+ with gr.Group():
126
+ with gr.Row(variant='panel'):
127
+ upload_image = gr.Image(type="filepath", label="Загрузите изображение")
128
+ convert_button = gr.Button("Конвертировать в аудио")
129
+
130
+ with gr.Column(variant='panel'):
131
+ output_audio_from_image = gr.Audio(type="filepath", label="Сгенерированный звук")
132
 
133
+ def gradio_image_to_audio_fn(upload_image):
134
+ return image_to_spectrogram_audio(upload_image)
135
+
136
+ convert_button.click(
137
+ gradio_image_to_audio_fn,
138
+ inputs=[upload_image],
139
+ outputs=[output_audio_from_image]
140
+ )
141
+
142
+ with gr.Tab("Спектрограмма аудио"):
143
+ with gr.Group():
144
+ with gr.Row(variant='panel'):
145
+ upload_audio = gr.Audio(type="filepath", label="Загрузите аудиофайл")
146
+ decode_button = gr.Button("Показать спектрограмму")
147
+
148
+ with gr.Column(variant='panel'):
149
+ decoded_image = gr.Image(type="filepath", label="Спектрограмма аудио")
150
+
151
+ def gradio_decode_fn(upload_audio):
152
+ return display_audio_spectrogram(upload_audio)
153
+
154
+ decode_button.click(
155
+ gradio_decode_fn,
156
+ inputs=[upload_audio],
157
+ outputs=[decoded_image]
158
+ )
159
 
160
  iface.launch(share=True)