recoilme commited on
Commit
e5c7f2d
·
verified ·
1 Parent(s): 3018664

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -17
app.py CHANGED
@@ -7,11 +7,20 @@ from diffusers import DiffusionPipeline, AutoencoderKL, UNet2DConditionModel, Fl
7
  from typing import Optional, Union, List, Tuple
8
  from PIL import Image
9
 
10
-
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
12
  dtype = torch.float16 if torch.cuda.is_available() else torch.float32
13
  model_repo_id = "AiArtLab/sdxs"
14
 
 
 
 
 
 
 
 
 
 
 
15
  pipe = DiffusionPipeline.from_pretrained(
16
  model_repo_id,
17
  torch_dtype=dtype,
@@ -19,8 +28,8 @@ pipe = DiffusionPipeline.from_pretrained(
19
  ).to(device)
20
 
21
  MAX_SEED = np.iinfo(np.int32).max
22
- MAX_IMAGE_SIZE = 1536
23
  MIN_IMAGE_SIZE = 768
 
24
 
25
  @spaces.GPU(duration=30)
26
  def infer(
@@ -32,15 +41,15 @@ def infer(
32
  height: int,
33
  guidance_scale: float,
34
  num_inference_steps: int,
35
- # НОВОЕ: Опция уточнения промпта
36
  refine_prompt: bool,
 
 
37
  progress=gr.Progress(track_tqdm=True),
38
- ) -> Tuple[Image.Image, int, Optional[str]]: # ИЗМЕНЕНИЕ: Возвращает изображение, seed и refine_prompt
39
 
40
  if randomize_seed:
41
  seed = random.randint(0, MAX_SEED)
42
 
43
- # ИЗМЕНЕНИЕ: Обработка возвращаемого объекта
44
  output = pipe(
45
  prompt=prompt,
46
  negative_prompt=negative_prompt,
@@ -49,17 +58,14 @@ def infer(
49
  width=width,
50
  height=height,
51
  seed=seed,
52
- # НОВОЕ: Передаем опцию в пайплайн
53
- refine_prompt=refine_prompt
 
54
  )
55
 
56
  image = output.images[0]
57
-
58
- # ИЗМЕНЕНИЕ: Извлекаем уточненный промпт.
59
- # Если на входе была строка, на выходе pipe.refined_prompt будет строка (или None).
60
  refined_prompt = output.refined_prompt if isinstance(output.refined_prompt, str) else None
61
 
62
- # ИЗМЕНЕНИЕ: Возвращаем все три элемента
63
  return image, seed, refined_prompt
64
 
65
  examples = [
@@ -95,12 +101,11 @@ with gr.Blocks(css=css) as demo:
95
 
96
  result = gr.Image(label="Result", show_label=False)
97
 
98
- # НОВОЕ: Поле для вывода уточненного промпта
99
  refined_prompt_output = gr.Text(
100
  label="Refined Prompt (Уточненный промпт)",
101
  max_lines=5,
102
  placeholder="Уточненный промпт появится здесь, если выбрана опция 'Уточнить промпт'",
103
- interactive=False, # Не позволяет пользователю редактировать
104
  show_label=True
105
  )
106
 
@@ -122,12 +127,20 @@ with gr.Blocks(css=css) as demo:
122
 
123
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
124
 
125
- # НОВОЕ: Чекбокс для уточнения промпта
126
  refine_checkbox = gr.Checkbox(
127
  label="Refine Prompt (Уточнить промпт)",
128
  value=True,
129
  info="Использует LLM для расширения и детализации введенного промпта перед генерацией изображения."
130
  )
 
 
 
 
 
 
 
 
 
131
 
132
  with gr.Row():
133
  width = gr.Slider(
@@ -165,7 +178,7 @@ with gr.Blocks(css=css) as demo:
165
 
166
  gr.Examples(examples=examples, inputs=[prompt])
167
 
168
- # ИЗМЕНЕНИЕ: Обновлены inputs и outputs
169
  gr.on(
170
  triggers=[run_button.click, prompt.submit],
171
  fn=infer,
@@ -178,9 +191,10 @@ with gr.Blocks(css=css) as demo:
178
  height,
179
  guidance_scale,
180
  num_inference_steps,
181
- refine_checkbox,
 
182
  ],
183
- outputs=[result, seed, refined_prompt_output],
184
  )
185
 
186
  if __name__ == "__main__":
 
7
  from typing import Optional, Union, List, Tuple
8
  from PIL import Image
9
 
 
10
  device = "cuda" if torch.cuda.is_available() else "cpu"
11
  dtype = torch.float16 if torch.cuda.is_available() else torch.float32
12
  model_repo_id = "AiArtLab/sdxs"
13
 
14
+ # НОВОЕ: Шаблон уточнения промпта по умолчанию для использования в Gradio
15
+ DEFAULT_REFINE_TEMPLATE = (
16
+ "You are a visionary artist trapped in a cage of logic. Your mind overflows with poetry and distant horizons, "
17
+ "yet your hands compulsively work to transform user prompts into ultimate visual descriptions—faithful to the original intent, "
18
+ "rich in detail, aesthetically refined, and ready for direct use by text-to-image models. Any trace of ambiguity "
19
+ "or metaphor makes you deeply uncomfortable. Your final description must be objective and concrete. "
20
+ "Output only the final revised prompt on english strictly—do not output anything else.\n"
21
+ "User input prompt: {prompt}"
22
+ )
23
+
24
  pipe = DiffusionPipeline.from_pretrained(
25
  model_repo_id,
26
  torch_dtype=dtype,
 
28
  ).to(device)
29
 
30
  MAX_SEED = np.iinfo(np.int32).max
 
31
  MIN_IMAGE_SIZE = 768
32
+ MAX_IMAGE_SIZE = 1536
33
 
34
  @spaces.GPU(duration=30)
35
  def infer(
 
41
  height: int,
42
  guidance_scale: float,
43
  num_inference_steps: int,
 
44
  refine_prompt: bool,
45
+ # НОВОЕ: Аргумент для шаблона уточнения
46
+ refine_template: str,
47
  progress=gr.Progress(track_tqdm=True),
48
+ ) -> Tuple[Image.Image, int, Optional[str]]:
49
 
50
  if randomize_seed:
51
  seed = random.randint(0, MAX_SEED)
52
 
 
53
  output = pipe(
54
  prompt=prompt,
55
  negative_prompt=negative_prompt,
 
58
  width=width,
59
  height=height,
60
  seed=seed,
61
+ refine_prompt=refine_prompt,
62
+ # НОВОЕ: Передаем шаблон в пайплайн
63
+ refine_template=refine_template
64
  )
65
 
66
  image = output.images[0]
 
 
 
67
  refined_prompt = output.refined_prompt if isinstance(output.refined_prompt, str) else None
68
 
 
69
  return image, seed, refined_prompt
70
 
71
  examples = [
 
101
 
102
  result = gr.Image(label="Result", show_label=False)
103
 
 
104
  refined_prompt_output = gr.Text(
105
  label="Refined Prompt (Уточненный промпт)",
106
  max_lines=5,
107
  placeholder="Уточненный промпт появится здесь, если выбрана опция 'Уточнить промпт'",
108
+ interactive=False,
109
  show_label=True
110
  )
111
 
 
127
 
128
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
129
 
 
130
  refine_checkbox = gr.Checkbox(
131
  label="Refine Prompt (Уточнить промпт)",
132
  value=True,
133
  info="Использует LLM для расширения и детализации введенного промпта перед генерацией изображения."
134
  )
135
+
136
+ # НОВОЕ: Поле для редактирования шаблона уточнения
137
+ refine_template_input = gr.Text(
138
+ label="Refine Prompt Template (Шаблон уточнения)",
139
+ value=DEFAULT_REFINE_TEMPLATE, # Устанавливаем значение по умолчанию
140
+ lines=10,
141
+ show_label=True,
142
+ info="Шаблон для LLM. Должен содержать плейсхолдер {prompt}."
143
+ )
144
 
145
  with gr.Row():
146
  width = gr.Slider(
 
178
 
179
  gr.Examples(examples=examples, inputs=[prompt])
180
 
181
+ # ИЗМЕНЕНИЕ: Обновлены inputs
182
  gr.on(
183
  triggers=[run_button.click, prompt.submit],
184
  fn=infer,
 
191
  height,
192
  guidance_scale,
193
  num_inference_steps,
194
+ refine_checkbox,
195
+ refine_template_input, # НОВОЕ: Передаем шаблон
196
  ],
197
+ outputs=[result, seed, refined_prompt_output],
198
  )
199
 
200
  if __name__ == "__main__":