Chandima Prabhath commited on
Commit
59da9b5
·
1 Parent(s): 6e6c1ff

Enhance image sending functionality to support concurrent uploads of multiple images

Browse files
Files changed (1) hide show
  1. app.py +23 -24
app.py CHANGED
@@ -112,32 +112,30 @@ 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
 
116
  def send_images(message_id, to_number, image_paths, caption="Here are your images!", retries=3):
117
  """
118
- Uploads multiple images at once.
119
  """
120
- chat_id = to_number if to_number.endswith("@g.us") else to_number
121
- url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
122
- payload = {"chatId": chat_id, "caption": caption, "quotedMessageId": message_id}
123
- files = []
124
- file_handles = []
125
- try:
126
- for idx, image_path in enumerate(image_paths):
127
- f = open(image_path, "rb")
128
- file_handles.append(f)
129
- files.append(("file", (f"image_{idx}.jpg", f, "image/jpeg")))
130
- for i in range(retries):
131
- try:
132
- r = requests.post(url, data=payload, files=files)
133
- r.raise_for_status()
134
- return r.json()
135
- except requests.RequestException as e:
136
- if i == retries - 1:
137
- return {"error": str(e)}
138
- finally:
139
- for f in file_handles:
140
- f.close()
141
 
142
  def send_audio(message_id, to_number, audio_path, retries=3):
143
  logging.debug("send_audio")
@@ -195,8 +193,9 @@ def handle_image_generation(message_id, chat_id, prompt):
195
  images_info.append((path, ret_prompt, url))
196
  # Create a caption listing the URLs of all generated images.
197
  caption = "✨ Images ready:\n" + "\n".join(url for _, _, url in images_info)
198
- # Send all generated images at once.
199
  image_paths = [path for path, _, _ in images_info]
 
200
  send_images(message_id, chat_id, image_paths, caption=caption)
201
  # Cleanup generated image files.
202
  for path in image_paths:
@@ -349,7 +348,7 @@ async def whatsapp_webhook(request: Request):
349
  send_message(mid, chat, "Failed to generate trivia. Please try again.")
350
  return {"success": True}
351
 
352
- # ANSWER: Accept any message starting with /answer. If additional text is provided, check it.
353
  if low.startswith("/answer"):
354
  user_response = body[len("/answer"):].strip()
355
  if chat in trivia_store:
 
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")
 
193
  images_info.append((path, ret_prompt, url))
194
  # Create a caption listing the URLs of all generated images.
195
  caption = "✨ Images ready:\n" + "\n".join(url for _, _, url in images_info)
196
+ # Extract the file paths from the generated images.
197
  image_paths = [path for path, _, _ in images_info]
198
+ # Send all generated images concurrently.
199
  send_images(message_id, chat_id, image_paths, caption=caption)
200
  # Cleanup generated image files.
201
  for path in image_paths:
 
348
  send_message(mid, chat, "Failed to generate trivia. Please try again.")
349
  return {"success": True}
350
 
351
+ # ANSWER
352
  if low.startswith("/answer"):
353
  user_response = body[len("/answer"):].strip()
354
  if chat in trivia_store: