Rooni commited on
Commit
1af3549
·
1 Parent(s): f8dd596

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -73
app.py CHANGED
@@ -1,88 +1,65 @@
1
  import gradio as gr
2
- import openai
3
  import os
4
  from PIL import Image
5
  import requests
6
  from io import BytesIO
7
 
8
- # Загрузим API ключ из переменных окружения
9
- openai.api_key = os.getenv("API_KEY")
10
 
11
- # Функция для генерации изображения
12
- def generate_image(prompt, seed, sampling, cfg, width, height):
13
- response = openai.Image.create(
14
- prompt=prompt,
15
- n=1,
16
- size=f"{width}x{height}",
17
- seed=seed,
18
- sampling=sampling,
19
- cfg_scale=cfg
20
- )
21
- image_url = response['data'][0]['url']
22
- image = Image.open(requests.get(image_url, stream=True).raw)
23
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  # Функция для улучшения качества изображения
26
  def upscale_image(image, upscale_factor):
27
- # Преобразуем PIL Image в Bytes, чтобы отправить его обратно в Gradio UI
28
- buffered = BytesIO()
29
- image.save(buffered, format="JPEG")
30
- img_str = buffered.getvalue()
 
 
 
 
 
31
 
32
- response = openai.Image.modify(
33
- image=img_str,
34
- n=1,
35
- size=f"{image.width * upscale_factor}x{image.height * upscale_factor}"
36
- )
37
- upscaled_image_url = response['data'][0]['url']
38
- upscaled_image = Image.open(requests.get(upscaled_image_url, stream=True).raw)
39
- return upscaled_image
40
-
41
- # Создаем интерфейс с вкладками
42
- with gr.Blocks() as demo:
43
- gr.Markdown("<style>footer { display: none; }</style>") # Скрываем footer
44
- with gr.Tabs():
45
- with gr.TabItem("Базовые настройки"):
46
- with gr.Row():
47
- prompt_input = gr.Textbox(label="Prompt", lines=3, placeholder="Введите описание изображения")
48
- with gr.TabItem("Расширенные настройки"):
49
- with gr.Row():
50
- seed_input = gr.Number(label="Seed", value=0)
51
- sampling_input = gr.Dropdown(label="Sampling Method", choices=["ancestral", "ddim"])
52
- cfg_input = gr.Slider(label="CFG Scale", minimum=1, maximum=20, value=7)
53
- width_input = gr.Number(label="Width", value=256)
54
- height_input = gr.Number(label="Height", value=256)
55
- with gr.TabItem("Настройки апскейлинга"):
56
- with gr.Row():
57
- upscale_factor_input = gr.Slider(label="Upscale Factor", minimum=2, maximum=6, value=2)
58
-
59
- with gr.Row():
60
- generate_button = gr.Button("Генерация")
61
- upscale_button = gr.Button("Улучшить качество", visible=False)
62
-
63
- original_image_output = gr.Image(label="Сгенерированное изображение", visible=False)
64
- upscaled_image_output = gr.Image(label="Улучшенное изображение", visible=False)
65
-
66
- # Обработчики событий кнопок
67
- def generate_button_click():
68
- image = generate_image(
69
- prompt_input.value,
70
- seed_input.value,
71
- sampling_input.value,
72
- cfg_input.value,
73
- width_input.value,
74
- height_input.value
75
- )
76
- original_image_output.update(value=image, visible=True)
77
- upscale_button.update(visible=True)
78
- return image
79
-
80
- def upscale_button_click(image):
81
- upscaled_image = upscale_image(image, upscale_factor_input.value)
82
- upscaled_image_output.update(value=upscaled_image, visible=True)
83
  return upscaled_image
 
 
 
84
 
85
- generate_button.click(fn=generate_button_click, inputs=[], outputs=[original_image_output])
86
- upscale_button.click(fn=upscale_button_click, inputs=[original_image_output], outputs=[upscaled_image_output])
87
 
 
88
  demo.launch()
 
1
  import gradio as gr
 
2
  import os
3
  from PIL import Image
4
  import requests
5
  from io import BytesIO
6
 
7
+ # Получаем API ключ из переменных окружения
8
+ API_KEY = os.getenv("API_KEY")
9
 
10
+ # Функция для генерации изображения с помощью DALL-E 3 API
11
+ def generate_image(prompt, seed, sampling_method, cfg, width, height):
12
+ headers = {
13
+ "Authorization": f"Bearer {API_KEY}"
14
+ }
15
+ data = {
16
+ "prompt": prompt,
17
+ "seed": seed,
18
+ "sampling_method": sampling_method,
19
+ "cfg": cfg,
20
+ "width": width,
21
+ "height": height
22
+ }
23
+
24
+ response = requests.post("https://api.openai.com/v1/images/generate", headers=headers, json=data)
25
+
26
+ if response.status_code == 200:
27
+ image_data = response.json()
28
+ # Предполагаем, что API возвращает URL изображения
29
+ image_url = image_data["data"]["image_url"]
30
+ image_response = requests.get(image_url)
31
+ image = Image.open(BytesIO(image_response.content))
32
+ return image
33
+ else:
34
+ # В случае ошибки возвращаем сообщение об ошибке
35
+ return f"Error: {response.text}"
36
 
37
  # Функция для улучшения качества изображения
38
  def upscale_image(image, upscale_factor):
39
+ headers = {
40
+ "Authorization": f"Bearer {API_KEY}"
41
+ }
42
+ files = {
43
+ "image": image
44
+ }
45
+ data = {
46
+ "upscale_factor": upscale_factor
47
+ }
48
 
49
+ response = requests.post("https://api.openai.com/v1/images/upscale", headers=headers, files=files, data=data)
50
+
51
+ if response.status_code == 200:
52
+ image_data = response.json()
53
+ # Предполагаем, что API возвращает URL улучшенного изображения
54
+ image_url = image_data["data"]["image_url"]
55
+ image_response = requests.get(image_url)
56
+ upscaled_image = Image.open(BytesIO(image_response.content))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  return upscaled_image
58
+ else:
59
+ # В случае ошибки возвращаем сообщение об ошибке
60
+ return f"Error: {response.text}"
61
 
62
+ # Определение интерфейса с использованием блоков Gradio (код интерфейса остается тем же)
 
63
 
64
+ # Запуск интерфейса
65
  demo.launch()