У меня выходит ошибка в коде, помоги мне. Ошибка: Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), main.dict)
File "", line 244, in
File "/storage/emulated/0/лицензии/license_generator.py", line 61, in init
self.request_semaphore = Semaphore(self.config["max_concurrent_requests"])
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'max_concurrent_requests'
[Program finished] код:
import logging
import os
import json
from typing import Tuple, List, Dict, Any, Optional, TypeVar, Generic
from collections import OrderedDict
import requests
import io
from PIL import Image, ImageDraw, ImageFont
import random
import math
import qrcode
import cProfile
import pstats
import numpy as np
import functools
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
import time
from threading import Semaphore
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
T = TypeVar('T')
class LRUCache(Generic[T]):
def init(self, capacity: int):
self.capacity = capacity
self.cache: OrderedDict[Any, T] = OrderedDict()
def get(self, key: Any) -> Optional[T]:
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return None
def put(self, key: Any, value: T) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
def __contains__(self, key: Any) -> bool:
return key in self.cache
class ImageProcessor:
def init(self, config: Dict[str, Any]):
self.config = config
self.mask_cache: LRUCache[Image.Image] = LRUCache(self.config["cache_max_size"])
self.gradient_cache: LRUCache[Image.Image] = LRUCache(self.config["cache_max_size"])
self.resized_cache: LRUCache[Image.Image] = LRUCache(self.config["cache_max_size"])
self.image_cache: LRUCache[Image.Image] = LRUCache(self.config["cache_max_size"])
self.fonts: Dict[str, ImageFont.FreeTypeFont] = {
name: ImageFont.truetype(data["file"], size=data["size"]) if os.path.exists(data["file"]) else ImageFont.load_default()
for name, data in self.config["font_config"].items()}
self.executor = ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())
self.last_request_time: Dict[int, float] = {}
self.request_semaphore = Semaphore(self.config["max_concurrent_requests"])
self.downloaded_images = set()
def get_font(self, font_name: str) -> ImageFont.FreeTypeFont:
return self.fonts[font_name]
def download_image(self, image_url: str) -> Optional[Image.Image]:
if image_url in self.downloaded_images:
logging.info(f"Изображение {image_url} уже загружено")
return self.image_cache.get(image_url)
try:
response = requests.get(image_url, stream=True)
response.raise_for_status()
with Image.open(io.BytesIO(response.content)) as image:
image = image.convert('RGBA')
self.image_cache.put(image_url, image)
self.downloaded_images.add(image_url)
logging.info(f"Изображение {image_url} успешно загружено и добавлено в кеш. Размер: {image.size}")
return image
except requests.exceptions.RequestException as e:
logging.error(f"Ошибка при скачивании изображения: {e}")
return None
except Exception as e:
logging.error(f"Ошибка открытия изображения: {e}")
return None
def generate_qr_code(self, url: str) -> Image.Image:
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=5, border=2)
qr.add_data(url)
qr.make(fit=True)
return qr.make_image(fill_color="black", back_color="white")
def create_rounded_rectangle(self, size: Tuple[int, int], radius: int,
color: Tuple[int, int, int, int]) -> Image.Image:
rectangle = Image.new('RGBA', size, (0, 0, 0, 0))
ImageDraw.Draw(rectangle).rounded_rectangle((0, 0, size[0], size[1]), radius=radius, fill=color)
return rectangle
def generate_random_corner_points(self, width: int, height: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
corners = [(0, 0), (width, 0), (0, height), (width, height)]
p1 = random.choice(corners)
corners.remove(p1)
return p1, random.choice(corners)
def _create_gradient_background_process(self, size: Tuple[int, int], start_color: Tuple[int, int, int, int],
end_color: Tuple[int, int, int, int], point1: Tuple[int, int],
point2: Tuple[int, int]) -> np.ndarray:
x1, y1 = point1
x2, y2 = point2
dx, dy = x2 - x1, y2 - y1
length = math.sqrt(dx ** 2 + dy ** 2)
if length == 0:
return np.full((size[1], size[0], 4), start_color, dtype=np.uint8)
x, y = np.meshgrid(np.arange(size[0]), np.arange(size[1]))
px, py = x - x1, y - y1
t = np.clip((px * dx + py * dy) / length ** 2, 0, 1).astype(np.float64)
start_color_array = np.array(start_color, dtype=np.float64)
end_color_array = np.array(end_color, dtype=np.float64)
lerped_colors = (start_color_array + (end_color_array - start_color_array) * t[:, :, None]).astype(np.uint8)
return lerped_colors
def create_gradient_background(self, size: Tuple[int, int], start_color: Tuple[int, int, int, int],
end_color: Tuple[int, int, int, int], point1: Tuple[int, int],
point2: Tuple[int, int]) -> Image.Image:
cache_key = hash((size, start_color, end_color, point1, point2))
cached_gradient = self.gradient_cache.get(cache_key)
if cached_gradient:
return cached_gradient
gradient_array = self._create_gradient_background_process(size, start_color, end_color, point1, point2)
gradient = Image.fromarray(gradient_array)
self.gradient_cache.put(cache_key, gradient)
return gradient
@functools.lru_cache(maxsize=32)
def create_rounded_mask(self, width: int, height: int, radius: int) -> Image.Image:
mask = Image.new('L', (width, height), 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, width, height), radius=radius, fill=255)
return mask
@functools.lru_cache(maxsize=32)
def create_partial_rounded_mask(self, width: int, height: int, radius: int, percentage: float) -> Image.Image:
mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(mask)
round_width = int(width * percentage)
draw.rectangle((0, 0, round_width, height), fill=255)
draw.rounded_rectangle((0, 0, round_width, height), radius=radius, fill=255)
return mask
def create_cut_gradient_mask(self, width: int, height: int, corner_radius: int) -> Image.Image:
cache_key = hash((width, height, corner_radius))
cached_mask = self.mask_cache.get(cache_key)
if cached_mask:
return cached_mask
mask = Image.new('L', (width, height), 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, width, height), radius=corner_radius, fill=255)
self.mask_cache.put(cache_key, mask)
return mask
def crop_and_center_image(self, image: Image.Image, target_width: int, target_height: int) -> Image.Image:
cache_key = hash((image.tobytes(), target_width, target_height))
cached_image = self.resized_cache.get(cache_key)
if cached_image:
return cached_image
iw, ih = image.size
scale = max(target_width / iw, target_height / ih)
nw, nh = int(iw * scale), int(ih * scale)
resized_image = image.resize((nw, nh), Image.Resampling.LANCZOS)
w, h = resized_image.size
left = (w - target_width) // 2
top = (h - target_height) // 2
cropped_image = resized_image.crop((left, top, left + target_width, top + target_height))
self.resized_cache.put(cache_key, cropped_image)
logging.info(f"Изображение обрезано до {target_width}x{target_height} с сохранением пропорций. Оригинал: {iw}x{ih}")
return cropped_image
def draw_text_with_stroke(self, draw: ImageDraw.ImageDraw, x: int, y: int, text: str,
font: ImageFont.FreeTypeFont, fill: Tuple[int, int, int], stroke_width: int,
stroke_color: Tuple[int, int, int], stroke_opacity: float) -> None:
if stroke_width > 0:
color = (*stroke_color[:3], int(stroke_color[3] * stroke_opacity))
draw.text((x - stroke_width, y), text, font=font, fill=color)
draw.text((x + stroke_width, y), text, font=font, fill=color)
draw.text((x, y - stroke_width), text, font=font, fill=color)
draw.text((x, y + stroke_width), text, font=font, fill=color)
draw.text((x, y), text, font=font, fill=fill)
def draw_rectangle_with_stroke_and_shadow(self, draw: ImageDraw.ImageDraw, x: int, y: int, width: int, height: int,
radius: int, color: Tuple[int, int, int, int], stroke_width: int,
stroke_color: Tuple[int, int, int, int]) -> None:
if stroke_width > 0:
draw.rounded_rectangle((x, y, x + width, y + height), radius=radius, fill=color, outline=stroke_color,
width=stroke_width)
else:
draw.rounded_rectangle((x, y, x + width, y + height), radius=radius, fill=color)
def create_rounded_mask_for_qr(self, size: Tuple[int, int], radius: int) -> Image.Image:
mask = Image.new('L', size, 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, *size), radius=radius, fill=255)
return mask
def mirror_image(self, image: Image.Image) -> Image.Image:
return image.transpose(Image.FLIP_LEFT_RIGHT)
def analyze_image_colors(self, image: Image.Image) -> List[Tuple[int, int, int, int]]:
scale_size = self.config["color_analysis_scale_size"]
img = image.resize(scale_size)
img_array = np.array(img, dtype=np.uint8)
width, height, _ = img_array.shape
center_x = width // 2
line_colors = []
for y in range(height):
if img_array[y, center_x, 3] > 0: # Check if alpha is greater than zero
line_colors.append(tuple(img_array[y, center_x, :3])) # Extract RGB from numpy array
# Получаем уникальные цвета и выбираем 3-4 случайных цвета
unique_colors = list(set(line_colors))
if not unique_colors:
return []
num_colors = min(len(unique_colors), 4)
selected_colors = random.sample(unique_colors, num_colors)
return [tuple(c) + (255,) for c in selected_colors]
def color_distance(self, color1: Tuple[int, int, int, ], color2: Tuple[int, int, int]) -> float:
return math.sqrt(sum((color1[i] - color2[i]) ** 2 for i in range(3)))
def find_close_color(self, main_color: Tuple[int, int, int, ],
colors: List[Tuple[int, int, int, ]], min_distance: int,
max_distance: int) -> Optional[Tuple[int, int, int, int]]:
for color in colors:
if color == main_color:
continue
dist = self.color_distance(main_color, color)
if min_distance <= dist <= max_distance:
return color
return None
def choose_gradient_colors(self, colors: List[Tuple[int, int, int, int]]) -> Tuple[
Tuple[int, int, int, int], Tuple[int, int, int, int]]:
if not colors:
return (255, 255, 255, 255), (0, 0, 0, 255)
if len(colors) == 1:
return colors[0], colors[0]
return random.sample(colors, 2)
def process_license_async(self, user_id: int, background: Image.Image, user_data: Dict[str, Any],
qr_code: Optional[Image.Image], callback):
current_time = time.time()
if user_id in self.last_request_time and (current_time - self.last_request_time[user_id] < self.config["request_interval"]):
logging.warning(f"Запрос от пользователя {user_id} отклонен из-за ограничения частоты.")
return
self.last_request_time[user_id] = current_time
def safe_callback(image):
try:
callback(image)
except Exception as e:
logging.error(f"Ошибка в callback: {e}")
self.request_semaphore.release()
self.request_semaphore.acquire()
future = self.executor.submit(self.create_license_image, background, user_data, qr_code)
future.add_done_callback(lambda f: safe_callback(f.result()))
def create_license_image(self, background: Image.Image, user_data: Dict[str, Any],
qr_code: Optional[Image.Image]) -> Optional[Image.Image]:
if not background:
logging.error("Фон не загружен")
return None
iw, ih = 5000, 2813
main_background = Image.new("RGBA", (iw, ih), (230, 230, 230, 255))
start_color, end_color = self.choose_gradient_colors(self.analyze_image_colors(background))
gw, gh = self.config["gradient_config"]["width"], self.config["gradient_config"]["height"]
p1, p2 = self.generate_random_corner_points(gw, gh)
gradient_mask = self.create_cut_gradient_mask(gw, gh, self.config["gradient_config"]["radius"])
gradient_background = self.create_gradient_background((gw, gh), start_color, end_color, p1, p2)
gradient_background = Image.composite(gradient_background, Image.new('RGBA', (gw, gh), (0, 0, 0, 0)), gradient_mask)
h_percent = self.config["background_config"].get("horizontal_percentage", 1.0)
elements = sorted([*({"type": "rectangle", "config": c} for _, c in self.config["rectangle_config"].items()),
{"type": "background", "image": background,
"config": self.config["background_config"]}], key=lambda x: x["config"].get("layer", 0))
for element in elements:
if element["type"] == "background":
tw, th = element["config"]["target_width"], element["config"]["target_height"]
resized = self.crop_and_center_image(element["image"], tw, th)
if resized:
mask = self.create_rounded_mask(tw, th, element["config"]["radius"])
partial_mask = self.create_partial_rounded_mask(tw, th, element["config"]["radius"], h_percent)
mask.paste(partial_mask, (0, 0), partial_mask)
resized.putalpha(mask)
mirrored = self.mirror_image(resized)
mx, my = element["config"].get("mirror_offset_x", 0), element["config"].get("mirror_offset_y", 0)
main_background.paste(mirrored,
(element["config"]["x"] - mirrored.width + element["config"]["size"][0] + mx,
element["config"]["y"] + my), mirrored)
main_background.paste(resized, (element["config"]["x"], element["config"]["y"]), resized)
elif element["type"] == "rectangle":
draw = ImageDraw.Draw(main_background)
x, y = element["config"]["x"], element["config"]["y"]
w, h = element["config"]["size"][0], element["config"]["size"][1]
r, c = element["config"]["radius"], element["config"]["color"]
sw, sc = element["config"]["stroke_width"], element["config"]["stroke_color"]
self.draw_rectangle_with_stroke_and_shadow(draw, x, y, w, h, r, c, sw, sc)
main_background.paste(gradient_background,
(self.config["gradient_config"]["x"], self.config["gradient_config"]["y"]),
gradient_background)
draw = ImageDraw.Draw(main_background)
for config in self.config["text_config"].values():
self.draw_text_with_stroke(draw, config["x"], config["y"], config["text"].format(**user_data),
self.get_font(config["font"]), config["fill"], config["stroke_width"],
config["stroke_color"], config["stroke_opacity"])
if qr_code:
qr_resized = qr_code.resize((200, 200))
qr_mask = self.create_rounded_mask_for_qr(qr_resized.size, 20)
qr_resized = qr_resized.convert('RGBA')
qr_resized.putalpha(qr_mask)
main_background.paste(qr_resized, (540, 600), qr_resized)
try:
light_background = Image.open(self.config["light_background_image"]).convert("RGBA").resize((iw, ih))
main_background.paste(light_background, (0, 0), light_background)
except Exception as e:
logging.error(f"Ошибка загрузки фона: {e}")
return main_background
if name == "main":
import time
def load_config(config_path):
try:
with open(config_path, 'r') as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f"Error: config file not found at: {config_path}")
return None
except json.JSONDecodeError:
print(f"Error: Failed to decode JSON in {config_path}")
return None
config_path = "config.json"
config = load_config(config_path)
if config is None:
exit(1)
processor = ImageProcessor(config)
user_data = {"name": "John Doe", "address": "123 Main St"}
image_url = "https://placekitten.com/200/300"
def send_image(user_id, image):
# Вставьте сюда ваш код для отправки изображения
print(f"Изображение отправлено: {user_id}.")
def test_process(user_id):
background_image = processor.download_image(image_url)
if background_image is not None:
qr_code = processor.generate_qr_code("https://example.com")
cropped_image = processor.crop_and_center_image(background_image, 1950, 2500)
def callback(license_image):
if license_image:
send_image(user_id, license_image)
else:
print("Failed to create license image.")
processor.process_license_async(user_id, cropped_image, user_data, qr_code, callback)
return True
else:
print("Failed to download image.")
return False
profile_file = 'profile_results.prof'
profiler = cProfile.Profile()
profiler.enable()
start_time = time.time()
# Запускаем несколько процессов одновременно
for i in range(10):
test_process(389769778 + i) # Отправляем запросы от нескольких пользователей
end_time = time.time()
profiler.disable()
processing_time = end_time - start_time
print(f"Time taken to create license image: {processing_time:.4f} seconds")
stats = pstats.Stats(profiler).sort_stats('tottime')
stats.dump_stats(profile_file)
stats.print_stats(10)
print("Profile data dumped to 'profile_results.prof'")