zarox commited on
Commit
7f410e3
·
verified ·
1 Parent(s): 83daf9e
Files changed (1) hide show
  1. app.py +46 -274
app.py CHANGED
@@ -1,247 +1,54 @@
1
- import io
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
3
- import sys
4
- import time
5
  import secrets
6
- import asyncio
7
- import threading
8
- import traceback
9
  import gradio as gr
10
-
11
- from io import BytesIO
12
- from fusion import Fusion
13
- from datetime import datetime
14
- from telethon.tl.tlobject import TLObject
15
- from telethon import TelegramClient, events, Button, types
16
-
17
-
18
- API_ID = os.environ.get("API_ID")
19
- API_HASH = os.environ.get("API_HASH")
20
- BOT_TOKEN = os.environ.get("BOT_TOKEN")
21
-
22
-
23
- client = TelegramClient('session_name', API_ID, API_HASH)
24
-
25
-
26
- def utc_to_local(utc_datetime):
27
- now_timestamp = time.time()
28
- offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(
29
- now_timestamp
30
- )
31
- return utc_datetime + offset
32
-
33
- def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64):
34
- result = []
35
- if isinstance(obj, TLObject):
36
- obj = obj.to_dict()
37
-
38
- if isinstance(obj, dict):
39
- if not obj:
40
- return "dict:"
41
- items = obj.items()
42
- has_items = len(items) > 1
43
- has_multiple_items = len(items) > 2
44
- result.append(obj.get("_", "dict") + (":" if has_items else ""))
45
- if has_multiple_items:
46
- result.append("\n")
47
- indent += 2
48
- for k, v in items:
49
- if k == "_" or v is None:
50
- continue
51
- formatted = yaml_format(v, indent)
52
- if not formatted.strip():
53
- continue
54
- result.append(" " * (indent if has_multiple_items else 1))
55
- result.append(f"{k}:")
56
- if not formatted[0].isspace():
57
- result.append(" ")
58
- result.append(f"{formatted}")
59
- result.append("\n")
60
- if has_items:
61
- result.pop()
62
- if has_multiple_items:
63
- indent -= 2
64
- elif isinstance(obj, str):
65
- result = repr(obj[:max_str_len])
66
- if len(obj) > max_str_len:
67
- result += "…"
68
- return result
69
- elif isinstance(obj, bytes):
70
- if all(0x20 <= c < 0x7F for c in obj):
71
- return repr(obj)
72
- return "<…>" if len(obj) > max_byte_len else " ".join(f"{b:02X}" for b in obj)
73
- elif isinstance(obj, datetime):
74
- return utc_to_local(obj).strftime("%Y-%m-%d %H:%M:%S")
75
- elif hasattr(obj, "__iter__"):
76
- result.append("\n")
77
- indent += 2
78
- for x in obj:
79
- result.append(f"{' ' * indent}- {yaml_format(x, indent + 2)}")
80
- result.append("\n")
81
- result.pop()
82
- indent -= 2
83
- else:
84
- return repr(obj)
85
- return "".join(result)
86
-
87
- async def aexec(code, smessatatus):
88
- message = event = smessatatus
89
- p = lambda _x: print(yaml_format(_x))
90
- reply = await event.get_reply_message()
91
- exec("async def __aexec(message, event , reply, client, p, chat): "
92
- + "".join(f"\n {l}" for l in code.split("\n")))
93
-
94
- return await locals()["__aexec"](
95
- message, event, reply, message.client, p, message.chat_id
96
- )
97
-
98
- @client.on(events.NewMessage(incoming=True, pattern="(/)?eval(?:\s|$)([\s\S]*)"))
99
- @client.on(events.MessageEdited(incoming=True, pattern="(/)?eval(?:\s|$)([\s\S]*)"))
100
- async def evalution(event):
101
- if event.sender.id != 6034486765: return
102
-
103
- cmd = "".join(event.message.message.split(maxsplit=1)[1:])
104
- if not cmd:
105
- return await event.reply("`Give something to run! ...`")
106
- eval_ = await event.reply("`Evalution in process ...`")
107
- old_stderr = sys.stderr
108
- old_stdout = sys.stdout
109
- redirected_output = sys.stdout = io.StringIO()
110
- redirected_error = sys.stderr = io.StringIO()
111
- stdout, stderr, exc = None, None, None
112
- try:
113
- await aexec(cmd, event)
114
- except Exception:
115
- exc = traceback.format_exc()
116
- stdout = redirected_output.getvalue()
117
- stderr = redirected_error.getvalue()
118
- sys.stdout = old_stdout
119
- sys.stderr = old_stderr
120
- evaluation = ""
121
- if exc:
122
- evaluation = exc
123
- elif stderr:
124
- evaluation = stderr
125
- elif stdout:
126
- evaluation = stdout
127
- else:
128
- evaluation = "Success"
129
- final_output = (f"**• Syntax : **\n```{cmd}``` \n\n**• Output :**\n```{evaluation}``` \n")
130
- await eval_.edit(text=final_output)
131
-
132
-
133
- get_duration = lambda x: int(len(Fusion.from_file(x))/1000.0)
134
- states = {}
135
-
136
- @client.on(events.NewMessage(pattern='/start'))
137
- async def start_handler(event):
138
- await event.reply("Welcome to AudioFusion Bot! Send me an audio file, and I'll apply effects for you.")
139
-
140
- buttons = [
141
- [Button.inline('Slowed', b'slowed'), Button.inline('8D', b'8d')],
142
- [Button.inline('Reverb', b'reverb'), Button.inline('Reverse', b'reverse')],
143
- [Button.inline('Volume', b'volume'), Button.inline('Speedup', b'speedup')],
144
- [Button.inline('Preview', b'preview')],
145
- [Button.inline('Send', b'send')],
146
- ]
147
-
148
- @client.on(events.NewMessage(pattern='/buttons'))
149
- async def buttons_handler(event):
150
- user_id = event.sender_id
151
-
152
- # Download the audio file and store it in the user's state
153
- reply_message = await event.get_reply_message()
154
- if not reply_message or not reply_message.file:
155
- await event.reply("Please reply to an audio file.")
156
- return
157
-
158
- audio_file = BytesIO()
159
- await event.client.download_media(reply_message, audio_file)
160
- audio_file.seek(0)
161
-
162
- # Store the audio file in the user's state
163
- states[user_id] = {'audio': audio_file}
164
-
165
- await client.send_file(event.chat_id, file="image.jpg", caption="Preview the current modification:", buttons=buttons)
166
-
167
-
168
- @client.on(events.CallbackQuery(pattern=b'(slowed|8d|reverb|reverse|trim|volume|speedup)'))
169
- async def audio_effect_handler(event):
170
- user_id = event.sender_id
171
- if user_id not in states or not states[user_id]:
172
- await event.answer("No audio file found. Please use /buttons command to upload an audio file.")
173
- return
174
-
175
- # Retrieve the audio file from the user's state
176
- audio_file = states[user_id]['audio']
177
-
178
- query = event.pattern_match.group(1).decode("UTF-8")
179
- sound = Fusion.from_file(audio_file, format="mp3")
180
- if query == 'slowed':
181
- modified_sound = await Fusion.effectSlowed(sound)
182
- elif query == 'speedup':
183
- modified_sound = await Fusion.effectSlowed(sound, 1.1)
184
- elif query == '8d':
185
- modified_sound = await Fusion.effect8D(sound)
186
- elif query == 'reverb':
187
- modified_sound = await Fusion.effectReverb(sound)
188
- elif query == 'reverse':
189
- modified_sound = sound.reverse()
190
- else:
191
- return await event.answer("INvalid for now...")
192
-
193
- audio_file = BytesIO()
194
- audio = modified_sound.export(audio_file, format="mp3")
195
- audio.seek(0)
196
- # Update the user's state with the modified sound
197
- states[user_id]['audio'] = audio
198
-
199
- await event.answer("Effect applied. Click /send to receive the modified audio file.", alert=True)
200
-
201
-
202
-
203
- @client.on(events.CallbackQuery(pattern=b'preview'))
204
- async def preview_handler(event):
205
- user_id = event.sender_id
206
- if user_id in states and states[user_id]:
207
- # Send the current modification for preview
208
- output_file_name = f"{user_id}_preview"
209
- output_file = await Fusion.saveSound(states[user_id]['audio'], output_file_name)
210
- await event.edit("`Uploading...`", buttons=buttons)
211
- # Edit the message and send the audio file in the edited message
212
- await event.edit(file=output_file, text="`Preview the current modification:`", buttons=buttons)
213
-
214
- # Clean up - remove the saved preview audio file
215
- os.remove(output_file)
216
- else:
217
- await event.answer("No modified audio file found. Please apply an effect first.", alert=True)
218
-
219
-
220
- @client.on(events.CallbackQuery(pattern=b'send'))
221
- async def send_handler(event):
222
- user_id = event.sender_id
223
- if user_id in states and states[user_id]:
224
- audio_file = states[user_id]['audio']
225
-
226
- audio_file.name = "AudioFusion.mp3"
227
- duration = int(len(Fusion.from_file(audio_file))/1000.0)
228
- audio_file.seek(0)
229
- await client.send_file(event.chat_id, file=audio_file)
230
- # Clean up - remove the user's state and the saved audio file
231
- del states[user_id]
232
- # os.remove(output_file)
233
- await event.delete()
234
- else:
235
- await event.answer("No modified audio file found. Please apply an effect first.")
236
-
237
-
238
 
