ImgGenLite / app.py
Rooni's picture
Update app.py
3dcf040 verified
import gradio as gr
import requests
import random
import urllib.parse
import logging
from PIL import Image
from io import BytesIO
from deep_translator import GoogleTranslator
from langdetect import detect
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def generate_image(prompt, style, width, height, seed):
if seed == -1:
seed = random.randint(0, 999999)
# Добавляем теги для стилей
style_tags = {
"Свой": "",
"Аниме": "anime style, detailed, vibrant colors, cartoonish",
"Реализм": "realism style, hyperrealistic, photorealistic",
"3D": "3D style, rendering, high detail, volumetric lighting",
"Краски": "paintings style, impressionist, detailed brush strokes, oil painting",
"Пиксель-арт": "pixel art style, low resolution, retro, nostalgic",
"Машины с лицами": "machines with faces, mechanical humanoid, futuristic, detailed features",
"Космический": "space style, celestial bodies, galaxies, stars, nebulae",
"Монстры": "monster style, mythical creatures, detailed anatomy, fantasy",
"Супергерои": "superhero style, comic book, vibrant colors, dynamic poses",
"Детская книга": "children's book style, whimsical, colorful, simple shapes",
"Готический": "gothic style, dark, intricate details, brooding atmosphere",
"Ретро": "retro style, vintage, 8-bit, nostalgic",
"Стимпанк": "steampunk style, steam-powered machinery, brass and copper elements, Victorian era",
"Фэнтези": "fantasy style, magical creatures, enchanted forests, mythical landscapes",
"Народные мотивы": "folk art style, traditional patterns, cultural motifs, vibrant colors",
"Минимализм": "minimalist style, clean lines, simple shapes, neutral colors",
"Гаражный хардкор": "garage punk style, industrial, rugged, DIY, metal textures",
"Стример": "streamer style, gaming, charismatic, energetic, modern",
"Новый хоррор": "new horror style, dark atmosphere, suspenseful, twisted, modern",
"Детский мультфильм": "children's animation style, colorful, cartoonish, simple shapes",
"Арт-ноу": "art nouveau style, ornate, flowing lines, detailed patterns",
"Викторианский": "victorian style, intricate details, ornate architecture, vintage",
"Грейский тон": "grayscale style, monochrome, detailed textures, high contrast",
"Моцарт": "mozart style, classical music, baroque, elegant, detailed",
"Гамбит": "chess style, board game, strategy, detailed pieces, high contrast",
"Киберпанк": "cyberpunk style, futuristic, neon lights, high-tech, detailed environments",
"Грот": "cave style, underground, detailed textures, stone formations, natural",
"Цирк": "circus style, vibrant, acrobatic, colorful, dynamic",
"Арт-деко": "art deco style, geometric patterns, ornate, luxurious, 1920s",
"Стратегические игры": "strategy game style, hexagonal tiles, detailed maps, military units",
"Инди-игра": "indie game style, charming, minimalist, vibrant colors, simple graphics",
"Медиевский": "medieval style, knightly armor, castles, detailed textures, historical",
"Макет": "model kit style, detailed parts, assembly instructions, high precision",
"Футуристический": "futuristic style, sleek design, high-tech, minimalistic, modern",
"Пасха": "easter egg style, hidden details, playful, humorous, subtle",
"Микстап": "meme style, humorous, exaggerated, pop culture references, viral",
"Скульптура": "sculpture style, detailed modeling, textured surfaces, realistic materials",
"Дизайн интерьера": "interior design style, modern, functional, detailed textures, cozy",
"Спорт": "sports style, dynamic action, detailed athletes, high contrast, vibrant colors",
"Голливудский": "hollywood style, glamour, high contrast, detailed sets, cinematic",
"Тематический парк": "theme park style, vibrant, detailed rides, futuristic, entertaining",
"Космический полет": "space travel style, detailed spaceships, planets, starfields, high contrast",
"Лабиринт": "maze style, intricate pathways, detailed textures, puzzle-like, high contrast",
"Тропический лес": "tropical rainforest style, lush vegetation, detailed textures, vibrant colors",
"Экспериментальный": "experimental style, abstract, unconventional, detailed patterns, vibrant colors"
}
language = detect(prompt)
if language != 'en':
prompt = GoogleTranslator(source=language, target='en').translate(prompt)
prompt = style_tags.get(style, "") + ". " + prompt if style_tags.get(style, "") else prompt
prompt = prompt.strip()
# URL-кодирование промпта
encoded_prompt = urllib.parse.quote(prompt)
url = f"https://image.pollinations.ai/prompt/{encoded_prompt}?width={width}&height={height}&seed={seed}&nologo=true&nofeed=true"
logger.info(f"Generated URL: {url}")
try:
response = requests.get(url, timeout=150)
if response.status_code == 200:
logger.info("Image generated successfully")
# Преобразуем байты в изображение
image = Image.open(BytesIO(response.content))
return image
else:
logger.error(f"Failed to generate image. Status code: {response.status_code}, Response: {response.text}")
raise gr.Error("Извините, изображение создавалось слишком долго или произошла ошибка. Попробуйте снова.")
except requests.exceptions.Timeout:
logger.error("Request timed out")
raise gr.Error("Извините, изображение создавалось слишком долго, мы отменили генерацию.")
except requests.exceptions.RequestException as e:
logger.error(f"Request exception: {e}")
raise gr.Error("Произошла ошибка при генерации изображения. Попробуйте снова.")
# Ссылка на файл CSS
css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
# Получение CSS по ссылке
response = requests.get(css_url)
css = response.text + ".gradio-container{max-width: 700px !important} h1{text-align:center}"
# Создаем интерфейс Gradio
with gr.Blocks(css=css) as demo:
gr.Markdown("")
gr.Markdown("# Генератор Изображений (Lite)")
with gr.Tab("Основные настройки"):
prompt_input = gr.Textbox(label="Описание изображения", placeholder="Введите описание изображения на английском языке")
with gr.Accordion("Стиль", open=False):
style_radio = gr.Radio(label="Выбор стиля", choices=[
"Свой",
"Аниме",
"Реализм",
"3D",
"Краски",
"Пиксель-арт",
"Машины с лицами",
"Космический",
"Монстры",
"Супергерои",
"Детская книга",
"Готический",
"Ретро",
"Стимпанк",
"Фэнтези",
"Народные мотивы",
"Минимализм",
"Гаражный хардкор",
"Стример",
"Новый хоррор",
"Детский мультфильм",
"Арт-ноу",
"Викторианский",
"Грейский тон",
"Моцарт",
"Гамбит",
"Киберпанк",
"Грот",
"Цирк",
"Арт-деко",
"Стратегические игры",
"Инди-игра",
"Медиевский",
"Макет",
"Футуристический",
"Пасха",
"Микстап",
"Скульптура",
"Дизайн интерьера",
"Спорт",
"Голливудский",
"Тематический парк",
"Космический полет",
"Лабиринт",
"Тропический лес",
"Экспериментальный"
], value="Свой")
with gr.Tab("Дополнительные настройки"):
with gr.Row():
width_slider = gr.Slider(label="Ширина", minimum=80, maximum=4000, value=1024)
height_slider = gr.Slider(label="Высота", minimum=80, maximum=4000, value=1024)
with gr.Row():
seed_slider = gr.Slider(label="Сид", minimum=-1, maximum=999999, value=-1, step=1)
create_button = gr.Button("Создать")
output_image = gr.Image(label="Изображение", type="pil", show_share_button=False)
create_button.click(
fn=generate_image,
inputs=[prompt_input, style_radio, width_slider, height_slider, seed_slider],
outputs=[output_image],
queue=True,
concurrency_limit=250
)
demo.queue(max_size=250).launch(show_api=False, share=False)