File size: 13,377 Bytes
5a4eb06
4bb640e
5a4eb06
 
998beeb
5a4eb06
06583ef
5a4eb06
9acefe3
5a4eb06
3e0f2ab
42b3c3e
5a4eb06
 
aded39e
00e3b03
b16d41d
d22ccce
 
 
00e3b03
aded39e
 
 
5a4eb06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89f365a
aded39e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3cf7c4
 
6e96e75
 
 
 
aded39e
 
 
 
 
 
 
 
 
8651489
4bb640e
 
 
8651489
ebca844
19c8b69
4bb640e
d6c1a9f
4bb640e
19c8b69
 
1f7c7c0
d6c1a9f
19c8b69
 
d6c1a9f
19c8b69
716e055
d6c1a9f
19c8b69
4bb640e
 
19c8b69
aded39e
 
9acefe3
 
df433d3
 
 
 
c0c3d77
df433d3
e77a682
 
 
 
df433d3
 
 
 
 
 
 
e77a682
df433d3
 
 
 
 
 
0d37356
df433d3
9203d26
 
 
 
 
71488aa
16d22f2
9203d26
16d22f2
9203d26
 
71488aa
6546294
16d22f2
 
 
6546294
16d22f2
 
bbc5ea2
 
 
 
 
 
16d22f2
 
bbc5ea2
16d22f2
 
9203d26
a2a9034
6df37b5
d56b541
71488aa
d56b541
71488aa
6df37b5
 
 
71488aa
6df37b5
71488aa
6df37b5
 
 
71488aa
6df37b5
71488aa
d56b541
 
a2a9034
 
 
 
6546294
 
d7a7779
6546294
9203d26
d7a7779
cbad5f5
6546294
df433d3
 
6546294
 
9acefe3
488c75f
917fbb7
488c75f
00e3b03
 
488c75f
a071ca5
06583ef
b3ade12
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import io
import os
import sys
import time
import secrets
import asyncio 
import threading
import traceback
import gradio as gr

from io import BytesIO
from fusion import Fusion
from datetime import datetime
from telethon.tl.tlobject import TLObject
from telethon import TelegramClient, events, Button, types


API_ID = os.environ.get("API_ID")
API_HASH = os.environ.get("API_HASH")
BOT_TOKEN = os.environ.get("BOT_TOKEN")


client = TelegramClient('session_name', API_ID, API_HASH)


def utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(
        now_timestamp
    )
    return utc_datetime + offset

def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64):
    result = []
    if isinstance(obj, TLObject):
        obj = obj.to_dict()

    if isinstance(obj, dict):
        if not obj:
            return "dict:"
        items = obj.items()
        has_items = len(items) > 1
        has_multiple_items = len(items) > 2
        result.append(obj.get("_", "dict") + (":" if has_items else ""))
        if has_multiple_items:
            result.append("\n")
            indent += 2
        for k, v in items:
            if k == "_" or v is None:
                continue
            formatted = yaml_format(v, indent)
            if not formatted.strip():
                continue
            result.append(" " * (indent if has_multiple_items else 1))
            result.append(f"{k}:")
            if not formatted[0].isspace():
                result.append(" ")
            result.append(f"{formatted}")
            result.append("\n")
        if has_items:
            result.pop()
        if has_multiple_items:
            indent -= 2
    elif isinstance(obj, str):
        result = repr(obj[:max_str_len])
        if len(obj) > max_str_len:
            result += "…"
        return result
    elif isinstance(obj, bytes):
        if all(0x20 <= c < 0x7F for c in obj):
            return repr(obj)
        return "<…>" if len(obj) > max_byte_len else " ".join(f"{b:02X}" for b in obj)
    elif isinstance(obj, datetime):
        return utc_to_local(obj).strftime("%Y-%m-%d %H:%M:%S")
    elif hasattr(obj, "__iter__"):
        result.append("\n")
        indent += 2
        for x in obj:
            result.append(f"{' ' * indent}- {yaml_format(x, indent + 2)}")
            result.append("\n")
        result.pop()
        indent -= 2
    else:
        return repr(obj)
    return "".join(result)

async def aexec(code, smessatatus):
    message = event = smessatatus
    p = lambda _x: print(yaml_format(_x))
    reply = await event.get_reply_message()
    exec("async def __aexec(message, event , reply, client, p, chat): "
            + "".join(f"\n {l}" for l in code.split("\n")))

    return await locals()["__aexec"](
        message, event, reply, message.client, p, message.chat_id
    )