239
  def process_audio(input_file,
240
  effect_8d, pan_boundary, jump_percentage, time_l_to_r, volume_multiplier,
241
  effect_slowed, speed_multiplier,
242
  effect_reverb, room_size, damping, width, wet_level, dry_level
243
  ):
244
- # Load the sound file
245
  sound = Fusion.loadSound(input_file)
246
  os.remove(os.path.abspath(input_file))
247
  effects_str = []
@@ -260,36 +67,12 @@ def process_audio(input_file,
260
  output_file = f"{input_file} {' + '.join(effects_str)} - {'By AudioFusion'}"
261
 
262
  # Save the processed sound and return the output file
263
- return Fusion.saveSound(sound, output_file)
264
-
265
-
266
-
267
- before_text = """<div align="center">
268
- <h1>AudioFusion</h1>
269
- <i>Add a touch of uniqueness with various customizable effects like slowed and reverb.</i>
270
- </div>
271
- <hr>"""
272
-
273
- after_text = """<hr>
274
- PR in [github](https://github.com/MineisZarox/AudioFusion) repository beta branch are always welcome.
275
-
276
- <h3>Todo</h3>
277
-
278
- \# Acapella Extractor<br>
279
- \# Karoke Maker<br>
280
- \# Bass Booster<br>
281
- \# Volume Booster<br>
282
 
283
 
284
- <h3>Inspiration & Credits</h3>
285
-
286
- - Special thanks to [Jiaaro](https://github.com/jiaaro) for pydub. AudioFusion is mainly wrapped around pydub
287
-
288
- - My Soundscapes of Serenity - [Because](https://t.me/bcuzwhynot)
289
- """
290
-
291
  with gr.Blocks(title="Audio Fusion") as iface:
292
- gr.Markdown(before_text)
293
  input_audio = gr.Audio(label="Upload your music file", type="filepath")
294
 
295
  # SLowed Effect and its arguments
@@ -353,18 +136,7 @@ with gr.Blocks(title="Audio Fusion") as iface:
353
  inputs = [input_audio, dimension_check, pan, jump, time, volx, speed_check, speed, reverb_check, room, damp, width, wet, dry]
354
  output = [gr.Audio(label="Download processed music", type="filepath")]
355
 
356
- gr.Markdown(after_text)
357
-
358
  btnClear.add(components=output)
359
  btnRun.click(fn=process_audio, inputs=inputs, outputs=output, api_name="AudioFusion")
360
 
361
- async def initiation():
362
- await client.send_message(-1001662130485, "**Hugging is Running.**", buttons=[(Button.url("Execal", "https://t.me/execal"),)],)
363
-
364
- if __name__ == '__main__':
365
- client.start(bot_token=BOT_TOKEN)
366
- client.loop.run_until_complete(initiation())
367
- threading.Thread(target=iface.launch).start() #(share=False)
368
- print("Bot started succefully")
369
- client.run_until_disconnected()
370
-
 
1
+ Hugging Face's logo
2
+ Hugging Face
3
+ Search models, datasets, users...
4
+ Models
5
+ Datasets
6
+ Spaces
7
+ Posts
8
+ Docs
9
+ Pricing
10
+
11
+
12
+
13
+ Spaces:
14
+
15
+ zarox
16
+ /
17
+ AudioFusion
18
+
19
+
20
+ like
21
+ 6
22
+
23
+ App
24
+ Files
25
+ Community
26
+ Settings
27
+ AudioFusion
28
+ /
29
+ app.py
30
+
31
+ zarox's picture
32
+ zarox
33
+ UPDATE
34
+ 16d22f2
35
+ 5 months ago
36
+ raw
37
+ history
38
+ blame
39
+ No virus
40
+ 4.32 kB
41
  import os
 
 
42
  import secrets
 
 
 
43
  import gradio as gr
44
+ from AudioFusion import Fusion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def process_audio(input_file,
47
  effect_8d, pan_boundary, jump_percentage, time_l_to_r, volume_multiplier,
48
  effect_slowed, speed_multiplier,
49
  effect_reverb, room_size, damping, width, wet_level, dry_level
50
  ):
51
+ # Load the sound file
52
  sound = Fusion.loadSound(input_file)
53
  os.remove(os.path.abspath(input_file))
54
  effects_str = []
 
67
  output_file = f"{input_file} {' + '.join(effects_str)} - {'By AudioFusion'}"
68
 
69
  # Save the processed sound and return the output file
70
+ output = Fusion.saveSound(sound, output_file)
71
+ return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
 
 
 
 
 
 
 
 
74
  with gr.Blocks(title="Audio Fusion") as iface:
75
+ gr.Markdown("<p align='center'><h1>Audio Fusion</h1></p>")
76
  input_audio = gr.Audio(label="Upload your music file", type="filepath")
77
 
78
  # SLowed Effect and its arguments
 
136
  inputs = [input_audio, dimension_check, pan, jump, time, volx, speed_check, speed, reverb_check, room, damp, width, wet, dry]
137
  output = [gr.Audio(label="Download processed music", type="filepath")]
138
 
 
 
139
  btnClear.add(components=output)
140
  btnRun.click(fn=process_audio, inputs=inputs, outputs=output, api_name="AudioFusion")
141
 
142
+ iface.launch(share=False)