File size: 25,685 Bytes
5546580
 
7fa9e07
f42e7d1
fe6d40e
7fa9e07
 
 
 
 
 
11ad260
 
 
7fa9e07
fe6d40e
956c50d
3f98253
448abf5
 
 
4c610fc
e0461c3
11ad260
b56f69c
 
c378b04
9650ea7
11ad260
 
d7fdc0e
11ad260
9650ea7
fad843f
a697e01
06ddfd4
 
3c5ffd1
06ddfd4
 
2afeadf
69dff14
f42e7d1
41e66b2
 
 
 
3c5ffd1
 
 
69dff14
3c5ffd1
f42e7d1
3c5ffd1
 
 
 
 
 
 
 
41e66b2
3c5ffd1
 
 
 
 
 
2afeadf
3189729
9b3563d
a661bc3
3189729
 
3c5ffd1
 
69dff14
3c5ffd1
 
3d12a7c
88d5346
04b6845
4c610fc
3c5ffd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f87b648
 
3c5ffd1
bf54bc6
3c5ffd1
 
 
 
41e66b2
8d38d87
448abf5
 
 
 
f42e7d1
448abf5
f42e7d1
 
 
 
448abf5
5546580
11ad260
5546580
dbb572b
5546580
dbb572b
 
740e062
eb0988a
cd3f2d7
dbb572b
8d38d87
 
 
3c5ffd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54389af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
import discord
import os
import threading
from threading import active_count
import gradio as gr 
import requests
import json
import random
import time
import re
from discord import Embed, Color
from discord.ext import commands
from gradio_client import Client
from PIL import Image
import asyncio
import shutil # for doing image movement magic 
import concurrent.futures
# reboot
import multiprocessing


#semaphore = asyncio.Semaphore(2)

DFIF_TOKEN = os.getenv('HF_TOKEN')
DISCORD_TOKEN = os.environ.get("GRADIOTEST_TOKEN", None)

jojogan = Client("akhaliq/JoJoGAN", DFIF_TOKEN)

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)


@bot.command()
async def active(ctx):
    # get the number of active threads
    activethreadcount = active_count()
    await ctx.message.reply(f'active threads: {activethreadcount}')
    
@bot.command()
async def jojo(ctx):

    # get the number of active threads
    activethreadcount = active_count()
    # report the number of active threads
    print(activethreadcount)
    start_time = time.time()
    attachment = await discord_before(ctx)
    if attachment:
        asyncio.create_task(generation(ctx, attachment, start_time))
        #await generation(ctx, attachment)
        
async def discord_before(ctx):
    if ctx.message.attachments: 
        await asyncio.gather(
            ctx.message.add_reaction('πŸ€–'),
            asyncio.sleep(0.5),
            ctx.message.add_reaction('βŒ›')  
        )
        attachment = ctx.message.attachments[0]

        # get the number of active threads
        activethreadcount = active_count()
        # report the number of active threads
        print(activethreadcount)
        
        return attachment
    else:
        await asyncio.gather(
            ctx.send(f"{ctx.author.mention} No attachments to be found... Can't animify dat! Try sending me an image πŸ˜‰"),
            asyncio.sleep(0.5),
            ctx.message.add_reaction('❌') 
        )
        return None

async def generation(ctx, attachment, start_time):
    if attachment:
        style = 'JoJo'

        im = await asyncio.get_running_loop().run_in_executor(None, jojogan.predict, attachment.url, style)
        #semaphore.release()

        #im = await asyncio.to_thread(jojogan.predict, attachment.url, style)
        #im = jojogan.predict(attachment.url, style)

        # get the number of active threads
        activethreadcount = active_count()
        # report the number of active threads
        print(activethreadcount)
        
        end_time = time.time()
        total_time = end_time - start_time
        
        await asyncio.gather(
            ctx.send(f'{ctx.author.mention} Jojo image generated in {total_time:.2f} seconds.', file=discord.File(im)),
            asyncio.sleep(0.5),
            ctx.message.remove_reaction('βŒ›', bot.user),
            asyncio.sleep(0.5),
            ctx.message.add_reaction('βœ…'),
            asyncio.sleep(0.5)
        )   
        


 


