File size: 8,370 Bytes
947c4e2
dcf0c01
 
 
 
 
b819721
 
e1503fb
 
dcf0c01
 
 
 
 
 
 
d040dbe
 
 
 
dcf0c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2906d95
d040dbe
 
 
11dceec
74758ee
dcf0c01
d040dbe
dcf0c01
 
 
 
 
 
 
 
b819721
 
 
d040dbe
b819721
 
 
 
d040dbe
dcf0c01
 
 
 
 
 
 
8e01f8a
 
dcf0c01
2906d95
 
8e01f8a
 
 
 
 
d040dbe
 
 
 
 
 
 
 
 
2906d95
 
 
8e01f8a
 
 
 
 
d040dbe
 
 
 
 
 
 
 
 
 
 
 
8e01f8a
d0696ca
 
 
 
d040dbe
74758ee
d040dbe
11dceec
d040dbe
 
 
 
 
 
 
 
 
 
 
dcf0c01
 
 
b2dc0dc
d040dbe
 
61c73fd
 
d040dbe
61c73fd
 
 
dcf0c01
 
 
87db54d
d040dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e426c7
d040dbe
 
 
 
 
 
286bd3b
d040dbe
 
 
 
 
 
 
 
 
2e426c7
d040dbe
 
 
 
 
 
 
 
 
dcf0c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d040dbe
 
 
 
dcf0c01
 
 
 
 
 
 
 
 
 
d040dbe
 
 
11dceec
 
74758ee
dcf0c01
 
 
 
d040dbe
dcf0c01
b2dc0dc
d040dbe
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import gradio as gr
import os
import random
from gradio_client import Client, handle_file
from PIL import Image
import tempfile
import requests
from io import BytesIO
from deep_translator import GoogleTranslator
from langdetect import detect

# Constants
MAX_SEED = 2**32 - 1
MAX_IMAGE_SIZE = 1024

def get_random_api_key():
    keys = os.getenv("KEYS", "").split(",")
    if keys and keys[0]:  # Check if KEYS is set and not empty
        return random.choice(keys).strip()
    else:
        raise ValueError("API keys not found. Please set the KEYS environment variable.")

def resize_img(image, max_size=1024):
    width, height = image.size
    scaling_factor = min(max_size / width, max_size / height)
    new_width = int(width * scaling_factor)
    new_height = int(height * scaling_factor)
    return image.resize((new_width, new_height), Image.LANCZOS)

def process_image(
    image,
    prompt,
    scale,
    seed,
    randomize_seed,
    width,
    height,
    model_choice,
    negative_prompt="", # Add negative_prompt parameter
    guidance_scale=5,    # Add guidance_scale parameter
    num_inference_steps=25, # Add num_inference_steps parameter
    scale_kolors=0.5,
    prompt_kolors="",
):

    api_key = get_random_api_key()

    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    if image is None:
        return None, seed

    if isinstance(image, str) and image.startswith("http"):
        try:
            response = requests.get(image, stream=True)
            response.raise_for_status()
            image = Image.open(BytesIO(response.content))
        except requests.exceptions.RequestException as e:
            print(f"Error downloading image from URL: {e}")
            return "Ошибка загрузки изображения", seed
    elif not isinstance(image, Image.Image):
        image = Image.fromarray(image)

    resized_image = resize_img(image)

    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
        resized_image.save(temp_file.name)
        image_path = temp_file.name
    
        
    try:
        if model_choice == "Stable Diffusion":
            client = Client("InstantX/SD35-IP-Adapter", hf_token=api_key)
            
            language = detect(prompt)
            if language != 'en':
               prompt = GoogleTranslator(source=language, target='en').translate(prompt)
                
            result = client.predict(
                image=handle_file(image_path),
                prompt=prompt,
                scale=scale,
                seed=seed,
                width=width,
                height=height,
                api_name="/process_image"
            )

        elif model_choice == "Flux":
            client = Client("InstantX/flux-IP-adapter", hf_token=api_key)
            
            language = detect(prompt)
            if language != 'en':
               prompt = GoogleTranslator(source=language, target='en').translate(prompt)
                
            result = client.predict(
                 image=handle_file(image_path),
                prompt=prompt,
                scale=scale,
                seed=seed,
                width=width,
                height=height,
                api_name="/process_image"
            )

        elif model_choice == "Kolors":
            client = Client("multimodalart/Kolors-IPAdapter", hf_token=api_key)
            
            language = detect(prompt_kolors)
            if language != 'en':
                prompt_kolors = GoogleTranslator(source=language, target='en').translate(prompt_kolors)
            
            result = client.predict(
                prompt=prompt_kolors,
                ip_adapter_image=handle_file(image_path),
                ip_adapter_scale=scale_kolors,
                negative_prompt=negative_prompt,
                seed=seed,
                width=width,
                height=height,
                guidance_scale=guidance_scale,
                num_inference_steps=num_inference_steps,
                api_name="/infer"
            )

        generated_image = result[0]

    finally:
        os.remove(image_path)


    return gr.update(value=generated_image), result[1]

# Ссылка на файл 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} #col-container { margin: 0 auto; max-width: 960px; }"

with gr.Blocks(css=css) as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown("# Ии Редактор")

        input_image = gr.Image(label="Входное изображение", type="pil")
        result = gr.Image(label="Результат", show_share_button=False)


        with gr.Tabs():
            with gr.TabItem("Stable Diffusion & Flux"):
                with gr.Row():
                    with gr.Column():
                        prompt = gr.Text(
                            label="Описание изображения",
                            max_lines=1,
                            placeholder="Введите ваш запрос (Например: Сделай в аниме стиле)",
                        )
                        model_choice_sf = gr.Radio(choices=["Stable Diffusion", "Flux"], value="Stable Diffusion", label="Модель")
                        scale = gr.Slider(
                            label="Схожесть с оригиналом",
                            minimum=0.0,
                            maximum=1.0,
                            step=0.1,
                            value=0.7,
                        )
                    
            with gr.TabItem("Kolors (Баг)"):
                 with gr.Row():
                    with gr.Column():
                        prompt_kolors = gr.Text(
                           label="Описание изображения",
                           max_lines=1,
                           placeholder="Введите ваш запрос (Например: Сделай в аниме стиле)",
                        )
                        negative_prompt = gr.Text(label="Негативное описание", max_lines=1)
                        scale_kolors = gr.Slider(
                            label="Схожесть с оригиналом",
                            minimum=0.0,
                            maximum=1.0,
                            step=0.1,
                            value=0.5,
                         )
                        guidance_scale = gr.Slider(label="Guidance Scale", minimum=0, maximum=20, value=7, step=0.5)
                        num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=50, value=25, step=1)


        with gr.Accordion("Дополнительные настройки", open=False):
            seed = gr.Slider(
                label="Сид",
                minimum=0,
                maximum=MAX_SEED,
                step=1,
                value=42,
            )
            randomize_seed = gr.Checkbox(label="Случайный сид", value=True)
            with gr.Row():
                width = gr.Slider(
                    label="Ширина",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=1024,
                )
                height = gr.Slider(
                    label="Высота",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=1024,
                 )
        run_button = gr.Button("Изменить", variant="primary")


    run_button.click(
        fn=process_image,
        inputs=[
            input_image,
            prompt,
            scale,
            seed,
            randomize_seed,
            width,
            height,
            model_choice_sf, # Use model_choice_sf here
            negative_prompt,
            guidance_scale,
            num_inference_steps,
            scale_kolors,
            prompt_kolors,
        ],
        outputs=[result, seed],
    )


if __name__ == "__main__":
    demo.queue(max_size=250).launch(show_api=False, share=False)