Spaces:
Running
Running
File size: 4,802 Bytes
3547bc5 9b43207 8fe992b 9b43207 3547bc5 9b43207 3547bc5 9b43207 3547bc5 9b43207 3547bc5 85e0899 3547bc5 9b43207 8e9c77f f92aa04 99f3562 f92aa04 99f3562 f92aa04 3f9f678 9b43207 8ed4af9 9b43207 9b5b26a 9b43207 9b5b26a 3547bc5 9b5b26a 9b43207 9b5b26a 9b43207 3547bc5 9b43207 9b5b26a 8c01ffb 3547bc5 8c01ffb 9b43207 3547bc5 9b43207 3547bc5 ae7a494 9b43207 3547bc5 9b43207 3547bc5 ae7a494 9b43207 3547bc5 8c01ffb 9b43207 3547bc5 9b43207 8c01ffb 9b43207 8c01ffb 9b43207 3547bc5 9b43207 | 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 | import os
import tempfile
import gradio as gr
import torch
from PIL import Image
from huggingface_hub import InferenceClient
from ben2 import AutoModel
from smolagents import (
CodeAgent,
FinalAnswerTool,
InferenceClientModel,
tool,
)
HF_TOKEN = os.getenv("HF_TOKEN")
if HF_TOKEN is None:
raise ValueError("Add HF_TOKEN to Secrets Hugging Face Space.")
device = "cuda" if torch.cuda.is_available() else "cpu"
client = InferenceClient(
provider="hf-inference",
api_key=HF_TOKEN,
)
print("Loading BEN2...")
ben_model = (
AutoModel
.from_pretrained("PramaLLC/BEN2")
.to(device)
)
ben_model.eval()
print("BEN2 loaded.")
model = InferenceClientModel(
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
temperature=0.5,
max_tokens=2048,
)
@tool
def text_to_image(prompt: str) -> str:
"""Generate a new image.
Use this tool EVERY TIME the user asks to:
- generate an image
- create an image
- draw
- render
- make a picture
- imagine a scene
- create art
Never answer with a text description instead of calling this tool.
Do not use this tool for editing existing images.
Args:
prompt: Detailed description of the image.
Returns:
Path to the generated image.
"""
print("========== TOOL CALLED ==========")
image = client.text_to_image(
prompt,
model="stabilityai/sdxl-turbo",
)
output_path = tempfile.mktemp(suffix=".png")
image.save(output_path)
return output_path
@tool
def change_background_tool(image_path: str) -> str:
"""
Removes background and places image
on white background.
Args:
image_path: Path to image.
Returns:
Path to processed image.
"""
image = Image.open(image_path).convert("RGB")
result = ben_model.inference(
image,
refine_foreground=True,
)
white = Image.new(
"RGBA",
result.size,
(255, 255, 255, 255),
)
final = Image.alpha_composite(
white,
result,
).convert("RGB")
output_path = tempfile.mktemp(suffix=".png")
final.save(output_path)
return output_path
agent = CodeAgent(
tools=[
text_to_image,
change_background_tool,
],
model=model,
stream_outputs=False,
)
def run_agent(prompt, image):
try:
# Если пользователь загрузил изображение
if image is not None:
if prompt.strip() == "":
prompt = "Сделай белый фон"
full_prompt = f"""
Пользователь написал:
{prompt}
Изображение находится по пути:
{image}
Если требуется обработать изображение,
обязательно используй инструмент
change_background_tool.
Не пытайся описывать изображение.
Не придумывай ответ самостоятельно.
"""
# Если изображения нет
else:
full_prompt = f"""
Пользователь написал:
{prompt}
Если пользователь просит создать изображение,
используй инструмент text_to_image.
"""
result = agent.run(full_prompt)
# Агент вернул путь к изображению
if isinstance(result, str):
if os.path.exists(result):
return result, "Готово"
return None, str(result)
except Exception as e:
return None, str(e)
########################################################
# Интерфейс
########################################################
demo = gr.Interface(
fn=run_agent,
inputs=[
gr.Textbox(
label="Запрос",
lines=3,
placeholder="Например: сгенерируй красный Ferrari"
),
gr.Image(
type="filepath",
label="Изображение (необязательно)"
),
],
outputs=[
gr.Image(label="Результат"),
gr.Textbox(label="Ответ агента"),
],
title="🤖 AI Image Agent",
description="""
Загрузите изображение или введите текстовый запрос.
• если изображение загружено —
агент обработает его через BEN2
• если изображения нет —
агент сгенерирует новое изображение.
""",
allow_flagging="never",
)
########################################################
if __name__ == "__main__":
demo.launch()
|