#--------------------------------------------------------
def get_total_threads():
    return multiprocessing.cpu_count()

total_threads = get_total_threads()
print("Total cpus:", total_threads)

# get the number of active threads
activethreadcount = active_count()
# report the number of active threads
print(activethreadcount)
    
def run_bot():
    bot.run(DISCORD_TOKEN)

threading.Thread(target=run_bot).start()

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.queue(concurrency_count=10)
demo.launch()
#--------------------------------------------------------



'''
 async def discord_after(ctx, im):
    await asyncio.gather(
        ctx.send(f'{ctx.author.mention} Here is the jojo version of it'),
        ctx.send(file=discord.File(im)),
        ctx.message.remove_reaction('βŒ›', bot.user),
        ctx.message.add_reaction('βœ…')
    )  

'''


'''
def blocking_io():
    #generate
    #return image

async def main():
    loop = asyncio.get_running_loop()


    
    exeresult = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', exeresult)

'''

























import discord
import os
import threading
import gradio as gr
import requests
import json
import random
import time
import re
from discord import Embed, Color
from discord.ext import commands
# test # fix? # unstick # fix
from gradio_client import Client
from PIL import Image
#from ratelimiter import RateLimiter

import asyncio
import concurrent.futures
import multiprocessing

import shutil # for doing image movement magic

#todo
# 4 -> combined image
# loading emoji? animated emojis?
# make success / fail emojis more consistent across both painter + dfif
# tasks for concurrent coroutines
# ratelimits

# enlarge each of 4 images?
# Error: [Errno 104] Connection reset by peer?

# clean up old threads
# safety for on_reaction_add?
# could use one channel, use threads to organize it. Otherwise may be too split and harder to keep track of
# lock generation after ~120s, can change
# restructure using slash commands? generate -> deepfloydif -> prompt -> thread -> combined -> upscale -> thread

DFIF_TOKEN = os.getenv('HF_TOKEN')
DISCORD_TOKEN = os.environ.get("GRADIOTEST_TOKEN", None)

df = Client("huggingface-projects/IF", DFIF_TOKEN)
jojogan = Client("akhaliq/JoJoGAN", DFIF_TOKEN)


intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)


#---------------------------------------------------------------------------------------------------------------------------------------------
@bot.event
async def on_ready():
    print('Logged on as', bot.user)
    bot.log_channel = bot.get_channel(1100458786826747945) # 1100458786826747945 = bot-test, 1107006391547342910 = lunarbot server
#---------------------------------------------------------------------------------------------------------------------------------------------
async def safetychecks(ctx):
    try:
        if ctx.author.bot:
            print(f"Error: The bot is not allowed to use its own commands.")
            return False
    
        #βœ…βœ… check if the bot is offline 
        offline_bot_role_id = 1103676632667017266
        bot_member = ctx.guild.get_member(bot.user.id)
        if any(role.id == offline_bot_role_id for role in bot_member.roles):
            print(f"Error: The bot is offline or under maintenance. (Remove the offline-bot role to bring it online)")         
            return False
    
        #βœ…βœ… check if the command is in the allowed channel(s)
        channel_id = 1100458786826747945
        if ctx.channel.id != 1100458786826747945:
            print(f"Error: This is not a permitted channel for that command. (bot-test is the correct channel)")
            return False
            
        #βœ…βœ… check if the user has the required role(s)   
        guild_id = 879548962464493619
        required_role_id = 900063512829755413  # @verified for now
        guild = bot.get_guild(guild_id)
        required_role = guild.get_role(required_role_id)
        if required_role not in ctx.author.roles:
            print(f"Error: The user does not have the required role to use that command. ({required_role} is the correct role)")        
            return False
    
        return True

    except Exception as e:
        print(f"Error: safetychecks failed somewhere, command will not continue.")
        await ctx.message.reply(f"<@811235357663297546> SC failed somewhere") # this will always ping, as long as the bot has access to the channel
