Rooni commited on
Commit
dfde0fa
·
1 Parent(s): ef5ea7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -62
app.py CHANGED
@@ -1,79 +1,51 @@
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;
50
- }
51
  """
52
 
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")
61
- sampling_method_input = gr.Dropdown(label="Sampling Method", choices=["ddim", "plms"])
62
- cfg_input = gr.Number(label="CFG")
63
- with gr.Row():
64
- width_input = gr.Number(label="Width")
65
- height_input = gr.Number(label="Height")
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()
 
1
  import gradio as gr
2
  import requests
3
  import os
 
 
4
 
5
+ # Функция для генерации изображения с помощью DALL-E 3 API
6
+ def generate_image(prompt, seed, sampling_method, cfg, width, height):
7
  headers = {
8
+ "Authorization": f"Bearer {os.getenv('API_KEY')}",
9
+ "Content-Type": "application/json",
10
  }
 
11
  data = {
12
+ "prompt": prompt,
13
+ "num_images": 1,
14
+ "seed": seed,
15
+ "sampling_method": sampling_method,
16
+ "cfg": cfg,
17
+ "width": width,
18
+ "height": height
19
  }
20
+ response = requests.post("https://api.openai.com/v1/engines/dalle-3/images", headers=headers, json=data)
21
+ if response.status_code == 200:
22
+ image_url = response.json()["data"][0]["url"]
23
+ return image_url
24
+ else:
25
+ return "Ошибка при генерации изображения"
26
+
27
+ # CSS для скрытия footer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  css = """
29
+ footer { display: none; }
 
 
30
  """
31
 
32
  with gr.Blocks(css=css) as demo:
33
+ with gr.Tabs():
34
+ with gr.TabItem("Базовые настройки"):
35
+ prompt_input = gr.Textbox(label="Введите текст для генерации изображения", lines=3, placeholder="Введите текст...")
36
+ with gr.TabItem("Расширенные настройки"):
37
+ seed_input = gr.Number(label="Сид", value=0)
38
+ sampling_method_input = gr.Dropdown(label="Метод семплирования", choices=["Default", "DDIM", "PLMS"], value="Default")
39
+ cfg_input = gr.Slider(label="CFG", minimum=1, maximum=20, value=7)
40
+ width_input = gr.Number(label="Ширина", value=512)
41
+ height_input = gr.Number(label="Высота", value=512)
42
+ generate_button = gr.Button("Генерация", variant="primary")
43
+ output_image = gr.Image()
44
+
 
 
 
 
 
 
45
  generate_button.click(
46
  generate_image,
47
  inputs=[prompt_input, seed_input, sampling_method_input, cfg_input, width_input, height_input],
48
+ outputs=output_image,
49
  )
50
 
51
+ demo.launch()