فهرست منبع

[2.8.2] Cleaning code

Penta 3 هفته پیش
والد
کامیت
1204ba62af
1فایلهای تغییر یافته به همراه26 افزوده شده و 13 حذف شده
  1. 26 13
      chatbot.py

+ 26 - 13
chatbot.py

@@ -132,15 +132,18 @@ def split_message(message, max_length=2000):
 
 def load_conversation_history():
     global conversation_history
+
     if os.path.isfile(CONVERSATION_HISTORY_FILE):
         try:
             with open(CONVERSATION_HISTORY_FILE, 'r', encoding='utf-8') as f:
                 loaded_history = json.load(f)
+
                 # Exclure uniquement le PERSONALITY_PROMPT
                 conversation_history = [
                     msg for msg in loaded_history
                     if not (msg.get("role") == "system" and msg.get("content") == PERSONALITY_PROMPT)
                 ]
+
             logger.info(f"Historique chargé depuis {CONVERSATION_HISTORY_FILE}")
         except Exception as e:
             logger.error(f"Erreur lors du chargement de l'historique : {e}")
@@ -148,30 +151,30 @@ def load_conversation_history():
     else:
         logger.info(f"Aucun fichier d'historique trouvé. Un nouveau fichier sera créé à {CONVERSATION_HISTORY_FILE}")
 
+
 def has_text(text):
-    """
-    Détermine si le texte fourni est non vide après suppression des espaces.
-    """
+    """Détermine si le texte fourni est non vide après suppression des espaces."""
     return bool(text.strip())
 
-def resize_image(image_bytes, mode='high', attachment_filename=None):
+
+def resize_image(image_bytes, attachment_filename=None):
     """Redimensionne l'image selon le mode spécifié."""
+
     try:
         with Image.open(BytesIO(image_bytes)) as img:
             original_format = img.format  # Stocker le format original
 
-            if mode == 'high':
-                img.thumbnail((2000, 2000))
-                if min(img.size) < 768:
-                    scale = 768 / min(img.size)
-                    new_size = tuple(int(x * scale) for x in img.size)
-                    img = img.resize(new_size, Image.Resampling.LANCZOS)
-            elif mode == 'low':
-                img = img.resize((512, 512))
+            img.thumbnail((2000, 2000))
+
+            if min(img.size) < 768:
+                scale = 768 / min(img.size)
+                new_size = tuple(int(x * scale) for x in img.size)
+                img = img.resize(new_size, Image.Resampling.LANCZOS)
 
             buffer = BytesIO()
             img_format = img.format or _infer_image_format(attachment_filename)
             img.save(buffer, format=img_format)
+
             return buffer.getvalue()
     except Exception as e:
         logger.error(f"Erreur lors du redimensionnement de l'image : {e}")
@@ -179,15 +182,19 @@ def resize_image(image_bytes, mode='high', attachment_filename=None):
 
 async def encode_image_from_attachment(attachment, mode='high'):
     """Encode une image depuis une pièce jointe en base64 après redimensionnement."""
+
     image_data = await attachment.read()
-    resized_image = resize_image(image_data, mode=mode, attachment_filename=attachment.filename)
+    resized_image = resize_image(image_data, attachment_filename=attachment.filename)
+
     return base64.b64encode(resized_image).decode('utf-8')
 
 def _infer_image_format(filename):
     """Déduit le format de l'image basé sur l'extension du fichier."""
+
     if filename:
         _, ext = os.path.splitext(filename)
         ext = ext.lower()
+
         format_mapping = {
             '.jpg': 'JPEG',
             '.jpeg': 'JPEG',
@@ -198,6 +205,7 @@ def _infer_image_format(filename):
         }
 
         return format_mapping.get(ext, 'PNG')
+
     return 'PNG'
 
 # Fonction de sauvegarde de l'historique
@@ -217,9 +225,11 @@ except ValueError:
 class MyDiscordClient(discord.Client):
     async def close(self):
         global openai_client
+
         if openai_client is not None:
             await openai_client.close()
             openai_client = None
+
         await super().close()
 
 # Initialiser le client Discord avec les intents modifiés
@@ -381,8 +391,11 @@ async def on_message(message):
 
         conversation_history = []
         save_conversation_history()
+
         await message.channel.send("✅ L'historique des conversations a été réinitialisé.")
+
         logger.info(f"Historique des conversations réinitialisé par {message.author}.")
+
         return  # Arrêter le traitement du message après la réinitialisation
 
     # Extensions de fichiers autorisées