#---------------------------------------------------------------------------------------------------------------------------------------------- 
# jojo
@bot.command()
async def jojo(ctx):
    # img + face    βœ…
    # img + no face βœ…
    # no image      βœ…
    # no generation βœ…
    # responsive?   βœ…
    # ratelimits?   ❌
    # safety checks?βœ…
    # bot no crash  βœ…
    try:  
        if await safetychecks(ctx): #βœ…
            await ctx.message.add_reaction('πŸ€–') 
            thread = await ctx.message.create_thread(name=f'{ctx.author} Jojo Thread')         
            if ctx.message.attachments:
                await thread.send(f'{ctx.author.mention}Generating images in thread, can take ~1 minute...yare yare, daze ...')  
                attachment = ctx.message.attachments[0]
                style = 'JoJo'
                #im = jojogan.predict(attachment.url, style)
                im = await asyncio.get_running_loop().run_in_executor(None, jojogan.predict, attachment.url, style)
                #await ctx.message.reply(f'Here is the {style} version of it', file=discord.File(im))
                await thread.send(f'{ctx.author.mention}Here is the {style} version of it', file=discord.File(im))
                await ctx.message.add_reaction('βœ…') # img + face    
            else: # no image
                await thread.send(f"{ctx.author.mention}No attachments to be found...Can't animify dat! Try sending me an image πŸ˜‰")
                await ctx.message.add_reaction('❌')             
    except Exception as e: # no generation / img + no face
        print(f"Error: {e}")
        await thread.send(f"{ctx.author.mention}Error: {e}")
        await ctx.message.add_reaction('❌')            
        
#---------------------------------------------------------------------------------------------------------------------------------------------- 
# Disney
@bot.command()
async def disney(ctx):
    try:
        if await safetychecks(ctx): #βœ…
            await ctx.message.add_reaction('πŸ€–') 
            thread = await ctx.message.create_thread(name=f'{ctx.author} disney Thread')         
            if ctx.message.attachments:
                await thread.send(f'{ctx.author.mention}Generating images in thread, can take ~1 minute...')  
                attachment = ctx.message.attachments[0]
                style = 'disney'
                im = await asyncio.get_running_loop().run_in_executor(None, jojogan.predict, attachment.url, style)
                await thread.send(f'{ctx.author.mention}Here is the {style} version of it', file=discord.File(im))
                await ctx.message.add_reaction('βœ…') # img + face    
            else: # no image
                await thread.send(f"{ctx.author.mention}No attachments to be found...Can't animify dat! Try sending me an image πŸ˜‰")
                await ctx.message.add_reaction('❌')             
    except Exception as e: # no generation / img + no face
        print(f"Error: {e}")
        await thread.send(f"{ctx.author.mention}Error: {e}")
        await ctx.message.add_reaction('❌') 
        
#---------------------------------------------------------------------------------------------------------------------------------------------- 
# Spider-Verse
@bot.command()
async def spiderverse(ctx):
    try:
        if await safetychecks(ctx): #βœ…
            await ctx.message.add_reaction('πŸ€–') 
            thread = await ctx.message.create_thread(name=f'{ctx.author} spider-verse Thread')         
            if ctx.message.attachments:
                await thread.send(f'{ctx.author.mention}Generating images in thread, can take ~1 minute...')  
                attachment = ctx.message.attachments[0]
                style = 'Spider-Verse'
                im = await asyncio.get_running_loop().run_in_executor(None, jojogan.predict, attachment.url, style)
                await thread.send(f'{ctx.author.mention}Here is the {style} version of it', file=discord.File(im))
                await ctx.message.add_reaction('βœ…') # img + face    
            else: # no image
                await thread.send(f"{ctx.author.mention}No attachments to be found...Can't animify dat! Try sending me an image πŸ˜‰")
                await ctx.message.add_reaction('❌')             
    except Exception as e: # no generation / img + no face
        print(f"Error: {e}")
        await thread.send(f"{ctx.author.mention}Error: {e}")
        await ctx.message.add_reaction('❌') 
        
