artintel235 commited on
Commit
baaab55
·
verified ·
1 Parent(s): 145c474

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -55
app.py CHANGED
@@ -4,36 +4,25 @@ import os
4
  import requests
5
  import asyncio
6
  import aiohttp # Use aiohttp for asynchronous HTTP requests
 
7
 
8
  # --- Environment Variables & Setup ---
9
  DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
10
  GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN")
11
  GLIF_API_URL = "https://simple-api.glif.app"
12
 
13
- # Check if tokens are set
14
  if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN:
15
- raise ValueError(
16
- "Both DISCORD_BOT_TOKEN and GLIF_API_TOKEN must be set as environment variables in the Hugging Face Space's settings."
17
- )
18
 
19
  # --- Discord Bot Setup ---
20
  intents = discord.Intents.default()
21
- # intents.message_content = True # If you need message content intent
22
  client = discord.Client(intents=intents)
23
  tree = app_commands.CommandTree(client)
24
 
25
- # --- Asynchronous GLIF API Interaction with aiohttp ---
26
  async def generate_image_async(prompt, aspect_ratio):
27
- """
28
- Generates an image using the GLIF API asynchronously.
29
- Args:
30
- prompt: The text prompt for image generation.
31
- aspect_ratio: The desired aspect ratio (e.g., "1:1", "16:9").
32
- Returns:
33
- The URL of the generated image, or an error message if the API request failed.
34
- """
35
  payload = {
36
- "id": "cm3ugmzv2002gnckiosrwk6xi", # Your GLIF model ID
37
  "inputs": [prompt, aspect_ratio],
38
  }
39
  headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
@@ -42,9 +31,8 @@ async def generate_image_async(prompt, aspect_ratio):
42
  try:
43
  async with session.post(
44
  GLIF_API_URL, json=payload, headers=headers, timeout=15
45
- ) as response: # Increased timeout to 15 seconds
46
  response.raise_for_status()
47
-
48
  response_data = await response.json()
49
  if "output" in response_data:
50
  return response_data["output"]
@@ -58,19 +46,13 @@ async def generate_image_async(prompt, aspect_ratio):
58
  except aiohttp.ClientError as e:
59
  return f"API request failed: {e}"
60
 
61
- # --- Discord Slash Commands ---
62
- @tree.command(
63
- name="generate", description="Generates an image based on a text prompt"
64
- )
65
  @app_commands.choices(
66
  aspect_ratio=[
67
  app_commands.Choice(name="1:1 (Square)", value="1:1"),
68
  app_commands.Choice(name="9:16 (Vertical)", value="9:16"),
69
  app_commands.Choice(name="16:9 (Horizontal)", value="16:9"),
70
- app_commands.Choice(name="4:5 (Portrait)", value="4:5"),
71
- app_commands.Choice(name="5:4 (Landscape)", value="5:4"),
72
- app_commands.Choice(name="3:4 (Portrait)", value="3:4"),
73
- app_commands.Choice(name="4:3 (Landscape)", value="4:3"),
74
  ]
75
  )
76
  async def generate_command(
@@ -79,50 +61,56 @@ async def generate_command(
79
  aspect_ratio: app_commands.Choice[str],
80
  ):
81
  try:
82
- await interaction.response.defer() # MUST be the first await
83
-
84
- # ... rest of your code ...
 
 
 
 
 
 
 
 
85
  except Exception as e:
86
- print(e)
87
- """Generates an image based on the user's prompt and aspect ratio."""
88
- # await interaction.response.defer() # Acknowledge within 3 seconds
89
-
90
- # Call the asynchronous image generation function
91
- image_url_or_error = await generate_image_async(
92
- prompt, aspect_ratio.value
93
- )
94
-
95
- if image_url_or_error.startswith("http"):
96
- await interaction.followup.send(
97
- f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url_or_error}"
98
- )
99
- else:
100
- await interaction.followup.send(
101
- f"Sorry, I couldn't generate an image. {image_url_or_error}"
102
- )
103
 
104
  @tree.command(name="hello", description="Says hello!")
105
  async def hello_command(interaction):
106
  await interaction.response.send_message("Hello there!")
107
 
108
- # --- Bot Initialization and Event Loop ---
109
  async def on_ready():
110
  await tree.sync()
111
  print("Bot is ready!")