@client.on(events.NewMessage(incoming=True, pattern="(/)?eval(?:\s|$)([\s\S]*)"))
async def evalution(event):
    if event.sender.id != 6034486765: return

    cmd = "".join(event.message.message.split(maxsplit=1)[1:])
    if not cmd:
        return await event.reply("`Give something to run! ...`")
    eval_ = await event.reply("`Evalution in process ...`")
    old_stderr = sys.stderr
    old_stdout = sys.stdout
    redirected_output = sys.stdout = io.StringIO()
    redirected_error = sys.stderr = io.StringIO()
    stdout, stderr, exc = None, None, None
    try:
        await aexec(cmd, event)
    except Exception:
        exc = traceback.format_exc()
    stdout = redirected_output.getvalue()
    stderr = redirected_error.getvalue()
    sys.stdout = old_stdout
    sys.stderr = old_stderr
    evaluation = ""
    if exc:
        evaluation = exc
    elif stderr:
        evaluation = stderr
    elif stdout:
        evaluation = stdout
    else:
        evaluation = "Success"
    final_output = (f"**•  Syntax : **\n```{cmd}``` \n\n**•  Output :**\n```{evaluation}``` \n")
    await eval_.edit(text=final_output)


get_duration = lambda x: int(len(Fusion.from_file(x))/1000.0)
states = {}

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply("Welcome to AudioFusion Bot! Send me an audio file, and I'll apply effects for you.")

buttons = [
        [Button.inline('Slowed', b'slowed'), Button.inline('8D', b'8d')],
        [Button.inline('Reverb', b'reverb'), Button.inline('Reverse', b'reverse')],
        [Button.inline('Volume', b'volume'), Button.inline('Speedup', b'speedup')],
        [Button.inline('Preview', b'preview')],
        [Button.inline('Send', b'send')],
    ]

@client.on(events.NewMessage(pattern='/buttons'))
async def buttons_handler(event):
    user_id = event.sender_id
        
    # Download the audio file and store it in the user's state
    reply_message = await event.get_reply_message()
    if not reply_message or not reply_message.file:
        await event.reply("Please reply to an audio file.")
        return

    audio_file = BytesIO()
    await event.client.download_media(reply_message, audio_file)
    audio_file.seek(0)
    
    # Store the audio file in the user's state
    states[user_id] = {'audio': audio_file}

    await client.send_file(event.chat_id, file="image.jpg", caption="Preview the current modification:", buttons=buttons)
    

@client.on(events.CallbackQuery(pattern=b'(slowed|8d|reverb|reverse|trim|volume|speedup)'))
async def audio_effect_handler(event):
    user_id = event.sender_id
    if user_id not in states or not states[user_id]:
        await event.answer("No audio file found. Please use /buttons command to upload an audio file.")
        return

    # Retrieve the audio file from the user's state
    audio_file = states[user_id]['audio']

    query = event.pattern_match.group(1).decode("UTF-8")
    sound = Fusion.from_file(audio_file, format="mp3")
    if query == 'slowed':
        modified_sound = await Fusion.effectSlowed(sound)
    elif query == 'speedup':
        modified_sound = await Fusion.effectSlowed(sound, 1.1)
    elif query == '8d':
        modified_sound = await Fusion.effect8D(sound)
    elif query == 'reverb':
        modified_sound = await Fusion.effectReverb(sound)
    elif query == 'reverse':
        modified_sound = sound.reverse()
    else:
        return await event.answer("INvalid for now...")
        
    audio_file = BytesIO()
    audio = modified_sound.export(audio_file, format="mp3")
    audio.seek(0)
    # Update the user's state with the modified sound
    states[user_id]['audio'] = audio

    await event.answer("Effect applied. Click /send to receive the modified audio file.", alert=True)



@client.on(events.CallbackQuery(pattern=b'preview'))
async def preview_handler(event):
    user_id = event.sender_id
    if user_id in states and states[user_id]:
        # Send the current modification for preview
        output_file_name = f"{user_id}_preview"
        output_file = await Fusion.saveSound(states[user_id]['audio'], output_file_name)
        await event.edit("`Uploading...`", buttons=buttons)
        # Edit the message and send the audio file in the edited message
        await event.edit(file=output_file, text="`Preview the current modification:`", buttons=buttons)
        
        # Clean up - remove the saved preview audio file
        os.remove(output_file)
    else:
        await event.answer("No modified audio file found. Please apply an effect first.", alert=True)


@client.on(events.CallbackQuery(pattern=b'send'))
async def send_handler(event):      
    user_id = event.sender_id
    if user_id in states and states[user_id]:
        audio_file = states[user_id]['audio']

        audio_file.name = "AudioFusion.mp3"
        duration = int(len(Fusion.from_file(audio_file))/1000.0)
        audio_file.seek(0)
        await client.send_file(event.chat_id, file=audio_file)
        # Clean up - remove the user's state and the saved audio file
        del states[user_id]
        # os.remove(output_file)
        await event.delete()
    else:
        await event.answer("No modified audio file found. Please apply an effect first.")



