Explorar el Código

feat: store temporary images in-memory (#282)

* Use no disk and improve speed!

* Update greetings.py

* Update functions.py
ÁÑÑÍHÌLÅTØR SPÄRK hace 1 año
padre
commit
f39c68fc73
Se han modificado 2 ficheros con 23 adiciones y 26 borrados
  1. 0 2
      wbb/modules/greetings.py
  2. 23 24
      wbb/utils/functions.py

+ 0 - 2
wbb/modules/greetings.py

@@ -23,7 +23,6 @@ SOFTWARE.
 """
 
 import asyncio
-import os
 from re import findall
 from datetime import datetime, timedelta
 from random import shuffle
@@ -221,7 +220,6 @@ async def handle_new_member(member, chat):
         caption=text,
         reply_markup=keyboard,
     )
-    os.remove(captcha_image)
 
     # Save captcha answers etc in mongodb in case the bot gets crashed or restarted.
     await update_captcha_cache(answers_dicc)

+ 23 - 24
wbb/utils/functions.py

@@ -56,43 +56,42 @@ def generate_captcha():
         return chr(randint(65, 90))
 
     def rndColor():
-        return randint(64, 255), randint(64, 255), randint(64, 255)
+        return (randint(64, 255), randint(64, 255), randint(64, 255))
 
     def rndColor2():
-        return randint(32, 127), randint(32, 127), randint(32, 127)
-
-    # Generate a 4 letter word
-    def gen_wrong_answer():
-        word = ""
-        for _ in range(4):
-            word += gen_letter()
-        return word
-
-    # Generate 8 wrong captcha answers
-    wrong_answers = []
-    for _ in range(8):
-        wrong_answers.append(gen_wrong_answer())
-
-    width = 80 * 4
-    height = 100
+        return (randint(32, 127), randint(32, 127), randint(32, 127))
+
+    wrong_answers = [
+        "".join(gen_letter() for _ in range(4)) for _ in range(8)
+    ]
+
+    width, height = 320, 100
     correct_answer = ""
     font = ImageFont.truetype("assets/arial.ttf", 55)
-    file = f"assets/{randint(1000, 9999)}.jpg"
+
+    # White background
     image = Image.new("RGB", (width, height), (255, 255, 255))
     draw = ImageDraw.Draw(image)
 
-    # Draw random points on image
-    for x in range(width):
-        for y in range(height):
-            draw.point((x, y), fill=rndColor())
+    # Noise (draw random lines instead of painting every pixel)
+    for _ in range(120):
+        x1, y1 = randint(0, width), randint(0, height)
+        x2, y2 = randint(0, width), randint(0, height)
+        draw.line((x1, y1, x2, y2), fill=rndColor(), width=1)
 
+    # Text
     for t in range(4):
         letter = gen_letter()
         correct_answer += letter
         draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
+
     image = image.filter(ImageFilter.BLUR)
-    image.save(file, "jpeg")
-    return [file, correct_answer, wrong_answers]
+    
+    buf = BytesIO() # on memory
+    image.save(buf, "JPEG")
+    buf.name = "captcha.jpg"
+    buf.seek(0)
+    return [buf, correct_answer, wrong_answers]
 
 
 def test_speedtest():