#---------------------------------------------------------------------------------------------------------------------------------------------- 
# sketch
@bot.command()
async def sketch(ctx):
    try:    
        if await safetychecks(ctx): #βœ…
            await ctx.message.add_reaction('πŸ€–') 
            thread = await ctx.message.create_thread(name=f'{ctx.author} sketch Thread')         
            if ctx.message.attachments:
                await thread.send(f'{ctx.author.mention}Generating images in thread, can take ~1 minute...')  
                attachment = ctx.message.attachments[0]
                style = 'sketch'
                im = await asyncio.get_running_loop().run_in_executor(None, jojogan.predict, attachment.url, style)
                await thread.send(f'{ctx.author.mention}Here is the {style} version of it', file=discord.File(im))
                await ctx.message.add_reaction('βœ…') # img + face    
            else: # no image
                await thread.send(f"{ctx.author.mention}No attachments to be found...Can't animify dat! Try sending me an image πŸ˜‰")
                await ctx.message.add_reaction('❌')             
    except Exception as e: # no generation / img + no face
        print(f"Error: {e}")
        await thread.send(f"{ctx.author.mention}Error: {e}")
        await ctx.message.add_reaction('❌') 
#----------------------------------------------------------------------------------------------------------------------------------------------     
# Stage 1
@bot.command()
async def deepfloydif(ctx, *, prompt: str):
    try:
        try:
            if await safetychecks(ctx): #βœ…
                await ctx.message.add_reaction('πŸ€–') # loading emoji?
                dfif_command_message_id = ctx.message.id # we will use this in some magic later on
                thread = await ctx.message.create_thread(name=f'{ctx.author} DeepfloydIF Image Upscaling Thread ')
                # create thread -> send new message inside thread + combined_image -> add reactions -> dfif2
    
                #current_time = int(time.time())
                #random.seed(current_time)
    
                negative_prompt = ''
                seed = random.randint(0, 1000)
                #seed = 1
                number_of_images = 4
                guidance_scale = 7
                custom_timesteps_1 = 'smart50'
                number_of_inference_steps = 50
    
                await thread.send(f'{ctx.author.mention}Generating images in thread, can take ~1 minute...')
            
        except Exception as e:
            print(f"Error: {e}")
            await ctx.reply('stage 1 error -> pre generation')
            await ctx.message.add_reaction('❌')

        try:
            stage_1_results, stage_1_param_path, stage_1_result_path = df.predict(
                prompt, negative_prompt, seed, number_of_images, guidance_scale, custom_timesteps_1, number_of_inference_steps, api_name='/generate64')
            
            partialpath = stage_1_result_path[5:] #magic for later
        except Exception as e:
            print(f"Error: {e}")
            await ctx.reply('stage 1 error -> during generation')
            await ctx.message.add_reaction('❌')            
            
        try:
            png_files = [f for f in os.listdir(stage_1_results) if f.endswith('.png')]

            if png_files:
                first_png = png_files[0]
                second_png = png_files[1]
                third_png = png_files[2]
                fourth_png = png_files[3]
    
                first_png_path = os.path.join(stage_1_results, first_png)
                second_png_path = os.path.join(stage_1_results, second_png)
                third_png_path = os.path.join(stage_1_results, third_png)
                fourth_png_path = os.path.join(stage_1_results, fourth_png)
    
                img1 = Image.open(first_png_path)
                img2 = Image.open(second_png_path)
                img3 = Image.open(third_png_path)
                img4 = Image.open(fourth_png_path)
    
                combined_image = Image.new('RGB', (img1.width * 2, img1.height * 2))
    
                combined_image.paste(img1, (0, 0))
                combined_image.paste(img2, (img1.width, 0))
                combined_image.paste(img3, (0, img1.height))
                combined_image.paste(img4, (img1.width, img1.height))
    
                combined_image_path = os.path.join(stage_1_results, f'{partialpath}{dfif_command_message_id}.png')
                combined_image.save(combined_image_path)   

            with open(combined_image_path, 'rb') as f:
                combined_image_dfif = await thread.send(f'{ctx.author.mention}React with the image number you want to upscale!', file=discord.File(
                    f, f'{partialpath}{dfif_command_message_id}.png')) # named something like: tmpgtv4qjix1111269940599738479.png 

            async def react1234(emoji, combined_image_dfif):
                for emoji in ['1️⃣', '2️⃣', '3️⃣', '4️⃣']:
                    await combined_image_dfif.add_reaction(emoji)                

            await react1234(emoji, combined_image_dfif)
            
            ''' individual images
            if png_files:
                for i, png_file in enumerate(png_files):
                    png_file_path = os.path.join(stage_1_results, png_file)
                    img = Image.open(png_file_path)
                    image_path = os.path.join(stage_1_results, f'{i+1}{partialpath}.png')
                    img.save(image_path)
                    with open(image_path, 'rb') as f:
                        await thread.send(f'{ctx.author.mention}Image {i+1}', file=discord.File(f, f'{i+1}{partialpath}.png'))
                    await asyncio.sleep(1)             
            
            '''
            
        except Exception as e:
            print(f"Error: {e}")
            await ctx.reply('stage 1 error -> posting images in thread')
            await ctx.message.add_reaction('❌')
            
    #deepfloydif try/except
    except Exception as e:
        print(f"Error: {e}")
        await ctx.reply('An error occurred in stage 1 for deepfloydif')
        await ctx.message.add_reaction('❌')

