Rooni commited on
Commit
bbe7ddd
·
1 Parent(s): b3ee695

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -24
app.py CHANGED
@@ -1,12 +1,49 @@
1
- import os
2
  import gradio as gr
3
- from gradio.external import load_interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # Загрузка интерфейса DALL-E с использованием API ключа
6
- api_key = os.getenv("API_KEY")
7
- dalle = load_interface("openai/dalle", api_key=api_key)
8
 
9
- # CSS для скрытия footer
 
 
 
 
 
 
10
  css = """
11
  footer {
12
  display: none;
@@ -16,31 +53,27 @@ footer {
16
  with gr.Blocks(css=css) as demo:
17
  with gr.Tab("Базовые настройки"):
18
  with gr.Row():
19
- prompt_input = gr.Textbox(label="Prompt", lines=3, placeholder="Введите описание изображения...")
20
-
21
- with gr.Tab("Расширенные настройки"):
 
 
 
 
22
  with gr.Row():
23
- seed_input = gr.Number(label="Seed", value=0)
24
- sampling_method_input = gr.Dropdown(label="Sampling Method", choices=["random", "DDIM", "DPM++", "DPM++_ancestral", "Heuristic"], value="random")
25
- cfg_input = gr.Slider(label="CFG", minimum=1, maximum=20, value=7)
26
- width_input = gr.Number(label="Width", value=256)
27
- height_input = gr.Number(label="Height", value=256)
28
-
29
  with gr.Row():
30
  generate_button = gr.Button("Генерация", variant="primary")
31
-
32
- output_image = gr.Image(label="Сгенерированное изображение")
33
-
34
- def generate_image(prompt, seed, sampling_method, cfg, width, height):
35
- # Генерация изображения с помощью DALL-E API
36
- response = dalle([prompt], num_images=1, seed=seed, sampling=sampling_method, cfg_scale=cfg, width=width, height=height)
37
- image_url = response[0][0]["url"]
38
- return image_url
39
 
 
40
  generate_button.click(
41
  generate_image,
42
  inputs=[prompt_input, seed_input, sampling_method_input, cfg_input, width_input, height_input],
43
  outputs=output_image
44
  )
45
 
46
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
+ from PIL import Image
5
+ from io import BytesIO
6
+
7
+ # Функция для генерации изображения с использованием DALL-E 3 API
8
+ def generate_image(prompt, seed=None, sampling_method=None, cfg=None, width=None, height=None):
9
+ headers = {
10
+ 'Authorization': f'Bearer {os.getenv("API_KEY")}',
11
+ 'Content-Type': 'application/json',
12
+ }
13
+
14
+ data = {
15
+ 'prompt': prompt,
16
+ 'n': 1,
17
+ 'size': '1024x1024',
18
+ }
19
+
20
+ # Добавление расширенных настроек, если они предоставлены
21
+ if seed is not None:
22
+ data['seed'] = seed
23
+ if sampling_method is not None:
24
+ data['sampling'] = sampling_method
25
+ if cfg is not None:
26
+ data['cfg'] = cfg
27
+ if width is not None and height is not None:
28
+ data['size'] = f'{width}x{height}'
29
+
30
+ response = requests.post('https://api.openai.com/v1/images/generations', headers=headers, json=data)
31
+ response_json = response.json()
32
+
33
+ # Проверка на наличие ошибок
34
+ if response.status_code != 200:
35
+ return "Error: " + response_json.get('error', 'Unknown error')
36
 
37
+ # Получение URL сгенерированного изображения
38
+ image_url = response_json['data'][0]['urls'][-1]
 
39
 
40
+ # Загрузка изображения и конвертация в формат, подходящий для Gradio
41
+ image_response = requests.get(image_url)
42
+ image = Image.open(BytesIO(image_response.content))
43
+
44
+ return image
45
+
46
+ # CSS для скрытия футера
47
  css = """
48
  footer {
49
  display: none;
 
53
  with gr.Blocks(css=css) as demo:
54
  with gr.Tab("Базовые настройки"):
55
  with gr.Row():
56
+ prompt_input = gr.Textbox(label="Prompt", lines=3, placeholder="Введите описание изображения")
57
+
58
+ with gr.Tab("Расширенные нас��ройки"):
59
+ with gr.Row():
60
+ seed_input = gr.Number(label="Seed", placeholder="Введите seed (целое число)")
61
+ sampling_method_input = gr.Dropdown(label="Sampling Method", choices=["ddim", "plms"], placeholder="Выберите метод семплирования")
62
+ cfg_input = gr.Number(label="CFG", placeholder="Введите CFG (число)")
63
  with gr.Row():
64
+ width_input = gr.Number(label="Width", placeholder="Введите ширину изображения")
65
+ height_input = gr.Number(label="Height", placeholder="Введите высоту изображения")
66
+
 
 
 
67
  with gr.Row():
68
  generate_button = gr.Button("Генерация", variant="primary")
69
+ output_image = gr.Image(label="Сгенерированное изображение")
 
 
 
 
 
 
 
70
 
71
+ # Обработчик кнопки для генерации изображения
72
  generate_button.click(
73
  generate_image,
74
  inputs=[prompt_input, seed_input, sampling_method_input, cfg_input, width_input, height_input],
75
  outputs=output_image
76
  )
77
 
78
+ if __name__ == "__main__":
79
+ demo.launch()