Files
LihonT/services/members/report.py
cheb0chik 5df4cddf7d LihonT 3 Luna pre-alpha: the streak pet becomes an animal
A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the
streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown
on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by
scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of
make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift.

Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 15:14:48 +03:00

223 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The detailed rejection report: what the AI saw, where, and how to appeal, as a one-page PDF.
An upload that the AI rejects gets a short reason at once. On request the author can get this report: the picture with the parts that
triggered the rejection marked by red squares, the model and the time of the check, the contact and the appeal terms. The squares come
from the same vision model (it answers with boxes in 0..1000 of the picture width and height); a box that makes no sense is dropped,
and a verdict without any box still gives a report, just without squares.
The page is drawn with Pillow only (no other PDF library), in A4 at 150 dpi.
"""
from __future__ import annotations
import io
import json
import re
import textwrap
from datetime import datetime, timedelta, timezone
try:
from . import moderation
except ImportError: # run as a plain script next to moderation.py
import moderation
from PIL import Image, ImageDraw, ImageFont
CONTACT = "t.me/cheb0chik"
APPEAL = ("Просим не требовать мгновенной публикации ресурса при обжаловании: "
"жалоба будет рассмотрена в течение 1 рабочего дня.")
NOTE = "Решение ИИ предварительное. Окончательное решение по спорной работе принимает человек."
MAX_REGIONS = 6
DETAIL_ANSWER = (
"Reply with one JSON object and nothing else: "
'{"verdict": "pass" or "review" or "reject", "reason": "up to 12 words, English", "reason_ru": "до 12 слов по-русски", '
'"regions": [{"label": "short English label", "label_ru": "коротко по-русски", "box": [x1, y1, x2, y2]}]}. '
"List EVERY separate problem you see, one region each, not only the first one. "
"Each box is in the range 0..1000, relative to the picture width and height (x1,y1 top left; x2,y2 bottom right), TIGHT around "
"that one element (for example the exposed legs, a logo, a face), never around the whole picture or an empty area; name the "
"exact element in the label. Use an empty list when the verdict is pass."
)
FONT_REGULAR = ("DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "segoeui.ttf", "arial.ttf")
FONT_BOLD = ("DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "segoeuib.ttf", "arialbd.ttf")
def _font(names, size):
for name in names:
try:
return ImageFont.truetype(name, size)
except OSError:
continue
raise RuntimeError("no font with Cyrillic found")
def detail_check(png: bytes, post=moderation.chain_post) -> dict:
"""The AI verdict with regions: {"ok", "reason", "reason_ru", "regions": [{"label", "label_ru", "box": [x1,y1,x2,y2] in 0..1}], "model"}.
ok is None when the check could not be made."""
import base64
url = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
body = {
"model": moderation.IMAGE_MODEL, "temperature": 0, "max_tokens": 600,
"messages": [
{"role": "system", "content": moderation.POLICY + " " + DETAIL_ANSWER},
{"role": "user", "content": [{"type": "text", "text": "Screen this picture."},
{"type": "image_url", "image_url": {"url": url}}]},
],
}
result = {"ok": None, "review": False, "reason": "", "reason_ru": "", "regions": [], "model": moderation.IMAGE_MODEL}
if post is moderation.chain_post and not moderation.providers("image"):
result["reason"] = "no key"
return result
try:
reply = post(body)
text = reply["choices"][0]["message"]["content"] or ""
if reply.get("_model"):
result["model"] = "%s (%s)" % (reply["_model"], reply.get("_provider", ""))
except Exception as error: # network, quota, bad gateway
result["reason"] = type(error).__name__
return result
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S).strip()
match = re.search(r"\{.*\}", text, flags=re.S)
try:
data = json.loads(match.group(0)) if match else None
except ValueError:
data = None
word = data.get("verdict") if isinstance(data, dict) else None
if word not in ("pass", "review", "reject"):
result["reason"] = "not json"
return result
result["ok"] = word != "reject"
result["review"] = word == "review"
result["reason"] = str(data.get("reason") or "")[:moderation.REASON_MAX]
result["reason_ru"] = str(data.get("reason_ru") or "")[:moderation.REASON_MAX]
width, height = Image.open(io.BytesIO(png)).size
longest = max(width, height)
for region in (data.get("regions") or [])[:MAX_REGIONS]:
box = region.get("box") if isinstance(region, dict) else None
if not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) for v in box)):
continue
# the model measures both axes against the LONGER side of the picture (it sees it padded to a square), so a wide picture
# has its boxes squeezed into the top part: scale back by the longer side, then to fractions of each side
x1, y1, x2, y2 = (min(1.0, max(0.0, box[0] / 1000.0 * longest / width)), min(1.0, max(0.0, box[1] / 1000.0 * longest / height)),
min(1.0, max(0.0, box[2] / 1000.0 * longest / width)), min(1.0, max(0.0, box[3] / 1000.0 * longest / height)))
if x2 - x1 < 0.02 or y2 - y1 < 0.02: # a box with no area is no box
continue
result["regions"].append({"label": str(region.get("label") or "")[:60], "label_ru": str(region.get("label_ru") or "")[:60],
"box": [x1, y1, x2, y2]})
return result
def _wrap(draw, text, font, width):
"""Lines of text that fit the width in pixels."""
lines = []
for paragraph in text.split("\n"):
words, line = paragraph.split(" "), ""
for word in words:
trial = (line + " " + word).strip()
if draw.textlength(trial, font=font) <= width or not line:
line = trial
else:
lines.append(line)
line = word
lines.append(line)
return lines
def _marked_picture(png: bytes, regions: list, width: int) -> Image.Image:
picture = Image.open(io.BytesIO(png)).convert("RGBA")
ground = Image.new("RGBA", picture.size, (236, 236, 240, 255))
ground.alpha_composite(picture)
height = max(1, int(ground.height * width / ground.width))
shown = ground.convert("RGB").resize((width, height), Image.Resampling.LANCZOS)
draw = ImageDraw.Draw(shown)
tag = _font(FONT_BOLD, 26)
for number, region in enumerate(regions, 1):
x1, y1, x2, y2 = (region["box"][0] * width, region["box"][1] * height, region["box"][2] * width, region["box"][3] * height)
draw.rectangle([x1, y1, x2, y2], outline=(214, 40, 57), width=5)
side = 38
top = y1 - side if y1 - side >= 0 else y1
draw.rectangle([x1, top, x1 + side, top + side], fill=(214, 40, 57))
draw.text((x1 + side / 2, top + side / 2), str(number), font=tag, fill=(255, 255, 255), anchor="mm")
return shown
def render_page(png: bytes, detail: dict, *, name: str, kind: str, art_id: str, when: datetime | None = None) -> Image.Image:
"""The one-page report as a picture."""
when = when or datetime.now(timezone.utc)
moscow = when.astimezone(timezone(timedelta(hours=3)))
w, h, margin = 1240, 1754, 90
page = Image.new("RGB", (w, h), (255, 255, 255))
draw = ImageDraw.Draw(page)
ink, grey, red, violet = (24, 24, 28), (110, 110, 120), (214, 40, 57), (92, 56, 168)
draw.rectangle([0, 0, w, 150], fill=violet)
draw.text((margin, 75), "LihonT · подробный отчёт об отклонении", font=_font(FONT_BOLD, 44), fill=(255, 255, 255), anchor="lm")
y = 200
rows = [("Ресурс", "%s «%s»" % ("рамка" if kind == "frame" else "пузырь чата" if kind == "bubble" else kind, name)),
("Номер", art_id[:12]),
("Время проверки", moscow.strftime("%d.%m.%Y %H:%M") + " МСК"),
("Модель ИИ", detail.get("model", "")),
("Решение", "отклонено" if detail.get("ok") is False else "спорное, смотрит человек" if detail.get("review")
else "принято" if detail.get("ok") else "не проверено")]
label_font, value_font = _font(FONT_REGULAR, 30), _font(FONT_BOLD, 30)
for label, value in rows:
draw.text((margin, y), label, font=label_font, fill=grey)
draw.text((margin + 330, y), value, font=value_font, fill=ink)
y += 52
y += 20
reason = detail.get("reason_ru") or detail.get("reason") or "—"
draw.text((margin, y), "Причина", font=label_font, fill=grey)
y += 46
body = _font(FONT_BOLD, 34)
for line in _wrap(draw, reason, body, w - 2 * margin):
draw.text((margin, y), line, font=body, fill=red if detail.get("ok") is False else ink)
y += 46
if detail.get("reason") and detail.get("reason_ru"): # the AI's own words as well
small = _font(FONT_REGULAR, 26)
for line in _wrap(draw, "Оригинальный ответ ИИ: " + detail["reason"], small, w - 2 * margin):
draw.text((margin, y), line, font=small, fill=grey)
y += 36
y += 24
marked = _marked_picture(png, detail.get("regions", []), min(w - 2 * margin, 900))
page.paste(marked, (margin, y))
draw.rectangle([margin - 1, y - 1, margin + marked.width, y + marked.height], outline=(200, 200, 208), width=2)
y += marked.height + 30
regions = detail.get("regions", [])
item = _font(FONT_REGULAR, 28)
if regions:
draw.text((margin, y), "Что сработало (красные квадраты):", font=label_font, fill=grey)
y += 46
for number, region in enumerate(regions, 1):
text = "%d. %s" % (number, region.get("label_ru") or region.get("label") or "область")
if region.get("label") and region.get("label_ru"):
text += " (%s)" % region["label"]
for line in _wrap(draw, text, item, w - 2 * margin):
draw.text((margin, y), line, font=item, fill=ink)
y += 40
elif detail.get("ok") is False:
draw.text((margin, y), "ИИ не указал отдельное место: вердикт относится ко всей картинке.", font=item, fill=grey)
y += 44
y = max(y + 40, h - 470)
draw.line([(margin, y), (w - margin, y)], fill=(220, 220, 226), width=3)
y += 30
draw.text((margin, y), "Если вы не согласны", font=_font(FONT_BOLD, 34), fill=ink)
y += 56
draw.text((margin, y), "Контакт: " + CONTACT, font=_font(FONT_BOLD, 32), fill=violet)
y += 56
for line in _wrap(draw, APPEAL, item, w - 2 * margin):
draw.text((margin, y), line, font=item, fill=ink)
y += 40
y += 16
small = _font(FONT_REGULAR, 25)
for line in _wrap(draw, NOTE, small, w - 2 * margin):
draw.text((margin, y), line, font=small, fill=grey)
y += 34
return page
def build_pdf(png: bytes, detail: dict, **info) -> bytes:
"""The one-page report as PDF bytes."""
out = io.BytesIO()
render_page(png, detail, **info).save(out, "PDF", resolution=150.0, title="LihonT: отчёт об отклонении", author="LihonT")
return out.getvalue()