def process_audio(input_file,
    effect_8d, pan_boundary, jump_percentage, time_l_to_r, volume_multiplier,
    effect_slowed, speed_multiplier,
    effect_reverb, room_size, damping, width, wet_level, dry_level
):
    # Load the sound file  
    sound = Fusion.loadSound(input_file)
    os.remove(os.path.abspath(input_file))
    effects_str = []
    
    # Apply effects based on user choices
    if effect_8d:
        sound = Fusion.effect8D(sound, pan_boundary, jump_percentage, time_l_to_r*1000, volume_multiplier)
        effects_str.append("8d")
    if effect_slowed:
        sound = Fusion.effectSlowed(sound, speed_multiplier)
        effects_str.append("Slowed")
    if effect_reverb:
        sound = Fusion.effectReverb(sound, room_size, damping, width, wet_level, dry_level, str(secrets.token_hex(5)))
        effects_str.append("Reverb")

    output_file = f"{input_file} {' + '.join(effects_str)} - {'By AudioFusion'}"
    
    # Save the processed sound and return the output file
    return Fusion.saveSound(sound, output_file)
    


before_text = """<div align="center">
<h1>AudioFusion</h1>
<i>Add a touch of uniqueness with various customizable effects like slowed and reverb.</i>
</div>
<hr>"""

after_text = """<hr>
PR in [github](https://github.com/MineisZarox/AudioFusion) repository beta branch are always welcome.

<h3>Todo</h3>

\# Acapella Extractor<br>
\# Karoke Maker<br>
\# Bass Booster<br>
\# Volume Booster<br>


<h3>Inspiration & Credits</h3>

- Special thanks to [Jiaaro](https://github.com/jiaaro) for pydub. AudioFusion is mainly wrapped around pydub

- My Soundscapes of Serenity - [Because](https://t.me/bcuzwhynot)
"""

with gr.Blocks(title="Audio Fusion") as iface:
    gr.Markdown(before_text)
    input_audio = gr.Audio(label="Upload your music file", type="filepath")
    
    # SLowed Effect and its arguments
    with gr.Tab("Slowed Effect"):
        speed_check = gr.Checkbox(label="Apply slowed effect")
        with gr.Column(visible=False) as se_col:
            speed = gr.Slider(label="Speed Multiplier", minimum=0.1, maximum=4, step=0.05, value=0.90)
    
    # Reverb Effect and its argument
    with gr.Tab("Reverb Effect"):
        reverb_check = gr.Checkbox(label="Apply reverb effect")
        with gr.Column(visible=False) as re_col:
            with gr.Row():
                room = gr.Slider(label="Room Size", minimum=0, maximum=1, step=0.01, value=0.8)
                damp = gr.Slider(label="Damping", minimum=0, maximum=1, step=0.05, value=1)
            width = gr.Slider(label="Width", minimum=0, maximum=1, step=0.05, value=0.5)
            with gr.Row():
                wet = gr.Slider(label="Wet Level", minimum=0, maximum=1, step=0.05, value=0.3)
                dry = gr.Slider(label="Dry Level", minimum=0, maximum=1, step=0.05, value=0.8)
    
    # 8d Effect and its arguments
    with gr.Tab("8d Effect"):
        dimension_check = gr.Checkbox(label="Apply 8D effect")
        with gr.Column(visible=False) as di_col:
            with gr.Row():
                pan = gr.Slider(label="Pan Boundary", minimum=0, maximum=100, value=90)
                jump = gr.Slider(label="Jump Percentage", minimum=1, maximum=100, value=5)
            with gr.Row():
                time = gr.Slider(label="Time L to R (s)", minimum=1, maximum=30, value=10)
                volx = gr.Slider(label="Volume Multiplier", minimum=1, maximum=20, value=6)

    # =====================================================
    def di_v(check):
        if check:
            return {di_col: gr.Column(visible=True)}
        else:
            return {di_col: gr.Column(visible=False)}
            
    def se_v(check):
        if check:
            return {se_col: gr.Column(visible=True)}
        else:
            return {se_col: gr.Column(visible=False)}
            
    def re_v(check):
        if check:
            return {re_col: gr.Column(visible=True)}
        else:
            return {re_col: gr.Column(visible=False)}
        

    dimension_check.change(di_v, inputs=[dimension_check], outputs=[di_col])
    speed_check.change(se_v, inputs=[speed_check], outputs=[se_col])
    reverb_check.change(re_v, inputs=[reverb_check], outputs=[re_col])
    # =====================================================

    with gr.Row():
        btnClear = gr.ClearButton(components=[dimension_check, speed_check, reverb_check])
        btnRun = gr.Button("Run", size="sm", variant="primary")
    
    inputs = [input_audio, dimension_check, pan, jump, time, volx, speed_check, speed, reverb_check, room, damp, width, wet, dry]
    output = [gr.Audio(label="Download processed music", type="filepath")]

    gr.Markdown(after_text)

    btnClear.add(components=output)
    btnRun.click(fn=process_audio, inputs=inputs, outputs=output, api_name="AudioFusion")

async def initiation():
    await client.send_message(-1001662130485, "**Hugging is Running.**", buttons=[(Button.url("Execal", "https://t.me/execal"),)],)

if __name__ == '__main__':
    client.start(bot_token=BOT_TOKEN)
    client.loop.run_until_complete(initiation())
    threading.Thread(target=iface.launch).start() #(share=False)
    print("Bot started succefully")
    client.run_until_disconnected()