Rooni commited on
Commit
d040dbe
·
verified ·
1 Parent(s): 73f8914

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -59
app.py CHANGED
@@ -15,7 +15,10 @@ MAX_IMAGE_SIZE = 1024
15
 
16
  def get_random_api_key():
17
  keys = os.getenv("KEYS", "").split(",")
18
- return random.choice(keys).strip()
 
 
 
19
 
20
  def resize_img(image, max_size=1024):
21
  width, height = image.size
@@ -33,7 +36,11 @@ def process_image(
33
  width,
34
  height,
35
  model_choice,
 
 
 
36
  ):
 
37
  api_key = get_random_api_key()
38
 
39
  if randomize_seed:
@@ -42,16 +49,15 @@ def process_image(
42
  if image is None:
43
  return None, seed
44
 
45
- # Download image from URL if provided
46
  if isinstance(image, str) and image.startswith("http"):
47
  try:
48
  response = requests.get(image, stream=True)
49
- response.raise_for_status() # Raise an exception for bad status codes (e.g., 404)
50
  image = Image.open(BytesIO(response.content))
51
  except requests.exceptions.RequestException as e:
52
  print(f"Error downloading image from URL: {e}")
53
  return "Ошибка загрузки изображения", seed
54
- elif not isinstance(image, Image.Image): # Convert to PIL image if needed
55
  image = Image.fromarray(image)
56
 
57
  resized_image = resize_img(image)
@@ -61,71 +67,105 @@ def process_image(
61
  image_path = temp_file.name
62
 
63
  language = detect(prompt)
64
-
65
  if language != 'en':
66
  prompt = GoogleTranslator(source=language, target='en').translate(prompt)
67
 
68
  try:
69
-
70
  if model_choice == "Stable Diffusion":
71
  client = Client("InstantX/SD35-IP-Adapter", hf_token=api_key)
 
 
 
 
 
 
 
 
 
72
 
73
  elif model_choice == "Flux":
74
  client = Client("InstantX/flux-IP-adapter", hf_token=api_key)
75
-
76
- result = client.predict(
77
- image=handle_file(image_path), # Отправляем скачанный файл
78
- prompt=prompt,
79
- scale=scale,
80
- seed=seed,
81
- randomize_seed=randomize_seed,
82
- width=width,
83
- height=height,
84
- api_name="/process_image"
85
- )
86
- generated_image_url = result[0]
87
- print(f"Generated image URL: {generated_image_url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  finally:
89
  os.remove(image_path)
90
 
91
- return gr.update(value=generated_image_url), result[1]
92
- # Ссылка на файл CSS
93
- css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
94
 
95
- # Получение CSS по ссылке
96
- response = requests.get(css_url)
97
- css = response.text + " .gradio-container{max-width: 700px !important} h1{text-align:center} #col-container { margin: 0 auto; max-width: 960px; }"
98
 
99
- # Create the Gradio interface
100
  with gr.Blocks(css=css) as demo:
101
  with gr.Column(elem_id="col-container"):
102
  gr.Markdown("# Ии Редактор")
103
-
104
- with gr.Row():
105
- with gr.Column():
106
- input_image = gr.Image(
107
- label="Входное изображение",
108
- type="pil"
109
- )
110
- scale = gr.Slider(
111
- label="Схожесть с оригиналом",
112
- minimum=0.0,
113
- maximum=1.0,
114
- step=0.1,
115
- value=0.7,
116
- )
117
- prompt = gr.Text(
118
- label="Описание изображения",
119
- max_lines=1,
120
- placeholder="Введите ваш запрос (Например: Сделай в аниме стиле)",
121
- )
122
- model_choice = gr.Radio(choices=["Stable Diffusion", "Flux"], value="Stable Diffusion", label="Модель")
123
-
124
- run_button = gr.Button("Изменить", variant="primary")
125
-
126
- with gr.Column():
127
- result = gr.Image(label="Результат", show_share_button=False)
128
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  with gr.Accordion("Дополнительные настройки", open=False):
130
  seed = gr.Slider(
131
  label="Сид",
@@ -134,9 +174,7 @@ with gr.Blocks(css=css) as demo:
134
  step=1,
135
  value=42,
136
  )
137
-
138
  randomize_seed = gr.Checkbox(label="Случайный сид", value=True)
139
-
140
  with gr.Row():
141
  width = gr.Slider(
142
  label="Ширина",
@@ -145,15 +183,16 @@ with gr.Blocks(css=css) as demo:
145
  step=32,
146
  value=1024,
147
  )
148
-
149
  height = gr.Slider(
150
  label="Высота",
151
  minimum=256,
152
  maximum=MAX_IMAGE_SIZE,
153
  step=32,
154
  value=1024,
155
- )
156
-
 
 
157
  run_button.click(
158
  fn=process_image,
159
  inputs=[
@@ -164,11 +203,15 @@ with gr.Blocks(css=css) as demo:
164
  randomize_seed,
165
  width,
166
  height,
167
- model_choice,
 
 
 
168
  ],
169
  outputs=[result, seed],
170
- concurrency_limit=250,
171
  )
172
 
 
173
  if __name__ == "__main__":
174
  demo.queue(max_size=250).launch(show_api=False, share=False)
 
 
15
 
16
  def get_random_api_key():
17
  keys = os.getenv("KEYS", "").split(",")
18
+ if keys and keys[0]: # Check if KEYS is set and not empty
19
+ return random.choice(keys).strip()
20
+ else:
21
+ raise ValueError("API keys not found. Please set the KEYS environment variable.")
22
 
23
  def resize_img(image, max_size=1024):
24
  width, height = image.size
 
36
  width,
37
  height,
38
  model_choice,
39
+ negative_prompt="", # Add negative_prompt parameter
40
+ guidance_scale=5, # Add guidance_scale parameter
41
+ num_inference_steps=25, # Add num_inference_steps parameter
42
  ):
43
+
44
  api_key = get_random_api_key()
45
 
46
  if randomize_seed:
 
49
  if image is None:
50
  return None, seed
51
 
 
52
  if isinstance(image, str) and image.startswith("http"):
53
  try:
54
  response = requests.get(image, stream=True)
55
+ response.raise_for_status()
56
  image = Image.open(BytesIO(response.content))
57
  except requests.exceptions.RequestException as e:
58
  print(f"Error downloading image from URL: {e}")
59
  return "Ошибка загрузки изображения", seed
60
+ elif not isinstance(image, Image.Image):
61
  image = Image.fromarray(image)
62
 
63
  resized_image = resize_img(image)
 
67
  image_path = temp_file.name
68
 
69
  language = detect(prompt)
 
70
  if language != 'en':
71
  prompt = GoogleTranslator(source=language, target='en').translate(prompt)
72
 
73
  try:
 
74
  if model_choice == "Stable Diffusion":
75
  client = Client("InstantX/SD35-IP-Adapter", hf_token=api_key)
76
+ result = client.predict(
77
+ image=handle_file(image_path),
78
+ prompt=prompt,
79
+ scale=scale,
80
+ seed=seed,
81
+ width=width,
82
+ height=height,
83
+ api_name="/process_image"
84
+ )
85
 
86
  elif model_choice == "Flux":
87
  client = Client("InstantX/flux-IP-adapter", hf_token=api_key)
88
+ result = client.predict(
89
+ image=handle_file(image_path),
90
+ prompt=prompt,
91
+ scale=scale,
92
+ seed=seed,
93
+ width=width,
94
+ height=height,
95
+ api_name="/process_image"
96
+ )
97
+
98
+ elif model_choice == "Kolors":
99
+ client = Client("multimodalart/Kolors-IPAdapter", hf_token=api_key)
100
+ result = client.predict(
101
+ prompt=prompt,
102
+ ip_adapter_image=handle_file(image_path),
103
+ ip_adapter_scale=scale,
104
+ negative_prompt=negative_prompt,
105
+ seed=seed,
106
+ width=width,
107
+ height=height,
108
+ guidance_scale=guidance_scale,
109
+ num_inference_steps=num_inference_steps,
110
+ api_name="/infer"
111
+ )
112
+
113
+ generated_image = result[0]
114
+
115
  finally:
116
  os.remove(image_path)
117
 
 
 
 
118
 
119
+ return gr.update(value=generated_image), result[1]
120
+
121
+
122
 
 
123
  with gr.Blocks(css=css) as demo:
124
  with gr.Column(elem_id="col-container"):
125
  gr.Markdown("# Ии Редактор")
126
+
127
+ input_image = gr.Image(label="Входное изображение", type="pil")
128
+ result = gr.Image(label="Результат", show_share_button=False)
129
+
130
+
131
+ with gr.Tabs():
132
+ with gr.TabItem("Stable Diffusion & Flux"):
133
+ with gr.Row():
134
+ with gr.Column():
135
+ prompt = gr.Text(
136
+ label="Описание изображения",
137
+ max_lines=1,
138
+ placeholder="Введите ваш запрос (Например: Сделай в аниме стиле)",
139
+ )
140
+ model_choice_sf = gr.Radio(choices=["Stable Diffusion", "Flux"], value="Stable Diffusion", label="Модель")
141
+ scale = gr.Slider(
142
+ label="Схожесть с оригиналом (scale)",
143
+ minimum=0.0,
144
+ maximum=1.0,
145
+ step=0.1,
146
+ value=0.7,
147
+ )
148
+
149
+ with gr.TabItem("Kolors"):
150
+ with gr.Row():
151
+ with gr.Column():
152
+ prompt_kolors = gr.Text(
153
+ label="Описание изображения",
154
+ max_lines=1,
155
+ placeholder="Введите ваш запрос (Например: Сделай в аниме стиле)",
156
+ )
157
+ negative_prompt = gr.Text(label="Негативное описание", max_lines=1)
158
+ scale_kolors = gr.Slider(
159
+ label="Схожесть с оригиналом (ip_adapter_scale)",
160
+ minimum=0.0,
161
+ maximum=1.0,
162
+ step=0.1,
163
+ value=0.5,
164
+ )
165
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=0, maximum=20, value=7, step=0.5)
166
+ num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=50, value=25, step=1)
167
+
168
+
169
  with gr.Accordion("Дополнительные настройки", open=False):
170
  seed = gr.Slider(
171
  label="Сид",
 
174
  step=1,
175
  value=42,
176
  )
 
177
  randomize_seed = gr.Checkbox(label="Случайный сид", value=True)
 
178
  with gr.Row():
179
  width = gr.Slider(
180
  label="Ширина",
 
183
  step=32,
184
  value=1024,
185
  )
 
186
  height = gr.Slider(
187
  label="Высота",
188
  minimum=256,
189
  maximum=MAX_IMAGE_SIZE,
190
  step=32,
191
  value=1024,
192
+ )
193
+ run_button = gr.Button("Изменить", variant="primary")
194
+
195
+
196
  run_button.click(
197
  fn=process_image,
198
  inputs=[
 
203
  randomize_seed,
204
  width,
205
  height,
206
+ model_choice_sf, # Use model_choice_sf here
207
+ negative_prompt,
208
+ guidance_scale,
209
+ num_inference_steps
210
  ],
211
  outputs=[result, seed],
 
212
  )
213
 
214
+
215
  if __name__ == "__main__":
216
  demo.queue(max_size=250).launch(show_api=False, share=False)
217
+