-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
238 lines (225 loc) · 15.7 KB
/
main.py
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
import asyncio
import random
import re
import time
import discord
import os
from dotenv import load_dotenv
from discord import app_commands
from io import BytesIO
from fakeyou import FakeYou
from openai import AsyncOpenAI
from pydub import AudioSegment
def load_wav(path, start=None, end=None, gain=None):
seg = AudioSegment.from_wav(path)[start:end]
if gain is not None:
seg = seg.apply_gain(gain-seg.dBFS)
return seg
load_dotenv()
gpt = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
fy = FakeYou()
fy.login(os.getenv("FAKEYOU_USERNAME"), os.getenv("FAKEYOU_PASSWORD"))
client = discord.Client(intents=discord.Intents.default(), activity=discord.Game("Ready"), status=discord.Status.online)
tree = app_commands.CommandTree(client)
music_closing_theme = load_wav("music/closing_theme.wav", gain=-35)
music_tip_top_polka = load_wav("music/tip_top_polka.wav", gain=-35)
music_rake_hornpipe = load_wav("music/rake_hornpipe.wav", gain=-35)
music_seaweed = load_wav("music/seaweed.wav", gain=-35)
music_sneaky_snitch = load_wav("music/sneaky_snitch.wav", gain=-35)
music_better_call_saul = load_wav("music/better_call_saul.wav", start=50, end=18250, gain=-35)
sfx_steel_sting = load_wav("sfx/steel_sting.wav", start=100, end=-450, gain=-20)
sfx_boowomp = load_wav("sfx/boowomp.wav", start=750, end=1200, gain=-20)
sfx_disgusting = load_wav("sfx/disgusting.wav", start=100, end=-250, gain=-20)
sfx_vibe_link_b = load_wav("sfx/vibe_link_b.wav", start=50, gain=-20)
sfx_this_guy_stinks = load_wav("sfx/this_guy_stinks.wav", start=550, end=-100, gain=-20)
sfx_my_leg = load_wav("sfx/my_leg.wav", start=150, end=-2700, gain=-20)
sfx_you_what = load_wav("sfx/you_what.wav", start=150, gain=-20)
sfx_dolphin = load_wav("sfx/dolphin.wav", start=1050, end=-950, gain=-20)
sfx_transition = load_wav("sfx/transition.wav", start=200, gain=-20)
ambiance_day = load_wav("ambiance/day.wav", start=2000, end=-1000, gain=-45)
ambiance_night = load_wav("ambiance/night.wav", start=100, end=-4000, gain=-45)
ambiance_rain = load_wav("ambiance/rain.wav", start=1000, end=-1000, gain=-45)
voice_gary = load_wav("voice/gary.wav", end=6000)
silence_line = AudioSegment.silent(500)
silence_transition = AudioSegment.silent(1100)
silence_music = AudioSegment.silent(2450)
emoji_spongebob = os.getenv("EMOJI_SPONGEBOB")
emoji_patrick = os.getenv("EMOJI_PATRICK")
emoji_squidward = os.getenv("EMOJI_SQUIDWARD")
emoji_gary = os.getenv("EMOJI_GARY")
emoji_plankton = os.getenv("EMOJI_PLANKTON")
emoji_mrkrabs = os.getenv("EMOJI_MRKRABS")
emoji_karen = os.getenv("EMOJI_KAREN")
emoji_sandy = os.getenv("EMOJI_SANDY")
emoji_mrspuff = os.getenv("EMOJI_MRSPUFF")
emoji_squilliam = os.getenv("EMOJI_SQUILLIAM")
emoji_larry = os.getenv("EMOJI_LARRY")
emoji_bubblebass = os.getenv("EMOJI_BUBBLEBASS")
emoji_bubblebuddy = os.getenv("EMOJI_BUBBLEBUDDY")
emoji_frenchnarrator = os.getenv("EMOJI_FRENCHNARRATOR")
embed_ready = discord.Embed(title="Ready", color=0xf5f306).set_footer(text="Ready to generate.")
embed_error_permissions = discord.Embed(title="Generating...", description="# > Failed", color=0xf5f306).set_footer(text="Missing permissions.")
embed_error_failed = discord.Embed(title="Generating...", description="# > Failed", color=0xf5f306).set_footer(text="An error occurred.")
generating = False
progress = 0
cooldown = {}
@tree.command(name="generate", description="Generate an episode.")
@app_commands.describe(topic="Topic of episode.")
async def generate(inter: discord.Interaction, topic: str) -> None:
if not (inter.app_permissions.view_channel and inter.app_permissions.embed_links and inter.app_permissions.attach_files and inter.app_permissions.read_message_history and inter.app_permissions.use_external_emojis and inter.app_permissions.send_messages):
try:
await inter.response.send_message(embed=embed_error_permissions)
except:
pass
elif inter.user.id not in cooldown.keys() or time.time() - cooldown[inter.user.id] > 300:
global generating
if not generating:
generating = True
try:
global progress
progress = 0
await inter.response.send_message(embed=discord.Embed(title="Generating...", description=f"# > {progress}%", color=0xf5f306).set_footer(text=f"Please wait..."))
await client.change_presence(activity=discord.Game(f"Generating... {progress}%"), status=discord.Status.dnd)
response = await inter.original_response()
message = await response.channel.fetch_message(response.id)
completion = await gpt.completions.create(
model="gpt-3.5-turbo-instruct",
max_tokens=700,
prompt=f"Create a vulgar, nsfw, politically incorrect script for a scene from Spongebob where characters discuss a topic. Possible characters include SpongeBob, Patrick, Squidward, Mr. Krabs, Plankton, Karen, Sandy and very rarely Gary, Larry, Mrs. Puff, Squilliam, Bubble Bass, Bubble Buddy, and French Narrator. Use the format: Character: <dialogue>. Only reply with coherent character dialogue. Around 12 - 15 lines of dialogue with talking only. Create a two word title with format: Title: <title>. The topic is: {topic}"
)
lines = re.sub(r"(^|\s+)(\(+\S[^()]+\S\)+|\[+\S[^\[\]]+\S]+|\*+\S[^*]+\S\*+|<+\S[^<>]+\S>+|\{+\S[^{}]+\S}+|-+\S[^-]+\S-+|\|+\S[^|]+\S\|+|/+\S[^/]+\S/+|\\+\S[^\\]+\S\\+)(\s+|$)", " ", completion.choices[0].text).replace("\n\n", "\n").replace(":\n", ": ").replace(" ", " ").strip().split("\n")
remaining = len(lines)
title = re.sub(r"[^A-Za-z0-9 ]+", "", lines.pop(0)[6:]).strip().replace(" ", "_").upper().replace("I", "i")
completed = 1
progress = int(100 * (completed / remaining))
await message.edit(embed=discord.Embed(title="Generating...", description=f"# > {progress}%", color=0xf5f306).set_footer(text=f"Generated script."))
await client.change_presence(activity=discord.Game(f"Generating... {progress}%"), status=discord.Status.dnd)
transcript = []
combined = AudioSegment.empty()
loop = asyncio.get_running_loop()
for line in lines:
loud = False
line = discord.utils.escape_markdown(line).strip()
lower = line.lower()
if lower.startswith("spongebob:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[10:].strip(), "weight_5by9kjm8vr8xsp7abe8zvaxc8"), 180)
line = "- " + emoji_spongebob + line[10:]
elif lower.startswith("patrick:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[8:].strip(), "weight_154man2fzg19nrtc15drner7t"), 180)
line = "- " + emoji_patrick + line[8:]
elif lower.startswith("squidward:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[10:].strip(), "weight_y9arhnd7wjamezhqd27ksvmaz"), 180)
line = "- " + emoji_squidward + line[10:]
elif lower.startswith("loudward:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[9:].strip(), "weight_y9arhnd7wjamezhqd27ksvmaz"), 180)
line = "- " + emoji_squidward + line[9:]
loud = True
elif lower.startswith("gary:"):
line = "- " + emoji_gary + line[5:]
tts = None
seg = voice_gary
elif lower.startswith("plankton:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[9:].strip(), "weight_ahxbf2104ngsgyegncaefyy6j"), 180)
line = "- " + emoji_plankton + line[9:]
elif lower.startswith("mr. krabs:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[10:].strip(), "weight_5bxbp9xqy61svfx03b25ezmwx"), 180)
line = "- " + emoji_mrkrabs + line[10:]
elif lower.startswith("karen:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[6:].strip(), "weight_eckp92cd68r4yk68n6re3fwcb"), 180)
line = "- " + emoji_karen + line[6:]
elif lower.startswith("sandy:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[6:].strip(), "weight_tzgp5df2xzwz7y7jzz7at96jf"), 180)
line = "- " + emoji_sandy + line[6:]
elif lower.startswith("mrs. puff:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[10:].strip(), "weight_129qhgze57zhndkkcq83e6b2a"), 180)
line = "- " + emoji_mrspuff + line[10:]
elif lower.startswith("squilliam:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[10:].strip(), "weight_zmjv8223ed6wx1fp234c79v9s"), 180)
line = "- " + emoji_squilliam + line[10:]
elif lower.startswith("larry:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[6:].strip(), "weight_k7qvaffwsft6vxbcps4wbyj58"), 180)
line = "- " + emoji_larry + line[6:]
elif lower.startswith("bubble bass:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[12:].strip(), "weight_h9g7rh6tj2hvfezrz8gjs4gwa"), 180)
line = "- " + emoji_bubblebass + line[12:]
elif lower.startswith("bubble buddy:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[13:].strip(), "weight_sbr0372ysxbdahcvej96axy1t"), 180)
line = "- " + emoji_bubblebuddy + line[13:]
elif lower.startswith("french narrator:"):
tts = await asyncio.wait_for(loop.run_in_executor(None, fy.say, line[16:].strip(), "weight_edzcfmq6y0vj7pte9pzhq5b6j"), 180)
line = "- " + emoji_frenchnarrator + line[16:]
else:
remaining -= 1
progress = int(100 * (completed / remaining))
await message.edit(embed=discord.Embed(title="Generating...", description=f"# > {progress}%", color=0xf5f306).set_footer(text=f"Skipped line."))
await client.change_presence(activity=discord.Game(f"Generating... {progress}%"), status=discord.Status.dnd)
continue
transcript.append(line)
if tts is None:
remaining -= 1
else:
with BytesIO(tts.content) as wav:
seg = AudioSegment.from_wav(wav)
await asyncio.sleep(10)
completed += 1
if random.randrange(100) > 0 and not loud:
seg = seg.apply_gain(-15-seg.dBFS)
else:
seg = seg.apply_gain(-seg.dBFS)
combined = combined.append(seg, 0)
if random.randrange(10) > 0 and not line.endswith("-"):
combined = combined.append(silence_line, 0)
progress = int(100 * (completed / remaining))
await message.edit(embed=discord.Embed(title="Generating...", description=f"# > {progress}%", color=0xf5f306).set_footer(text=f"Synthesized line {completed-1}/{remaining-1}."))
await client.change_presence(activity=discord.Game(f"Generating... {progress}%"), status=discord.Status.dnd)
sfx = random.choice([sfx_steel_sting, sfx_boowomp, sfx_disgusting, sfx_vibe_link_b, sfx_this_guy_stinks, sfx_my_leg, sfx_you_what, sfx_dolphin])
music = random.choices([music_closing_theme, music_tip_top_polka, music_rake_hornpipe, music_seaweed, music_sneaky_snitch, music_better_call_saul], [10, 10, 10, 10, 1, 1])[0]
music_loop = silence_music.append(music.fade_in(10000), 0)
while len(music_loop) < len(combined):
music_loop = music_loop.append(music, 0)
if random.randrange(3) > 0:
ambiance = random.choice([ambiance_day, ambiance_night])
ambiance_loop = ambiance.fade_in(500)
while len(ambiance_loop) < len(combined):
ambiance_loop = ambiance_loop.append(ambiance, 0)
else:
ambiance_loop = AudioSegment.empty()
if random.randrange(5) > 0:
rain_loop = AudioSegment.empty()
else:
rain_loop = ambiance_rain.fade_in(500)
while len(rain_loop) < len(combined):
rain_loop = rain_loop.append(ambiance_rain, 0)
final = silence_transition.append(combined.overlay(sfx, random.randrange(len(combined) - len(sfx))).append(silence_line, 0).overlay(music_loop).overlay(ambiance_loop).overlay(rain_loop), 0).overlay(sfx_transition).fade_out(500)
with BytesIO() as episode:
final.export(episode, "mp3")
await message.edit(content="***[Donate to support AI Sponge Lite!](https://github.com/sponsors/jeremynoesen)***", embed=discord.Embed(description="\n".join(transcript), color=0xf5f306), attachments=[discord.File(episode, f"{title}.mp3")])
await client.change_presence(activity=discord.Game("Ready"), status=discord.Status.online)
cooldown[inter.user.id] = time.time()
except:
try:
await message.edit(content=None, embed=embed_error_failed)
except:
try:
await inter.edit_original_response(content=None, embed=embed_error_failed)
except:
pass
await client.change_presence(activity=discord.Game("Ready"), status=discord.Status.online)
generating = False
else:
await inter.response.send_message(ephemeral=True, delete_after=10, embed=discord.Embed(title="Generating", description=f"# > {progress}%", color=0xf5f306).set_footer(text="Generating an episode."))
else:
await inter.response.send_message(ephemeral=True, delete_after=10, embed=discord.Embed(title=f"Cooldown", description=f"# > {int((300 - (time.time() - cooldown[inter.user.id])) / 60)}m {int((300 - (time.time() - cooldown[inter.user.id])) % 60)}s", color=0xf5f306).set_footer(text="You're on cooldown."))
@tree.command(name="status", description="Check if an episode can be generated.")
async def status(inter: discord.Interaction) -> None:
if inter.user.id not in cooldown.keys() or time.time() - cooldown[inter.user.id] > 300:
if generating:
await inter.response.send_message(ephemeral=True, delete_after=10, embed=discord.Embed(title="Generating", description=f"# > {progress}%", color=0xf5f306).set_footer(text="Generating an episode."))
else:
await inter.response.send_message(ephemeral=True, delete_after=10, embed=embed_ready)
else:
await inter.response.send_message(ephemeral=True, delete_after=10, embed=discord.Embed(title=f"Cooldown", description=f"# > {int((300 - (time.time() - cooldown[inter.user.id])) / 60)}m {int((300 - (time.time() - cooldown[inter.user.id])) % 60)}s", color=0xf5f306).set_footer(text="You're on cooldown."))
@client.event
async def on_ready():
await tree.sync()
client.run(os.getenv("DISCORD_BOT_TOKEN"))