Spaces:
Runtime error
Runtime error
File size: 8,172 Bytes
1d33068 24ea1ea ca3defd a2d5af8 8e64f0d 1d33068 ac77ded dcc49a2 8e64f0d 1d33068 8e64f0d 1d33068 8e64f0d 1d33068 a2d5af8 f35c9d9 94e298f 4107503 94e298f 24ea1ea 92f9409 60d0daf f35c9d9 24ea1ea 94e298f 24ea1ea b40d49a 611279e b40d49a f35c9d9 ca3defd 7437a2c ca3defd f35c9d9 374f848 a2d5af8 374f848 dea0635 a2d5af8 1d33068 f65a0cb 19d1e42 f65a0cb 19d1e42 f65a0cb 4107503 9a29b5b dea0635 ca3defd 611279e 64536ea dea0635 8e64f0d f65a0cb b40d49a 1d2163e 374f848 f65a0cb 1d2163e 0277ed0 ea489ba b40d49a ea489ba 091515f 85ddfa3 1563aef 091515f 0277ed0 d0c29e1 b3fd847 be586af 8e64f0d 996bcaa f35c9d9 8e64f0d f65a0cb 60d0daf 564c587 4107503 5a4a86b 42b7f57 1d33068 8e64f0d 1d33068 ca3defd aed520d b40a5eb 94e298f aed520d 985ebd8 f5bcaca 1d33068 24ea1ea 4803751 |
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 |
import gradio as gr
from gradio_client import Client
import os
import logging
import requests
from urllib.parse import urlparse, parse_qs
# Initialize the client for image generation
client_image = Client("mukaist/DALLE-4K")
# Retrieve secret token from environment variables
webhook_server = os.getenv('webhook_server')
# Define resolutions
resolutions = {
"896x1152": (896, 1152),
"1024x1024": (1024, 1024),
"1216x832": (1216, 832)
}
# Define the default style
DEFAULT_STYLE = "3840 x 2160"
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
resolution = resolutions.get(resolution_key, (1024, 1024))
width, height = resolution
full_prompt = f"{prompt}, Canon EOS R5, 4K, Photo-Realistic, appearing photorealistic with super fine details, high resolution, natural look, hyper realistic photography, cinematic lighting, --ar 64:37, --v 6.0, --style raw, --stylize 750"
try:
result = client_image.predict(
prompt=full_prompt,
negative_prompt="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation",
use_negative_prompt=True,
style=style,
seed=0,
width=width,
height=height,
guidance_scale=5,
randomize_seed=True,
api_name="/run"
)
logger.info("Image generation successful.")
return result
except Exception as e:
logger.error(f"Error generating image: {e}")
return None
def update_user_points(user_chat_id, points):
"""Updates the user's points using a webhook."""
webhook_url = f"{webhook_server}/update_user_points" # Ensure this URL is correct
payload = {
'user_chat_id': user_chat_id,
'points': points
}
try:
response = requests.post(webhook_url, json=payload)
response.raise_for_status()
logger.info(f"User with ID {user_chat_id} had their points updated by {points}. Webhook response: {response.status_code}")
except requests.RequestException as e:
logger.error(f"Error updating user points via webhook: {e}")
def get_user_points(user_chat_id):
"""Retrieve the user's points from the Flask server."""
try:
response = requests.get(f"{webhook_server}/get_points", params={'user_chat_id': user_chat_id})
response.raise_for_status()
data = response.json()
if 'error' in data:
return "User not found"
return data.get('points', 0)
except requests.RequestException as e:
logger.error(f"Error retrieving user points: {e}")
return "Error retrieving points"
def notify_webhook(user_chat_id):
"""Notify the webhook server about the points update."""
webhook_url = f"{webhook_server}/notify_update"
payload = {'user_chat_id': user_chat_id}
try:
response = requests.post(webhook_url, json=payload)
response.raise_for_status()
logger.info(f"Webhook notification sent successfully. Response: {response.status_code}")
except requests.RequestException as e:
logger.error(f"Error sending webhook notification: {e}")
def retrieve_user_points(user_chat_id):
"""Retrieve user points and display them."""
points = get_user_points(user_chat_id)
if points == "Guest":
return "Please register with @myexpsupportBot", ""
return points
def extract_user_chat_id_from_url(url):
parsed_url = urlparse(url)
params = parse_qs(parsed_url.query)
return params.get('user_chat_id', ["Guest"])[0]
def gradio_interface(prompt, resolution_key, user_chat_id):
# Check if user_chat_id is empty
if not user_chat_id.strip():
return None, "User Chat ID cannot be blank. Please provide a valid User Chat ID."
# Proceed with image generation if user_chat_id is provided
result = generate_image(prompt, resolution_key)
if result and result[0]:
file_path = result[0][0].get('image')
if file_path and os.path.exists(file_path):
update_user_points(user_chat_id, -5) # Deduct points for each image generated
return file_path, "The image was generated successfully."
else:
return None, "The image file is not available. Please try again later."
else:
return None, "There was an error processing your photo. Please try again later."
def handle_generate_image(prompt, resolution_key, user_chat_id):
points = get_user_points(user_chat_id)
# Check if the points is a string indicating user not found
if isinstance(points, str):
if points == "User not found":
return None, "Please register with @myexpsupportBot"
else:
return None, "Error retrieving points. Please try again later."
# Ensure points is an integer
try:
points = int(points)
except ValueError:
return None, "Error processing points. Please try again later."
if points >= 5:
result = gradio_interface(prompt, resolution_key, user_chat_id)
if result[0]: # If image generation is successful
return result[0], "The image was generated successfully."
else:
return None, "There was an error processing your photo. Please try again later."
else:
return None, "Insufficient points. Please get more points before generating an image."
def create_gradio_interface():
with gr.Blocks() as interface:
# Personalized HTML content
gr.HTML("""
<h1> AI Image Generate DALL 4K</h1>
<h3>Welcome! Please enter your user chat ID to continue.</h3>
""")
# Create input components
user_chat_id_input = gr.Textbox(
label="Your UID",
placeholder="Your UID",
interactive=True # Make this non-editable
)
points_output = gr.Textbox(label="Your Balances", placeholder="Your Points")
# Create the button to get user points
get_points_button = gr.Button("Show Your Points")
# Create other components
prompt_input = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...")
resolution_dropdown = gr.Dropdown(choices=list(resolutions.keys()), label="Resolution", value="1024x1024")
generate_button = gr.Button("Generate")
result_output = gr.Image(label="Generated Image", type="pil")
message_output = gr.Textbox(label="Result", placeholder="Results will be shown here", interactive=False)
# Arrange components in rows
with gr.Row():
user_chat_id_input
points_output
get_points_button
with gr.Row():
prompt_input
resolution_dropdown
generate_button
# Set up interactions
generate_button.click(
fn=handle_generate_image,
inputs=[prompt_input, resolution_dropdown, user_chat_id_input],
outputs=[result_output, message_output]
)
get_points_button.click(
fn=retrieve_user_points,
inputs=[user_chat_id_input],
outputs=[points_output] # Update points output
)
gr.HTML("""
<style>
footer.svelte-1rjryqp {
display: none !important;
}
</style>
""")
return interface
def launch_gradio():
# Obtain the URL dynamically (from a configured environment variable or similar)
url = 'https://measmonysuon-imagen.hf.space/?user_chat_id=00000000' # Replace with the actual URL or method to obtain it
user_chat_id = extract_user_chat_id_from_url(url)
# Pass the extracted user_chat_id to the Gradio interface
interface = create_gradio_interface()
interface.launch()
if __name__ == '__main__':
launch_gradio() |