256 lines
14 KiB
Python
256 lines
14 KiB
Python
"""Server-only helpers for Polza image generation.
|
||
|
||
The module deliberately keeps provider URLs and secrets out of API payloads.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ipaddress
|
||
import json
|
||
import os
|
||
import socket
|
||
import tempfile
|
||
from datetime import datetime, timezone
|
||
from html import unescape
|
||
from io import BytesIO
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from urllib.parse import urlparse
|
||
from uuid import uuid4
|
||
|
||
import httpx
|
||
from PIL import Image
|
||
|
||
DEFAULT_API_URL = "https://polza.ai/api"
|
||
DEFAULT_MODEL = "google/gemini-3.1-flash-image"
|
||
MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
||
ALLOWED_IMAGE_TYPES = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||
|
||
|
||
class ImageGenerationError(RuntimeError):
|
||
def __init__(self, code: str, message: str, *, size_error: bool = False) -> None:
|
||
super().__init__(message)
|
||
self.code = code
|
||
self.message = message
|
||
self.size_error = size_error
|
||
|
||
|
||
def normalize_api_url(value: str) -> str:
|
||
parsed = urlparse(value.strip().rstrip("/"))
|
||
if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||
raise ValueError("API URL должен быть абсолютным HTTPS URL без параметров.")
|
||
if parsed.hostname in {"localhost", "localhost.localdomain"}:
|
||
raise ValueError("API URL не может указывать на локальную сеть.")
|
||
try:
|
||
host_ip = ipaddress.ip_address(parsed.hostname or "")
|
||
if host_ip.is_private or host_ip.is_loopback or host_ip.is_link_local or host_ip.is_reserved:
|
||
raise ValueError("API URL не может указывать на локальную сеть.")
|
||
except ValueError as exc:
|
||
if str(exc).startswith("API URL"):
|
||
raise
|
||
try:
|
||
for address in socket.getaddrinfo(parsed.hostname, None):
|
||
host_ip = ipaddress.ip_address(address[4][0])
|
||
if host_ip.is_private or host_ip.is_loopback or host_ip.is_link_local or host_ip.is_reserved:
|
||
raise ValueError("API URL не может указывать на локальную сеть.")
|
||
except socket.gaierror as exc:
|
||
raise ValueError("Не удалось разрешить API URL.") from exc
|
||
return parsed.geturl().rstrip("/")
|
||
|
||
|
||
def _text(value: Any) -> str:
|
||
return unescape(__import__("re").sub(r"<[^>]+>", " ", str(value or ""))).replace("\xa0", " ").strip()
|
||
|
||
|
||
def content_blocks(editor_data: dict[str, Any]) -> list[dict[str, Any]]:
|
||
blocks = editor_data.get("blocks") if isinstance(editor_data, dict) else None
|
||
if not isinstance(blocks, list):
|
||
raise ValueError("editorData должен содержать массив blocks.")
|
||
result = []
|
||
for block in blocks:
|
||
if not isinstance(block, dict):
|
||
continue
|
||
kind, data = str(block.get("type") or ""), block.get("data") or {}
|
||
if not isinstance(data, dict) or kind == "image":
|
||
continue
|
||
text = _text(data.get("text") or data.get("caption") or data.get("content"))
|
||
if text:
|
||
result.append({"id": str(block.get("id") or ""), "type": kind, "text": text})
|
||
return result
|
||
|
||
|
||
def section_context(editor_data: dict[str, Any], target: str, target_block_id: str | None = None) -> str:
|
||
blocks = content_blocks(editor_data)
|
||
if not blocks:
|
||
return "Смысловой контекст отсутствует; создай сдержанную нейтральную аналитическую композицию."
|
||
headings = [i for i, block in enumerate(blocks) if block["type"] in {"header", "heading"}]
|
||
if target_block_id:
|
||
raw_blocks = editor_data.get("blocks") or []
|
||
image_index = next((i for i, item in enumerate(raw_blocks) if isinstance(item, dict) and str(item.get("id") or "") == target_block_id), -1)
|
||
if image_index >= 0:
|
||
nearby: list[str] = []
|
||
for item in raw_blocks[max(0, image_index - 4): image_index + 5]:
|
||
if not isinstance(item, dict) or item.get("type") == "image":
|
||
continue
|
||
data = item.get("data") or {}
|
||
if isinstance(data, dict):
|
||
text = _text(data.get("text") or data.get("caption") or data.get("content"))
|
||
if text:
|
||
nearby.append(text)
|
||
if nearby:
|
||
return " ".join(nearby)[:5000]
|
||
return " ".join(block["text"] for block in blocks[-4:])[:5000]
|
||
if headings:
|
||
sections: list[list[dict[str, Any]]] = []
|
||
for index, start in enumerate(headings):
|
||
end = headings[index + 1] if index + 1 < len(headings) else len(blocks)
|
||
sections.append(blocks[start:end])
|
||
if target == "final":
|
||
selected = sections[-1]
|
||
else:
|
||
total_chars = max(1, sum(len(block["text"]) for block in blocks))
|
||
offset = sum(len(block["text"]) for block in blocks[:headings[0]])
|
||
positioned_sections: list[tuple[float, list[dict[str, Any]]]] = []
|
||
for section in sections:
|
||
section_chars = sum(len(block["text"]) for block in section)
|
||
positioned_sections.append(((offset + section_chars / 2) / total_chars, section))
|
||
offset += section_chars
|
||
selected = min(positioned_sections, key=lambda item: abs(item[0] - .5))[1]
|
||
return " ".join(block["text"] for block in selected)[:5000]
|
||
total = sum(len(item["text"]) for item in blocks)
|
||
threshold = total * (.75 if target == "final" else .34)
|
||
seen, selected = 0, []
|
||
for item in blocks:
|
||
seen += len(item["text"])
|
||
if seen >= threshold:
|
||
selected.append(item)
|
||
return " ".join(item["text"] for item in selected[:6])[:5000]
|
||
|
||
|
||
def build_prompt(target: str, title: str, editor_data: dict[str, Any], target_block_id: str | None = None) -> str:
|
||
context = section_context(editor_data, target, target_block_id)
|
||
limits = ("Не показывай реальные карты, координаты, маршруты, военные схемы, оружие, активные БПЛА, ракеты, "
|
||
"взрывы, пожары, кровь, тела, разрушения, узнаваемых людей, флаги, гербы, эмблемы или логотипы. "
|
||
"Не выдавай спорные утверждения за доказанный факт.")
|
||
if target == "cover":
|
||
return f"""Создай фотореалистичную премиальную обложку серьёзного международного военно-политического аналитического издания, 16:9, кинематографичный свет, высокая детализация, спокойная центральная safe area.
|
||
ЕДИНСТВЕННЫЙ ТЕКСТ НА ИЗОБРАЖЕНИИ, строго без изменений:
|
||
<<<{title.strip()}>>>
|
||
Используй Bebas Neue, сохрани кириллицу, Ё, регистр и пунктуацию; холодно-серебристые металлические 3D-буквы, тёмно-графитовая обводка, тень и блики. Не добавляй иных надписей, логотипов или водяных знаков.
|
||
Сюжет создай по смыслу статьи: предметная, архитектурная, аналитическая композиция, без людей.
|
||
КОНТЕКСТ: {context}
|
||
{limits}"""
|
||
role = "факты, расследование, предметы, пространство и смысловой конфликт второй части" if target == "middle" else "вывод, последствия, ответственность, неопределённость или развязку заключительной части"
|
||
return f"""Создай фотореалистичную кинематографичную редакционную иллюстрацию 16:9 для военно-политической аналитической статьи. Визуализируй {role}. Полностью без текста, букв, цифр, читаемых документов, логотипов и водяных знаков. Сдержанная, серьёзная, неоднозначная предметная композиция.
|
||
КОНТЕКСТ: {context}
|
||
{limits}"""
|
||
|
||
|
||
def _safe_public_url(url: str) -> None:
|
||
parsed = urlparse(url)
|
||
if parsed.scheme != "https" or not parsed.hostname:
|
||
raise ImageGenerationError("download_failed", "Провайдер вернул недопустимую ссылку на изображение.")
|
||
try:
|
||
addresses = socket.getaddrinfo(parsed.hostname, None)
|
||
for address in addresses:
|
||
ip = ipaddress.ip_address(address[4][0])
|
||
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
|
||
raise ImageGenerationError("download_failed", "Ссылка на изображение недоступна.")
|
||
except socket.gaierror as exc:
|
||
raise ImageGenerationError("download_failed", "Не удалось разрешить адрес изображения.") from exc
|
||
|
||
|
||
def error_from_response(response: httpx.Response) -> ImageGenerationError:
|
||
body = response.text[:1000].lower()
|
||
if response.status_code in {401, 403}:
|
||
return ImageGenerationError("token_invalid", "Токен Polza отклонён.")
|
||
if response.status_code == 429:
|
||
return ImageGenerationError("rate_limited", "Превышен лимит запросов Polza.")
|
||
if "balance" in body or "insufficient" in body:
|
||
return ImageGenerationError("insufficient_balance", "Недостаточно средств в Polza.")
|
||
if "moderation" in body or "safety" in body:
|
||
return ImageGenerationError("moderation_rejected", "Запрос отклонён политикой провайдера.")
|
||
if "model" in body and ("not found" in body or "unavailable" in body):
|
||
return ImageGenerationError("model_unavailable", "Выбранная модель недоступна.")
|
||
size_error = any(value in body for value in ("resolution", "size", "quality", "4k", "image_resolution"))
|
||
return ImageGenerationError("provider_error", "Polza не смогла создать изображение.", size_error=size_error)
|
||
|
||
|
||
class PolzaClient:
|
||
def __init__(self, api_url: str, token: str) -> None:
|
||
self.api_url, self.token = normalize_api_url(api_url), token
|
||
|
||
@property
|
||
def media_url(self) -> str:
|
||
return self.api_url + "/v1/media"
|
||
|
||
async def create(self, model: str, prompt: str, resolution: str = "4K") -> str:
|
||
input_payload: dict[str, Any] = {
|
||
"prompt": prompt,
|
||
"output_format": "png",
|
||
"max_images": 1,
|
||
}
|
||
if resolution == "4K":
|
||
input_payload.update({"aspect_ratio": "16:9", "image_resolution": "4K", "quality": "high"})
|
||
else:
|
||
input_payload["aspect_ratio"] = "1792x1024"
|
||
try:
|
||
async with httpx.AsyncClient(timeout=60) as client:
|
||
response = await client.post(self.media_url, headers={"Authorization": f"Bearer {self.token}"}, json={"model": model, "input": input_payload, "async": True})
|
||
except httpx.TimeoutException as exc:
|
||
raise ImageGenerationError("provider_timeout", "Истёк тайм-аут Polza.") from exc
|
||
if response.is_error:
|
||
raise error_from_response(response)
|
||
data = response.json()
|
||
generation_id = data.get("id") or data.get("generation_id") or (data.get("data") or {}).get("id")
|
||
if not generation_id:
|
||
raise ImageGenerationError("provider_error", "Polza вернула неполный ответ.")
|
||
return str(generation_id)
|
||
|
||
async def status(self, generation_id: str) -> dict[str, Any]:
|
||
async with httpx.AsyncClient(timeout=30) as client:
|
||
response = await client.get(f"{self.media_url}/{generation_id}", headers={"Authorization": f"Bearer {self.token}"})
|
||
if response.is_error:
|
||
raise error_from_response(response)
|
||
return response.json()
|
||
|
||
|
||
def extract_result_url(data: dict[str, Any]) -> str | None:
|
||
candidates: list[Any] = [data.get("url"), data.get("output"), data.get("result"), data.get("data")]
|
||
while candidates:
|
||
value = candidates.pop(0)
|
||
if isinstance(value, str) and value.startswith("http"):
|
||
return value
|
||
if isinstance(value, dict):
|
||
candidates.extend(value.get(k) for k in ("url", "output", "result", "data", "images") if k in value)
|
||
if isinstance(value, list):
|
||
candidates.extend(value)
|
||
return None
|
||
|
||
|
||
def save_remote_image(url: str, target_dir: Path, public_base_url: str, article_id: int, target: str) -> str:
|
||
_safe_public_url(url)
|
||
response = httpx.get(url, timeout=45, follow_redirects=False)
|
||
if response.is_error or response.headers.get("content-type", "").split(";", 1)[0].lower() not in ALLOWED_IMAGE_TYPES:
|
||
raise ImageGenerationError("invalid_image", "Polza вернула недопустимый файл изображения.")
|
||
content = response.content
|
||
if not content or len(content) > MAX_IMAGE_BYTES:
|
||
raise ImageGenerationError("invalid_image", "Размер изображения недопустим.")
|
||
try:
|
||
Image.open(BytesIO(content)).verify()
|
||
except Exception as exc:
|
||
raise ImageGenerationError("invalid_image", "Файл изображения повреждён.") from exc
|
||
date_key = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||
date_dir = target_dir / "generated" / date_key / str(article_id)
|
||
date_dir.mkdir(parents=True, exist_ok=True)
|
||
suffix = ALLOWED_IMAGE_TYPES[response.headers["content-type"].split(";", 1)[0].lower()]
|
||
name = f"{target}-{uuid4().hex}{suffix}"
|
||
fd, temporary = tempfile.mkstemp(prefix=".upload-", dir=date_dir)
|
||
try:
|
||
with os.fdopen(fd, "wb") as output:
|
||
output.write(content)
|
||
os.replace(temporary, date_dir / name)
|
||
os.chmod(date_dir / name, 0o644)
|
||
finally:
|
||
if os.path.exists(temporary):
|
||
os.unlink(temporary)
|
||
return f"{public_base_url.rstrip('/')}/media/generated/{date_key}/{article_id}/{name}"
|