#----------------------------------------------------------------------------------------------------------------------------
# Stage 2
async def dfif2(index: int, stage_1_result_path, thread, dfif_command_message_id): # add safetychecks
    try:
        await thread.send(f"inside dfif2, upscaling")  
        selected_index_for_stage_2 = index
        seed_2 = 0
        guidance_scale_2 = 4
        custom_timesteps_2 = 'smart50'
        number_of_inference_steps_2 = 50
        result_path = df.predict(stage_1_result_path, selected_index_for_stage_2, seed_2, 
                                 guidance_scale_2, custom_timesteps_2, number_of_inference_steps_2, api_name='/upscale256')

        await thread.send(f"upscale done")          
        with open(result_path, 'rb') as f:
            await thread.send(f'Here is the upscaled image! :) ', file=discord.File(f, 'result.png'))

        # using custom emoji that looks nicer
        emoji_guild = thread.guild  
        confirm_emoji_id = 1098629085955113011
        confirm_emoji = discord.utils.get(emoji_guild.emojis, id=confirm_emoji_id)
        
        # assuming dfif2 is always inside a thread, we can always exit the thread to find the channel with the original command,
        # which allows us to react confirm on that message.
        parent_channel = thread.parent
        dfif_command_message = await parent_channel.fetch_message(dfif_command_message_id)

        # reacting to original !deepfloydif command + using a custom emoji to do it
        await dfif_command_message.add_reaction(confirm_emoji)
        await thread.send(f"upscale posted")             
            #await ctx.reply('Here is the result of the second stage', file=discord.File(f, 'result.png'))
            #await ctx.message.add_reaction('βœ…') need to fix this

        '''
        try:
            dfif_command_message = await channel.fetch_message(dfif_command_message_id)
            await dfif_command_message.add_reaction('βœ…')            
        '''
            
    except Exception as e:
        print(f"Error: {e}")
        
        #await ctx.reply('An error occured in stage 2') need to fix
        #await ctx.message.add_reaction('❌')
