Spaces:
Running
Running
File size: 10,117 Bytes
5699de1 c6a8b4d a2c470a 4f114d9 03b66c4 a2c470a 5699de1 687d54f 5699de1 687d54f 03b66c4 687d54f c0df552 687d54f c6a8b4d a2c470a 4f114d9 a2c470a 9557389 65a0191 9557389 a2c470a 9557389 5699de1 6a3a8c2 eb75e63 6a3a8c2 c589b78 65a0191 5699de1 687d54f 5699de1 addbb51 65a0191 addbb51 d3fbb8f 5699de1 24ec007 5699de1 65a0191 24ec007 65a0191 5699de1 65a0191 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
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")
create_button.click(
fn=generate_image,
inputs=[prompt_input, style_radio, width_slider, height_slider, seed_slider],
outputs=[output_image]
)
demo.queue(max_size=150).launch() |