112
 
 
113
  client.event(on_ready)
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  async def main():
116
- print("Inside main()")
117
- async with client:
118
- print("Starting client...")
119
- await client.start(DISCORD_BOT_TOKEN)
120
- print("Bot has started.")
121
 
122
- # Keep the main function alive:
123
- while True:
124
- await asyncio.sleep(60) # Sleep for 60 seconds
125
 
126
  if __name__ == "__main__":
127
- print("Running main()")
128
  asyncio.run(main())
 
4
  import requests
5
  import asyncio
6
  import aiohttp # Use aiohttp for asynchronous HTTP requests
7
+ import gradio as gr # Import Gradio
8
 
9
  # --- Environment Variables & Setup ---
10
  DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
11
  GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN")
12
  GLIF_API_URL = "https://simple-api.glif.app"
13
 
 
14
  if not DISCORD_BOT_TOKEN or not GLIF_API_TOKEN:
15
+ raise ValueError("Both DISCORD_BOT_TOKEN and GLIF_API_TOKEN must be set.")
 
 
16
 
17
  # --- Discord Bot Setup ---
18
  intents = discord.Intents.default()
 
19
  client = discord.Client(intents=intents)
20
  tree = app_commands.CommandTree(client)
21
 
22
+
23
  async def generate_image_async(prompt, aspect_ratio):
 
 
 
 
 
 
 
 
24
  payload = {
25
+ "id": "cm3ugmzv2002gnckiosrwk6xi",
26
  "inputs": [prompt, aspect_ratio],
27
  }
28
  headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
 
31
  try:
32
  async with session.post(
33
  GLIF_API_URL, json=payload, headers=headers, timeout=15
34
+ ) as response:
35
  response.raise_for_status()
 
36
  response_data = await response.json()
37
  if "output" in response_data:
38
  return response_data["output"]
 
46
  except aiohttp.ClientError as e:
47
  return f"API request failed: {e}"
48
 
49
+
50
+ @tree.command(name="generate", description="Generates an image based on a text prompt")
 
 
51
  @app_commands.choices(
52
  aspect_ratio=[
53
  app_commands.Choice(name="1:1 (Square)", value="1:1"),
54
  app_commands.Choice(name="9:16 (Vertical)", value="9:16"),
55
  app_commands.Choice(name="16:9 (Horizontal)", value="16:9"),
 
 
 
 
56
  ]
57
  )
58
  async def generate_command(
 
61
  aspect_ratio: app_commands.Choice[str],
62
  ):
63
  try:
64
+ await interaction.response.defer()
65
+
66
+ image_url_or_error = await generate_image_async(prompt, aspect_ratio.value)
67
+ if image_url_or_error.startswith("http"):
68
+ await interaction.followup.send(
69
+ f"Here's your generated image based on the prompt '{prompt}' with aspect ratio {aspect_ratio.name}:\n{image_url_or_error}"
70
+ )
71
+ else:
72
+ await interaction.followup.send(
73
+ f"Sorry, I couldn't generate an image. {image_url_or_error}"
74
+ )
75
  except Exception as e:
76
+ await interaction.followup.send(f"Error: {str(e)}")
77
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  @tree.command(name="hello", description="Says hello!")
80
  async def hello_command(interaction):
81
  await interaction.response.send_message("Hello there!")
82
 
83
+
84
  async def on_ready():
85
  await tree.sync()
86
  print("Bot is ready!")
87
 
88
+
89
  client.event(on_ready)
90
 
91
+
92
+ # --- Gradio Interface ---
93
+ def echo_text(text):
94
+ return text
95
+
96
+
97
+ def run_gradio():
98
+ gr.Interface(
99
+ fn=echo_text,
100
+ inputs="text",
101
+ outputs="text",
102
+ live=False,
103
+ title="Minimal Gradio Interface",
104
+ ).launch(server_name="0.0.0.0", server_port=7860, share=False, show_error=True)
105
+
106
+
107
+ # --- Main ---
108
  async def main():
109
+ bot_task = asyncio.create_task(client.start(DISCORD_BOT_TOKEN))
110
+ gradio_task = asyncio.to_thread(run_gradio)
111
+
112
+ await asyncio.gather(bot_task, gradio_task)
 
113
 
 
 
 
114
 
115
  if __name__ == "__main__":
 
116
  asyncio.run(main())