File size: 5,470 Bytes
0478aa2
 
 
 
 
 
 
 
 
0a14a93
 
0478aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b75f00d
 
0478aa2
 
b75f00d
0478aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1eaed
0478aa2
 
 
fc4ed9a
0478aa2
 
 
 
 
 
3be57f1
0478aa2
703ae82
 
 
 
 
 
 
 
 
0478aa2
 
 
 
d0dfd30
 
0478aa2
 
 
 
 
b7ffe7f
0478aa2
 
 
 
 
b7ffe7f
0478aa2
 
b7ffe7f
0478aa2
 
 
 
 
 
 
 
d0dfd30
fc4ed9a
0478aa2
 
 
 
 
 
 
 
b75f00d
0478aa2
 
 
 
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
import os
import random
import sys
import requests
from typing import Sequence, Mapping, Any, Union
import gradio as gr
from deep_translator import GoogleTranslator
from langdetect import detect
from gradio_client import Client, handle_file
from PIL import Image


# Функция для получения случайного API ключа
def get_random_api_key():
    keys = os.getenv("KEYS", "").split(",")
    if keys and keys[0]:  # Проверяем, установлены ли ключи и не пусты ли они
        return random.choice(keys).strip()
    else:
        raise ValueError("API ключи не найдены. Пожалуйста, установите переменную окружения KEYS.")

# Ссылка на файл CSS
css_url = "https://neurixyufi-aihub.static.hf.space/style.css"

# Получение CSS по ссылке
try:
    response = requests.get(css_url)
    response.raise_for_status()
    css = response.text + " h1{text-align:center}"
except requests.exceptions.RequestException as e:
    print(f"Ошибка при загрузке CSS: {e}")
    css = " h1{text-align:center}"

# Функция для перевода текста на английский
def translate_to_english(prompt):
    language = detect(prompt)
    if language != 'en':
        prompt = GoogleTranslator(source=language, target='en').translate(prompt)
    return prompt

# Функция для загрузки изображений в кеш и отправки ссылки на API
def upload_image_to_hf_cache(image):
    if isinstance(image, dict) and 'url' in image:
        return image['url']
    elif isinstance(image, str):
        return image
    else:
        raise ValueError("Неподдерживаемый формат изображения")

# Функция для генерации изображения через API
def generate_image(prompt, structure_image, style_image, depth_strength=15, style_strength=0.5, progress=gr.Progress(track_tqdm=True)) -> str:
    """Основная функция генерации изображения."""
    prompt = translate_to_english(prompt) if prompt else ""
    structure_image_url = upload_image_to_hf_cache(structure_image)
    style_image_url = upload_image_to_hf_cache(style_image)
    
    client = Client("multimodalart/flux-style-shaping", hf_token=get_random_api_key())
    result = client.predict(
        prompt=prompt,
        structure_image=handle_file(structure_image_url),
        style_image=handle_file(style_image_url),
        depth_strength=depth_strength,
        style_strength=style_strength,
        api_name="/generate_image"
    )

    if isinstance(result, str) and os.path.exists(result):
        output_image = Image.open(result)
    elif isinstance(result, bytes):
        output_image = Image.open(BytesIO(result))
    else:
        raise ValueError(f"Неожиданный тип результата API: {type(result)}")

    return output_image

# Примеры для Gradio
examples = [
    ["", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/mona.png", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/receita-tacos.webp", 15, 0.6],
    ["Девочка смотрит на дом, который горит", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/disaster_girl.png", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/abaporu.jpg", 15, 0.15],
    ["Город Истанбул с высоты птичьего полёта", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/natasha.png", "https://huggingface.co/spaces/multimodalart/flux-style-shaping/resolve/main/istambul.jpg", 15, 0.5],
]

output_image = gr.Image(label="Сгенерированное изображение", show_share_button=False)

with gr.Blocks(css=css) as app:
    gr.Markdown("# Структуратор")
    with gr.Row():
        with gr.Column():
            prompt_input = gr.Textbox(label="Запрос", placeholder="Введите ваш запрос здесь...")
            with gr.Row():
                with gr.Group():
                    structure_image = gr.Image(label="Изображение структуры", type="filepath")
                    depth_strength = gr.Slider(minimum=0, maximum=50, value=15, label="Сила глубины")
                with gr.Group():
                    style_image = gr.Image(label="Изображение стиля", type="filepath")
                    style_strength = gr.Slider(minimum=0, maximum=1, value=0.5, label="Сила стиля")
            generate_btn = gr.Button("Создать", variant='primary')
            
            gr.Examples(
                examples=examples,
                inputs=[prompt_input, structure_image, style_image, depth_strength, style_strength],
                outputs=[output_image],
                fn=generate_image,
                label="Примеры",
                cache_examples=False,
            )
        
        with gr.Column():
            output_image.render()
    generate_btn.click(
        fn=generate_image,
        inputs=[prompt_input, structure_image, style_image, depth_strength, style_strength],
        outputs=[output_image],
        concurrency_limit=250
    )

if __name__ == "__main__":
    app.launch(show_api=False, share=False)