Z3ktrix commited on
Commit
f9840c6
Β·
verified Β·
1 Parent(s): 5aadbe8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -31
app.py CHANGED
@@ -9,6 +9,12 @@ import logging
9
  import io
10
  import time
11
  from PIL import Image
 
 
 
 
 
 
12
 
13
  # Load environment variables from the .env file
14
  load_dotenv()
@@ -16,27 +22,15 @@ load_dotenv()
16
  DISCORD_TOKEN = os.getenv('dsTOK')
17
  HF_API_KEY = os.getenv('HFREAD')
18
 
19
- API_URL = "https://api-inference.huggingface.co/models/Corcelio/mobius"
20
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
21
-
22
  # Set up logging
23
  logging.basicConfig(level=logging.INFO)
24
  logger = logging.getLogger(__name__)
25
 
26
- # Function to query the Hugging Face model with a structured prompt
27
- def query(payload, max_retries=5, delay=5):
28
- retries = 0
29
- while retries < max_retries:
30
- try:
31
- response = requests.post(API_URL, headers=headers, json=payload)
32
- response.raise_for_status()
33
- return response.content
34
- except requests.exceptions.RequestException as e:
35
- logger.error(f"Error querying the API: {e}. Retrying in {delay} seconds...")
36
- time.sleep(delay)
37
- retries += 1
38
- logger.error(f"Failed to query the API after {max_retries} attempts.")
39
- return None
40
 
41
  # Initialize the Discord bot with a default prefix
42
  intents = discord.Intents.default()
@@ -49,32 +43,38 @@ bot = commands.Bot(command_prefix=commands.when_mentioned_or(default_prefix), in
49
  async def on_ready():
50
  logger.info(f'Bot is ready. Logged in as {bot.user}')
51
 
52
- @bot.command(name='generate')
53
  @commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
54
  async def generate(ctx, *description):
55
  """
56
- Command to generate an image based on a description using the Hugging Face model.
57
  """
58
  if not description:
59
  await ctx.send("You need to provide a description for the image.")
60
  return
61
 
62
- description = " ".join(description)
 
 
63
  try:
64
- payload = {"inputs": description}
65
- image_bytes = query(payload)
 
 
 
 
 
 
 
 
66
 
67
- if image_bytes:
68
- image = Image.open(io.BytesIO(image_bytes))
69
- with io.BytesIO() as image_binary:
70
- image.save(image_binary, 'PNG')
71
- image_binary.seek(0)
72
- await ctx.send(file=discord.File(fp=image_binary, filename='generated_image.png'))
73
- else:
74
- await ctx.send("An error occurred while generating the image. Please try again later.")
75
  except Exception as e:
76
  logger.error(f"Error processing the generate command: {e}")
77
- await ctx.send("An error occurred while processing your request. Please try again later.")
78
 
79
  @generate.error
80
  async def generate_error(ctx, error):
 
9
  import io
10
  import time
11
  from PIL import Image
12
+ import torch
13
+ from diffusers import (
14
+ StableDiffusionXLPipeline,
15
+ KDPM2AncestralDiscreteScheduler,
16
+ AutoencoderKL
17
+ )
18
 
19
  # Load environment variables from the .env file
20
  load_dotenv()
 
22
  DISCORD_TOKEN = os.getenv('dsTOK')
23
  HF_API_KEY = os.getenv('HFREAD')
24
 
 
 
 
25
  # Set up logging
26
  logging.basicConfig(level=logging.INFO)
27
  logger = logging.getLogger(__name__)
28
 
29
+ # Load VAE component and configure the pipeline
30
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
31
+ pipe = StableDiffusionXLPipeline.from_pretrained("Corcelio/mobius", vae=vae, torch_dtype=torch.float16)
32
+ pipe.scheduler = KDPM2AncestralDiscreteScheduler.from_config(pipe.scheduler.config)
33
+ pipe.to('cuda')
 
 
 
 
 
 
 
 
 
34
 
35
  # Initialize the Discord bot with a default prefix
36
  intents = discord.Intents.default()
 
43
  async def on_ready():
44
  logger.info(f'Bot is ready. Logged in as {bot.user}')
45
 
46
+ @bot.command(name='gen')
47
  @commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
48
  async def generate(ctx, *description):
49
  """
50
+ Command to generate an image based on a description using the Stable Diffusion XL model.
51
  """
52
  if not description:
53
  await ctx.send("You need to provide a description for the image.")
54
  return
55
 
56
+ prompt = " ".join(description)
57
+ negative_prompt = "bad quality, low resolution, ugly, worse quality, grayscale, blurry"
58
+
59
  try:
60
+ # Generate the image
61
+ image = pipe(
62
+ prompt,
63
+ negative_prompt=negative_prompt,
64
+ width=512,
65
+ height=512,
66
+ guidance_scale=5,
67
+ num_inference_steps=25,
68
+ clip_skip=3
69
+ ).images[0]
70
 
71
+ with io.BytesIO() as image_binary:
72
+ image.save(image_binary, 'PNG')
73
+ image_binary.seek(0)
74
+ await ctx.send(file=discord.File(fp=image_binary, filename='generated_image.png'))
 
 
 
 
75
  except Exception as e:
76
  logger.error(f"Error processing the generate command: {e}")
77
+ await ctx.send("An error occurred while processing your request.")
78
 
79
  @generate.error
80
  async def generate_error(ctx, error):