Chandima Prabhath commited on
Commit
1743c01
Β·
1 Parent(s): 856d629

Refactor image handling in handle_image_generation to streamline image sending and improve error handling

Browse files
Files changed (1) hide show
  1. app.py +36 -72
app.py CHANGED
@@ -112,30 +112,6 @@ def send_image(message_id, to_number, image_path, caption="Here you go!", retrie
112
  except requests.RequestException as e:
113
  if i == retries - 1:
114
  return {"error": str(e)}
115
- finally:
116
- for _, filetuple in files:
117
- filetuple[1].close()
118
-
119
- def send_images(message_id, to_number, image_paths, caption="Here are your images!", retries=3):
120
- """
121
- Sends multiple images concurrently by calling send_image for each image in parallel.
122
- """
123
- responses = []
124
- threads = []
125
- lock = threading.Lock()
126
-
127
- def send_single(image_path):
128
- resp = send_image(message_id, to_number, image_path, caption)
129
- with lock:
130
- responses.append(resp)
131
-
132
- for path in image_paths:
133
- t = threading.Thread(target=send_single, args=(path,))
134
- t.start()
135
- threads.append(t)
136
- for t in threads:
137
- t.join()
138
- return responses
139
 
140
  def send_audio(message_id, to_number, audio_path, retries=3):
141
  logging.debug("send_audio")
@@ -182,39 +158,24 @@ def response_audio(message_id, chat_id, prompt):
182
  send_message(message_id, chat_id, "Error generating audio. Try again later.")
183
 
184
  def handle_image_generation(message_id, chat_id, prompt):
185
- try:
186
- images_info = []
187
- # Generate 4 images using the same prompt.
188
- for _ in range(4):
189
  img, path, ret_prompt, url = generate_image(prompt, message_id, message_id, image_dir)
190
- if not img:
 
 
 
 
 
 
 
 
 
 
191
  send_message(message_id, chat_id, "Image generation failed.")
192
- return
193
- images_info.append((path, ret_prompt, url))
194
-
195
- # Build caption with URLs of all images.
196
- caption = "✨ Images ready:\n" + "\n".join(url for _, _, url in images_info)
197
-
198
- # Send first 3 images without caption.
199
- for path, _, _ in images_info[:3]:
200
- result = send_image(message_id, chat_id, path, caption="")
201
- if "error" in result:
202
- send_message(message_id, chat_id, "Failed to send one of the images.")
203
-
204
- # Send the last image with the caption.
205
- last_image_path = images_info[3][0]
206
- result = send_image(message_id, chat_id, last_image_path, caption=caption)
207
- if "error" in result:
208
- send_message(message_id, chat_id, "Failed to send the final image with caption.")
209
-
210
- # Cleanup generated image files.
211
- for path, _, _ in images_info:
212
- if os.path.exists(path):
213
- os.remove(path)
214
- except Exception as e:
215
- logging.error("Error in handle_image_generation: %s", e)
216
- send_message(message_id, chat_id, "Error generating images.")
217
-
218
 
219
  # --- Startup Message ---
220
  def send_startup_message():
@@ -227,22 +188,22 @@ def send_startup_message():
227
  logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
228
 
229
  help_text = (
230
- "πŸ€– *Hi there, I'm Eve!* Here are the commands you can use:\n\n"
231
- "β€’ */help* – _Show this help message._\n"
232
- "β€’ */summarize <text>* – _Get a quick summary of your text._\n"
233
- "β€’ */translate <language>|<text>* – _Translate text to your chosen language._\n"
234
- "β€’ */joke* – _Enjoy a random, funny joke._\n"
235
- "β€’ */weather <location>* – _Get the current weather for a location._\n"
236
- "β€’ */inspire* – _Receive a short inspirational quote._\n"
237
- "β€’ */trivia* – _Start a new trivia question._\n"
238
- "β€’ */answer [your answer]* – _Reveal the trivia answer or check your answer if provided._\n"
239
- "β€’ */meme <text>* – _Generate a fun meme image._\n"
240
- "β€’ */poll <Question>|<Option1>|<Option2>|…* – _Create a poll._\n"
241
- "β€’ */results* – _See current poll results._\n"
242
- "β€’ */endpoll* – _End the poll and show final results._\n"
243
- "β€’ */gen <prompt>* – _Generate an image from your prompt._\n\n"
244
- "Send any other text and I'll reply with a voice message. I'm here to help, so don't hesitate to ask!"
245
- )
246
 
247
  # --- Webhook ---
248
  @app.post("/whatsapp")
@@ -359,12 +320,14 @@ async def whatsapp_webhook(request: Request):
359
  send_message(mid, chat, "Failed to generate trivia. Please try again.")
360
  return {"success": True}
361
 
362
- # ANSWER
363
  if low.startswith("/answer"):
 
364
  user_response = body[len("/answer"):].strip()
365
  if chat in trivia_store:
366
  correct_answer = trivia_store[chat]["answer"]
367
  question = trivia_store[chat]["question"]
 
368
  if user_response:
369
  eval_prompt = (
370
  f"Question: {question}\n"
@@ -469,6 +432,7 @@ def index():
469
  return "Server is running!"
470
 
471
  if __name__ == "__main__":
 
472
  def send_startup_message():
473
  if BOT_STATUS_CHAT:
474
  startup_msg = "🌟 Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"
 
112
  except requests.RequestException as e:
113
  if i == retries - 1:
114
  return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  def send_audio(message_id, to_number, audio_path, retries=3):
117
  logging.debug("send_audio")
 
158
  send_message(message_id, chat_id, "Error generating audio. Try again later.")
159
 
160
  def handle_image_generation(message_id, chat_id, prompt):
161
+ for i in range(4):
162
+ try:
 
 
163
  img, path, ret_prompt, url = generate_image(prompt, message_id, message_id, image_dir)
164
+ if img:
165
+ formatted_ret_prompt = "\n\n".join(
166
+ f"_{paragraph.strip()}_" for paragraph in ret_prompt.split("\n\n") if paragraph.strip()
167
+ )
168
+ send_image(
169
+ message_id,
170
+ chat_id,
171
+ path,
172
+ caption=f"✨ Image ready: {url}\n>{chr(8203)} {formatted_ret_prompt}"
173
+ )
174
+ else:
175
  send_message(message_id, chat_id, "Image generation failed.")
176
+ except Exception as e:
177
+ logging.error("Error in handle_image_generation: %s", e)
178
+ send_message(message_id, chat_id, "Error generating image.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  # --- Startup Message ---
181
  def send_startup_message():
 
188
  logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
189
 
190
  help_text = (
191
+ "πŸ€– *Hi there, I'm Eve!* Here are the commands you can use:\n\n"
192
+ "β€’ */help* – _Show this help message._\n"
193
+ "β€’ */summarize <text>* – _Get a quick summary of your text._\n"
194
+ "β€’ */translate <language>|<text>* – _Translate text to your chosen language._\n"
195
+ "β€’ */joke* – _Enjoy a random, funny joke._\n"
196
+ "β€’ */weather <location>* – _Get the current weather for a location._\n"
197
+ "β€’ */inspire* – _Receive a short inspirational quote._\n"
198
+ "β€’ */trivia* – _Start a new trivia question._\n"
199
+ "β€’ */answer [your answer]* – _Reveal the trivia answer or check your answer if provided._\n"
200
+ "β€’ */meme <text>* – _Generate a fun meme image._\n"
201
+ "β€’ */poll <Question>|<Option1>|<Option2>|…* – _Create a poll._\n"
202
+ "β€’ */results* – _See current poll results._\n"
203
+ "β€’ */endpoll* – _End the poll and show final results._\n"
204
+ "β€’ */gen <prompt>* – _Generate an image from your prompt._\n\n"
205
+ "Send any other text and I'll reply with a voice message. I'm here to help, so don't hesitate to ask!"
206
+ )
207
 
208
  # --- Webhook ---
209
  @app.post("/whatsapp")
 
320
  send_message(mid, chat, "Failed to generate trivia. Please try again.")
321
  return {"success": True}
322
 
323
+ # ANSWER: Accept any message starting with /answer. If additional text is provided, check it.
324
  if low.startswith("/answer"):
325
+ # Remove command and any extra spaces
326
  user_response = body[len("/answer"):].strip()
327
  if chat in trivia_store:
328
  correct_answer = trivia_store[chat]["answer"]
329
  question = trivia_store[chat]["question"]
330
+ # If user provided an answer, evaluate it via LLM; otherwise, just reveal the answer.
331
  if user_response:
332
  eval_prompt = (
333
  f"Question: {question}\n"
 
432
  return "Server is running!"
433
 
434
  if __name__ == "__main__":
435
+ # Send startup message on launch
436
  def send_startup_message():
437
  if BOT_STATUS_CHAT:
438
  startup_msg = "🌟 Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"