Spaces:
Running
Running
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) | |