Files
buryan-infra/ops/home/gen_ai_rooms.py
T

105 lines
4.6 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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Генерация изометрических рендеров комнат через Pollinations (бесплатно, без ключа).
Вход: ops/home/renders/input/<room>/spec.json
Выход: ops/home/renders/ai/<room>.jpg + веб-версии в renders/web/
"""
import io
import json
import os
import time
import urllib.parse
import urllib.request
OUT_AI = '/root/buryan-infra/ops/home/renders/ai'
OUT_WEB = '/root/buryan-infra/ops/home/renders/web'
IN_DIR = '/root/buryan-infra/ops/home/renders/input'
BASE = 'https://image.pollinations.ai/prompt/'
STYLE = ("isometric 2.5D cutaway room illustration, cozy modern interior, detailed furniture, "
"warm interior lighting, soft shadows, dark charcoal background, clean minimalist style, "
"high detail, no text, no people")
PROMPTS = {
'bedroom': ("cozy bedroom, double bed with wooden headboard and grey bedding, two wooden nightstands "
"with warm bedside lamps, tall wardrobe, writing desk with chair, wall-mounted TV, "
"ceiling track light with spotlights"),
'office': ("home office room, large wooden desk with two monitors, ergonomic chair, wall-mounted TV, "
"white game console, tall wardrobe, air conditioner on wall, ceiling track light"),
'danina': ("teenage bedroom with loft mezzanine, single bed, study desk, small sofa, wall-mounted TV, "
"wooden loft platform with metal ladder, wardrobe, ceiling track light on wooden beam"),
'kitchen-living': ("open plan kitchen living room, wooden kitchen cabinets with stone countertop, "
"fridge, extractor hood, dining table with chairs, grey sofa, large wall-mounted TV, "
"open shelving unit, pendant lights"),
'bathroom': ("small bathroom, white bathtub, glass shower, toilet, sink with mirror cabinet, "
"washing machine, LED strip lighting, white tiles"),
'corridor': ("narrow entry corridor, tall wardrobe, wooden bench, full height mirror, shoe cabinet, "
"ceiling track light, warm wall lamps"),
'laundry': ("small utility laundry room, washing machine, dryer, wooden shelving with storage boxes, "
"compact space"),
'hall-way': ("small entrance hallway, wooden console table, mirror, hooks with coats, ceiling light"),
}
SIZES = {'bedroom': (1024, 1024), 'office': (1024, 1024), 'danina': (1024, 1024),
'kitchen-living': (1024, 768), 'bathroom': (1024, 1024), 'corridor': (768, 1024),
'laundry': (1024, 1024), 'hall-way': (1024, 1024)}
def gen(key, attempt=1):
w, h = SIZES.get(key, (1024, 1024))
prompt = (PROMPTS.get(key, key) + ", " + STYLE)
q = urllib.parse.quote(prompt)
url = ('%s%s?width=%d&height=%d&nologo=true&seed=%d&model=flux'
% (BASE, q, w, h, int(time.time()) % 100000))
try:
with urllib.request.urlopen(url, timeout=180) as r:
data = r.read()
if len(data) < 5000:
return None, 'мало данных (%d б)' % len(data)
os.makedirs(OUT_AI, exist_ok=True)
path = os.path.join(OUT_AI, key + '.jpg')
open(path, 'wb').write(data)
return path, None
except Exception as e:
return None, str(e)[:120]
def main():
from PIL import Image
os.makedirs(OUT_AI, exist_ok=True)
os.makedirs(OUT_WEB, exist_ok=True)
keys = sorted(PROMPTS.keys())
results = []
for key in keys:
name = key
sp = os.path.join(IN_DIR, key, 'spec.json')
if os.path.exists(sp):
try:
name = json.load(open(sp, encoding='utf-8')).get('name', key)
except Exception:
pass
t0 = time.time()
path, err = gen(key)
dt = round(time.time() - t0)
if path:
im = Image.open(path).convert('RGB')
# обрезаем водяной знак справа снизу
im = im.crop((0, 0, im.width - 90, im.height - 26)) if im.width > 400 else im
im.save(path, 'JPEG', quality=88, optimize=True)
wid = 1200
hei = int(im.height * wid / im.width)
im.resize((wid, hei), Image.LANCZOS).save(
os.path.join(OUT_WEB, key + '.jpg'), 'JPEG', quality=84, optimize=True)
print(' %-16s %-22s %ss %d КБ' % (key, name, dt, os.path.getsize(path) // 1024))
results.append(key)
else:
print(' %-16s ОШИБКА: %s' % (key, err))
time.sleep(2)
print('\nсгенерировано: %d из %d' % (len(results), len(keys)))
if __name__ == '__main__':
main()