#----------------------------------------------------------------------------------------------------------------------------
@bot.event
async def on_reaction_add(reaction, user):    # ctx = await bot.get_context(reaction.message)? could try later, might simplify
    try:
        # safety checks first ❌
        '''
        if user.bot:
            return   

        #offline bot check ❌
        offline_bot_role_id = 1103676632667017266
        bot_member = reaction.message.guild.get_member(bot.user.id)
        if any(role.id == offline_bot_role_id for role in bot_member.roles):            
            return
            
        # verified role check ❌
        guild = reaction.message.guild            
        required_role_id = 900063512829755413  # @verified for now
        required_role = guild.get_role(required_role_id)
        if required_role not in user.roles:
            return    

        #channel check ❌
        if reaction.message.channel.id != 1100458786826747945: 
            return        
        
        '''

        thread = reaction.message.channel
        threadparentid = thread.parent.id
        
        if not user.bot: 
            if threadparentid == 1100458786826747945: # bot-test
                # 811235357663297546 =  lunarflu
                if reaction.message.attachments:
                    if user.id == reaction.message.mentions[0].id:  #  if user.id == reaction.message.mentions[0].id:           
                        # magic begins
                        await reaction.message.channel.send("reaction detected")
                        attachment = reaction.message.attachments[0]
                        image_name = attachment.filename # named something like: tmpgtv4qjix1111269940599738479.png
                        # remove .png first
                        partialpathmessageid = image_name[:-4] # should be tmpgtv4qjix1111269940599738479 
                        # extract partialpath, messageid
                        partialpath = partialpathmessageid[:11] # tmpgtv4qjix
                        messageid = partialpathmessageid[11:] # 1111269940599738479
                        # add /tmp/ to partialpath, save as new variable
                        fullpath = "/tmp/" + partialpath # should be /tmp/tmpgtv4qjix
                        await reaction.message.channel.send(f"fullpath extracted, {fullpath}")        
                        emoji = reaction.emoji
                        
                        if emoji == "1️⃣":
                            index = 0
                        elif emoji == "2️⃣":
                            index = 1
                        elif emoji == "3️⃣":
                            index = 2
                        elif emoji == "4️⃣":
                            index = 3 
                            
                        await reaction.message.channel.send(f"index extracted, {index}")         
                        index = index
                        stage_1_result_path = fullpath
                        thread = reaction.message.channel
                        dfif_command_message_id = messageid
                        await reaction.message.channel.send(f"calling dfif2")  
                        await dfif2(index, stage_1_result_path, thread, dfif_command_message_id)
        
        '''

            if reaction.message.attachments:
                if user.id == reaction.message.mentions[0].id:  # all we care about is upscaling whatever image this is 
                    
                    # magic begins
                    attachment = reaction.message.attachments[0]
                    image_name = attachment.filename
                    # we know image_name will be something like 1tmpgtv4qjix.png
                    # remove .png first
                    indexpartialpath = image_name[:-4] # should be 1tmpgtv4qjix 
                    # extract index as an integer (dfif2 needs integer)
                    index = int(indexpartialpath[0]) - 1# should be 1
                    # extract partialpath
                    partialpath = indexpartialpath[1:] # should be tmpgtv4qjix
                    # add /tmp/ to partialpath, save as new variable
                    fullpath = "/tmp/" + partialpath # should be /tmp/tmpgtv4qjix
    
                    stage_1_result_path = fullpath
                    index = index
                    await dfif2(index, stage_1_result_path, thread)        
        
        '''

                
    except Exception as e:
        print(f"Error: {e}")
        
        #await ctx.reply('An error occured in stage 2') need to fix
        #await ctx.message.add_reaction('❌')
#---------------------------------------------------------------------------------------------------------------------------- 

    
def run_bot():
    bot.run(DISCORD_TOKEN)

threading.Thread(target=run_bot).start()

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()