measmonysuon commited on
Commit
6e87c75
1 Parent(s): 611279e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -64
app.py CHANGED
@@ -9,16 +9,14 @@ from urllib.parse import urlparse, parse_qs
9
  client_image = Client("mukaist/DALLE-4K")
10
 
11
  # Retrieve secret token from environment variables
12
- webhook_server = os.getenv('webhook_server')
13
 
14
- # Define resolutions
15
  resolutions = {
16
  "896x1152": (896, 1152),
17
  "1024x1024": (1024, 1024),
18
  "1216x832": (1216, 832)
19
  }
20
-
21
- # Define the default style
22
  DEFAULT_STYLE = "3840 x 2160"
23
 
24
  # Set up logging
@@ -29,7 +27,7 @@ def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
29
  resolution = resolutions.get(resolution_key, (1024, 1024))
30
  width, height = resolution
31
  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"
32
-
33
  try:
34
  result = client_image.predict(
35
  prompt=full_prompt,
@@ -49,14 +47,27 @@ def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
49
  logger.error(f"Error generating image: {e}")
50
  return None
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def update_user_points(user_chat_id, points):
53
- """Updates the user's points using a webhook."""
54
- webhook_url = f"{webhook_server}/update_user_points" # Ensure this URL is correct
55
- payload = {
56
- 'user_chat_id': user_chat_id,
57
- 'points': points
58
- }
59
-
60
  try:
61
  response = requests.post(webhook_url, json=payload)
62
  response.raise_for_status()
@@ -65,7 +76,6 @@ def update_user_points(user_chat_id, points):
65
  logger.error(f"Error updating user points via webhook: {e}")
66
 
67
  def get_user_points(user_chat_id):
68
- """Retrieve the user's points from the Flask server."""
69
  try:
70
  response = requests.get(f"{webhook_server}/get_points", params={'user_chat_id': user_chat_id})
71
  response.raise_for_status()
@@ -76,9 +86,8 @@ def get_user_points(user_chat_id):
76
  except requests.RequestException as e:
77
  logger.error(f"Error retrieving user points: {e}")
78
  return "Error retrieving points"
79
-
80
  def notify_webhook(user_chat_id):
81
- """Notify the webhook server about the points update."""
82
  webhook_url = f"{webhook_server}/notify_update"
83
  payload = {'user_chat_id': user_chat_id}
84
  try:
@@ -88,82 +97,56 @@ def notify_webhook(user_chat_id):
88
  except requests.RequestException as e:
89
  logger.error(f"Error sending webhook notification: {e}")
90
 
91
- def retrieve_user_points(user_chat_id):
92
- """Retrieve user points and display them."""
93
- points = get_user_points(user_chat_id)
94
- if points == "Guest":
95
- return "Please register with @myexpsupportBot", ""
96
- return points
97
-
98
  def extract_user_chat_id_from_url(url):
99
  parsed_url = urlparse(url)
100
  params = parse_qs(parsed_url.query)
101
  return params.get('user_chat_id', ["Guest"])[0]
102
 
103
  def gradio_interface(prompt, resolution_key, user_chat_id):
104
- # Check if user_chat_id is empty
105
  if not user_chat_id.strip():
106
  return None, "User Chat ID cannot be blank. Please provide a valid User Chat ID."
107
 
108
- # Proceed with image generation if user_chat_id is provided
109
  result = generate_image(prompt, resolution_key)
110
-
111
  if result and result[0]:
112
  file_path = result[0][0].get('image')
113
  if file_path and os.path.exists(file_path):
114
  update_user_points(user_chat_id, -5) # Deduct points for each image generated
115
  return file_path, "The image was generated successfully."
116
- else:
117
- return None, "The image file is not available. Please try again later."
118
- else:
119
- return None, "There was an error processing your photo. Please try again later."
120
 
121
  def handle_generate_image(prompt, resolution_key, user_chat_id):
122
  points = get_user_points(user_chat_id)
123
-
124
- # Check if the points is a string indicating user not found
125
  if isinstance(points, str):
126
  if points == "User not found":
127
  return None, "Please register with @myexpsupportBot"
128
- else:
129
- return None, "Error retrieving points. Please try again later."
130
-
131
- # Ensure points is an integer
132
  try:
133
  points = int(points)
134
  except ValueError:
135
  return None, "Error processing points. Please try again later."
136
-
137
  if points >= 5:
138
  result = gradio_interface(prompt, resolution_key, user_chat_id)
139
- if result[0]: # If image generation is successful
140
  return result[0], "The image was generated successfully."
141
- else:
142
- return None, "There was an error processing your photo. Please try again later."
143
- else:
144
- return None, "Insufficient points. Please get more points before generating an image."
145
-
146
 
147
  def create_gradio_interface():
148
  with gr.Blocks() as interface:
149
- # Personalized HTML content
150
  gr.HTML("""
151
- <h1> AI Image Generate DALL 4K</h1>
152
  <h3>Welcome! Please enter your user chat ID to continue.</h3>
153
  """)
154
 
155
- # Create input components
156
- user_chat_id_input = gr.Textbox(
157
- label="Your UID",
158
- placeholder="Your UID",
159
- interactive=True # Make this non-editable
160
- )
161
- points_output = gr.Textbox(label="Your Balances", placeholder="Your Points")
162
 
163
- # Create the button to get user points
164
- get_points_button = gr.Button("Show Your Points")
165
 
166
- # Create other components
167
  prompt_input = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...")
168
  resolution_dropdown = gr.Dropdown(choices=list(resolutions.keys()), label="Resolution", value="1024x1024")
169
  generate_button = gr.Button("Generate")
@@ -171,7 +154,6 @@ def create_gradio_interface():
171
  result_output = gr.Image(label="Generated Image", type="pil")
172
  message_output = gr.Textbox(label="Result", placeholder="Results will be shown here", interactive=False)
173
 
174
- # Arrange components in rows
175
  with gr.Row():
176
  user_chat_id_input
177
  points_output
@@ -181,8 +163,7 @@ def create_gradio_interface():
181
  prompt_input
182
  resolution_dropdown
183
  generate_button
184
-
185
- # Set up interactions
186
  generate_button.click(
187
  fn=handle_generate_image,
188
  inputs=[prompt_input, resolution_dropdown, user_chat_id_input],
@@ -191,10 +172,10 @@ def create_gradio_interface():
191
 
192
  get_points_button.click(
193
  fn=retrieve_user_points,
194
- inputs=[user_chat_id_input],
195
- outputs=[points_output] # Update points output
196
  )
197
-
198
  gr.HTML("""
199
  <style>
200
  footer.svelte-1rjryqp {
@@ -202,15 +183,13 @@ def create_gradio_interface():
202
  }
203
  </style>
204
  """)
205
-
206
  return interface
207
 
208
  def launch_gradio():
209
- # Obtain the URL dynamically (from a configured environment variable or similar)
210
- url = 'https://measmonysuon-imagen.hf.space/?user_chat_id=00000000' # Replace with the actual URL or method to obtain it
211
  user_chat_id = extract_user_chat_id_from_url(url)
212
 
213
- # Pass the extracted user_chat_id to the Gradio interface
214
  interface = create_gradio_interface()
215
  interface.launch()
216
 
 
9
  client_image = Client("mukaist/DALLE-4K")
10
 
11
  # Retrieve secret token from environment variables
12
+ webhook_server = os.getenv('WEBHOOK_SERVER')
13
 
14
+ # Define resolutions and default style
15
  resolutions = {
16
  "896x1152": (896, 1152),
17
  "1024x1024": (1024, 1024),
18
  "1216x832": (1216, 832)
19
  }
 
 
20
  DEFAULT_STYLE = "3840 x 2160"
21
 
22
  # Set up logging
 
27
  resolution = resolutions.get(resolution_key, (1024, 1024))
28
  width, height = resolution
29
  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"
30
+
31
  try:
32
  result = client_image.predict(
33
  prompt=full_prompt,
 
47
  logger.error(f"Error generating image: {e}")
48
  return None
49
 
50
+ def verify_otp(user_chat_id, otp):
51
+ response = requests.post(f"{webhook_server}/verify_otp", json={"user_chat_id": user_chat_id, "otp": otp})
52
+ return response.json().get("valid", False)
53
+
54
+ def retrieve_user_points(user_chat_id, otp):
55
+ # Verify OTP via Flask server
56
+ otp_response = requests.post(f"{webhook_server}/verify_otp", json={"user_chat_id": user_chat_id, "otp": otp})
57
+ if otp_response.status_code != 200 or not otp_response.json().get('valid'):
58
+ return "Invalid or expired OTP. Please request a new OTP."
59
+
60
+ # Retrieve user points via Flask server
61
+ response = requests.get(f"{webhook_server}/get_points", params={"user_chat_id": user_chat_id})
62
+ if response.status_code == 200:
63
+ data = response.json()
64
+ points = data.get("points", 0)
65
+ return f"Your current balance is: {points}"
66
+ return "Error retrieving points. Please try again later."
67
+
68
  def update_user_points(user_chat_id, points):
69
+ webhook_url = f"{webhook_server}/update_user_points"
70
+ payload = {'user_chat_id': user_chat_id, 'points': points}
 
 
 
 
 
71
  try:
72
  response = requests.post(webhook_url, json=payload)
73
  response.raise_for_status()
 
76
  logger.error(f"Error updating user points via webhook: {e}")
77
 
78
  def get_user_points(user_chat_id):
 
79
  try:
80
  response = requests.get(f"{webhook_server}/get_points", params={'user_chat_id': user_chat_id})
81
  response.raise_for_status()
 
86
  except requests.RequestException as e:
87
  logger.error(f"Error retrieving user points: {e}")
88
  return "Error retrieving points"
89
+
90
  def notify_webhook(user_chat_id):
 
91
  webhook_url = f"{webhook_server}/notify_update"
92
  payload = {'user_chat_id': user_chat_id}
93
  try:
 
97
  except requests.RequestException as e:
98
  logger.error(f"Error sending webhook notification: {e}")
99
 
 
 
 
 
 
 
 
100
  def extract_user_chat_id_from_url(url):
101
  parsed_url = urlparse(url)
102
  params = parse_qs(parsed_url.query)
103
  return params.get('user_chat_id', ["Guest"])[0]
104
 
105
  def gradio_interface(prompt, resolution_key, user_chat_id):
 
106
  if not user_chat_id.strip():
107
  return None, "User Chat ID cannot be blank. Please provide a valid User Chat ID."
108
 
 
109
  result = generate_image(prompt, resolution_key)
 
110
  if result and result[0]:
111
  file_path = result[0][0].get('image')
112
  if file_path and os.path.exists(file_path):
113
  update_user_points(user_chat_id, -5) # Deduct points for each image generated
114
  return file_path, "The image was generated successfully."
115
+ return None, "The image file is not available. Please try again later."
116
+ return None, "There was an error processing your photo. Please try again later."
 
 
117
 
118
  def handle_generate_image(prompt, resolution_key, user_chat_id):
119
  points = get_user_points(user_chat_id)
 
 
120
  if isinstance(points, str):
121
  if points == "User not found":
122
  return None, "Please register with @myexpsupportBot"
123
+ return None, "Error retrieving points. Please try again later."
124
+
 
 
125
  try:
126
  points = int(points)
127
  except ValueError:
128
  return None, "Error processing points. Please try again later."
129
+
130
  if points >= 5:
131
  result = gradio_interface(prompt, resolution_key, user_chat_id)
132
+ if result[0]:
133
  return result[0], "The image was generated successfully."
134
+ return None, "There was an error processing your photo. Please try again later."
135
+ return None, "Insufficient points. Please get more points before generating an image."
 
 
 
136
 
137
  def create_gradio_interface():
138
  with gr.Blocks() as interface:
 
139
  gr.HTML("""
140
+ <h1>AI Image Generation DALL·E 4K</h1>
141
  <h3>Welcome! Please enter your user chat ID to continue.</h3>
142
  """)
143
 
144
+ user_chat_id_input = gr.Textbox(label="Your UID", placeholder="Your UID")
145
+ user_otp_input = gr.Textbox(label="OTP", type="password")
146
+ points_output = gr.Textbox(label="Your Balances", placeholder="Your Points", interactive=False)
 
 
 
 
147
 
 
 
148
 
149
+ get_points_button = gr.Button("Show Your Points")
150
  prompt_input = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...")
151
  resolution_dropdown = gr.Dropdown(choices=list(resolutions.keys()), label="Resolution", value="1024x1024")
152
  generate_button = gr.Button("Generate")
 
154
  result_output = gr.Image(label="Generated Image", type="pil")
155
  message_output = gr.Textbox(label="Result", placeholder="Results will be shown here", interactive=False)
156
 
 
157
  with gr.Row():
158
  user_chat_id_input
159
  points_output
 
163
  prompt_input
164
  resolution_dropdown
165
  generate_button
166
+
 
167
  generate_button.click(
168
  fn=handle_generate_image,
169
  inputs=[prompt_input, resolution_dropdown, user_chat_id_input],
 
172
 
173
  get_points_button.click(
174
  fn=retrieve_user_points,
175
+ inputs=[user_chat_id_input, user_otp_input],
176
+ outputs=[points_output]
177
  )
178
+
179
  gr.HTML("""
180
  <style>
181
  footer.svelte-1rjryqp {
 
183
  }
184
  </style>
185
  """)
186
+
187
  return interface
188
 
189
  def launch_gradio():
190
+ url = 'https://measmonysuon-imagen.hf.space/?user_chat_id=00000000'
 
191
  user_chat_id = extract_user_chat_id_from_url(url)
192
 
 
193
  interface = create_gradio_interface()
194
  interface.launch()
195