Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
Β·
1a71a94
1
Parent(s):
3e7203b
fix image generation failing
Browse files
app.py
CHANGED
@@ -5,7 +5,7 @@ Description: A comprehensive WhatsApp bot with a professional, class-based struc
|
|
5 |
Features include image generation, image editing, voice replies,
|
6 |
and various utility functions, all handled by an asynchronous task queue.
|
7 |
Includes request logging and chat ID filtering.
|
8 |
-
Version 2.
|
9 |
"""
|
10 |
|
11 |
import os
|
@@ -306,7 +306,7 @@ class WhatsAppBot:
|
|
306 |
# NEW: Cache for bot-sent image message IDs and their local file paths
|
307 |
self.sent_image_path_cache = defaultdict(lambda: deque(maxlen=50))
|
308 |
|
309 |
-
self.fastapi_app = FastAPI(title="WhatsApp Eve Bot", version="2.
|
310 |
self._setup_routes()
|
311 |
self._start_workers()
|
312 |
|
@@ -539,7 +539,27 @@ class WhatsAppBot:
|
|
539 |
for i in range(count):
|
540 |
path = None
|
541 |
try:
|
542 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
543 |
caption = f"β¨ Image {i+1}/{count}: {prompt}"
|
544 |
response = self.api_client.send_file(chat_id, path, caption, mid)
|
545 |
|
@@ -548,12 +568,17 @@ class WhatsAppBot:
|
|
548 |
self.logger.info(f"Caching sent image path for message {sent_message_id}: {path}")
|
549 |
self._manage_cached_file(chat_id, sent_message_id, path)
|
550 |
else:
|
|
|
|
|
551 |
self.logger.warning(f"Could not get sent message ID for {path}. Deleting file.")
|
552 |
-
os.
|
|
|
553 |
except Exception as e:
|
554 |
-
|
555 |
-
self.
|
556 |
-
|
|
|
|
|
557 |
|
558 |
def _task_edit_image(self, task: Dict[str, Any]):
|
559 |
chat_id, mid, prompt = task["chat_id"], task["message_id"], task["prompt"]
|
@@ -662,5 +687,4 @@ if __name__ == "__main__":
|
|
662 |
except KeyboardInterrupt:
|
663 |
print("\nπ Bot stopped by user.")
|
664 |
except Exception as e:
|
665 |
-
logging.basicConfig()
|
666 |
logging.getLogger().critical(f"β A fatal error occurred: {e}", exc_info=True)
|
|
|
5 |
Features include image generation, image editing, voice replies,
|
6 |
and various utility functions, all handled by an asynchronous task queue.
|
7 |
Includes request logging and chat ID filtering.
|
8 |
+
Version 2.3.0: Fixed image generation ID mismatch issue.
|
9 |
"""
|
10 |
|
11 |
import os
|
|
|
306 |
# NEW: Cache for bot-sent image message IDs and their local file paths
|
307 |
self.sent_image_path_cache = defaultdict(lambda: deque(maxlen=50))
|
308 |
|
309 |
+
self.fastapi_app = FastAPI(title="WhatsApp Eve Bot", version="2.3.0")
|
310 |
self._setup_routes()
|
311 |
self._start_workers()
|
312 |
|
|
|
539 |
for i in range(count):
|
540 |
path = None
|
541 |
try:
|
542 |
+
# Create a unique ID for each image in the batch to avoid mismatches.
|
543 |
+
unique_image_id = f"{mid}_{i}"
|
544 |
+
|
545 |
+
# Call the image generation library with matching IDs
|
546 |
+
generation_result = generate_image(
|
547 |
+
prompt,
|
548 |
+
unique_image_id,
|
549 |
+
unique_image_id,
|
550 |
+
self.config.IMAGE_DIR,
|
551 |
+
width=task.get("width"),
|
552 |
+
height=task.get("height")
|
553 |
+
)
|
554 |
+
|
555 |
+
# If generation fails, the result will be None. Handle this gracefully.
|
556 |
+
if not generation_result:
|
557 |
+
self.logger.error(f"Image generation {i+1} failed because the generator returned None.")
|
558 |
+
self.api_client.send_message(chat_id, f"π’ Failed to generate image {i+1}.", mid)
|
559 |
+
continue # Move to the next image in the loop
|
560 |
+
|
561 |
+
_, path, _, _ = generation_result
|
562 |
+
|
563 |
caption = f"β¨ Image {i+1}/{count}: {prompt}"
|
564 |
response = self.api_client.send_file(chat_id, path, caption, mid)
|
565 |
|
|
|
568 |
self.logger.info(f"Caching sent image path for message {sent_message_id}: {path}")
|
569 |
self._manage_cached_file(chat_id, sent_message_id, path)
|
570 |
else:
|
571 |
+
# If we can't get the message ID, we can't cache the image for later editing.
|
572 |
+
# It's better to delete it to avoid filling up the disk.
|
573 |
self.logger.warning(f"Could not get sent message ID for {path}. Deleting file.")
|
574 |
+
if path and os.path.exists(path):
|
575 |
+
os.remove(path)
|
576 |
except Exception as e:
|
577 |
+
# Catch any other unexpected errors during the process
|
578 |
+
self.logger.error(f"Image generation {i+1} failed with an exception: {e}", exc_info=True)
|
579 |
+
self.api_client.send_message(chat_id, f"π’ An error occurred while generating image {i+1}.", mid)
|
580 |
+
if path and os.path.exists(path):
|
581 |
+
os.remove(path) # Clean up partially created files
|
582 |
|
583 |
def _task_edit_image(self, task: Dict[str, Any]):
|
584 |
chat_id, mid, prompt = task["chat_id"], task["message_id"], task["prompt"]
|
|
|
687 |
except KeyboardInterrupt:
|
688 |
print("\nπ Bot stopped by user.")
|
689 |
except Exception as e:
|
|
|
690 |
logging.getLogger().critical(f"β A fatal error occurred: {e}", exc_info=True)
|