fantaxy commited on
Commit
432a7d3
·
verified ·
1 Parent(s): 309afbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -104
app.py CHANGED
@@ -1,61 +1,57 @@
 
 
1
  import os
2
- from dotenv import load_dotenv
3
  import logging
4
- from notion_client import Client
5
- import gradio as gr
6
- from gradio_client import Client as GradioClient
7
- import requests
8
  from datetime import datetime
9
 
10
-
11
- # 로깅 설정
12
- logging.basicConfig(level=logging.INFO)
13
-
14
- # 환경 변수 로드
15
- load_dotenv()
16
-
17
  # 로깅 설정
18
  logging.basicConfig(level=logging.INFO)
19
 
20
  # API 클라이언트 설정
21
  api_client = Client("http://211.233.58.202:7960/")
22
 
23
- # Notion API 설정
24
- NOTION_API_KEY = "secret_MpVfJphbfo4599fdczYfMYKNOpyzCcvkhhzk3lgTfVk"
25
- NOTION_DATABASE_ID = "88c9bdad-cb20-4412-9af7-7d5932e1a82a"
26
- NOTION_API_URL = "https://api.notion.com/v1"
27
-
28
- # Notion 클라이언트 초기화
29
- notion = Client(auth=NOTION_API_KEY)
30
-
31
- # Gradio API 클라이언트 설정
32
- gradio_client = GradioClient("http://211.233.58.202:7960/")
33
-
34
- def create_notion_database():
35
- new_database = notion.databases.create(
36
- parent={"type": "page_id", "page_id": NOTION_PAGE_ID},
37
- title=[{"type": "text", "text": {"content": "Generated Images"}}],
38
- properties={
39
- "Name": {"title": {}},
40
- "Prompt": {"rich_text": {}},
41
- "Image": {"url": {}},
42
- "Created At": {"date": {}}
43
- }
44
- )
45
- return new_database.id
46
-
47
- def add_page_to_notion_database(database_id, name, prompt, image_url):
48
- new_page = notion.pages.create(
49
- parent={"database_id": database_id},
50
- properties={
51
- "Name": {"title": [{"text": {"content": name}}]},
52
- "Prompt": {"rich_text": [{"text": {"content": prompt}}]},
53
- "Image": {"url": image_url},
54
- "Created At": {"date": {"start": datetime.now().isoformat()}}
55
- }
56
- )
57
- return new_page.url
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  def respond(message, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
61
  logging.info(f"Received message: {message}, seed: {seed}, randomize_seed: {randomize_seed}, "
@@ -64,7 +60,7 @@ def respond(message, seed, randomize_seed, width, height, guidance_scale, num_in
64
 
65
  try:
66
  # 이미지 생성 요청
67
- result = gradio_client.predict(
68
  prompt=message,
69
  seed=seed,
70
  randomize_seed=randomize_seed,
@@ -79,33 +75,13 @@ def respond(message, seed, randomize_seed, width, height, guidance_scale, num_in
79
  # 결과 확인 및 처리
80
  if isinstance(result, tuple) and len(result) >= 1:
81
  image_path = result[0]
82
- image_url = f"http://211.233.58.202:7960/file={image_path}"
83
-
84
- # Notion 데이터베이스 생성 (이미 존재한다면 기존 ID 사용)
85
- database_id = NOTION_DATABASE_ID # 이 변수를 미리 정의해야 합니다
86
- if not database_id:
87
- database_id = create_notion_database()
88
- NOTION_DATABASE_ID = database_id # 전역 변수로 저장
89
-
90
- # Notion에 페이지 추가
91
- page_url = add_page_to_notion_database(
92
- database_id,
93
- f"Generated Image - {datetime.now().isoformat()}",
94
- message,
95
- image_url
96
- )
97
-
98
- logging.info(f"Added to Notion: {page_url}")
99
- return image_url, page_url
100
  else:
101
  raise ValueError("Unexpected API response format")
102
  except Exception as e:
103
  logging.error("Error during API request: %s", str(e))
104
- return "Failed to generate image due to an error.", None
105
-
106
-
107
- def use_prompt(prompt):
108
- return prompt
109
 
110
  css = """
111
  footer {
@@ -113,6 +89,8 @@ footer {
113
  }
114
  """
115
 
 
 
116
  # 이미지 생성을 위한 예제 프롬프트
117
  examples = [
118
  ["A glamorous young woman with long, wavy blonde hair and smokey eye makeup, posing in a luxury hotel room. She’s wearing a sparkly gold cocktail dress and holding up a white card with 'openfree.ai' written on it in elegant calligraphy. Soft, warm lighting creates a luxurious atmosphere. ", "q1.webp"],
@@ -137,46 +115,68 @@ examples = [
137
  ["A fantasy map of a fictional world, with detailed terrain and cities.", "q19.webp"]
138
  ]
139
 
140
-
 
141
 
142
  with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
143
-
144
-
145
- with gr.Row():
146
- input_text = gr.Textbox(label="Enter your prompt for image generation")
147
- output_image = gr.Image(label="Generated Image")
148
-
149
- with gr.Row():
150
- seed = gr.Slider(minimum=0, maximum=1000000, step=1, label="Seed", value=123)
151
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)
152
-
153
- with gr.Row():
154
- width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=1024)
155
- height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=576)
156
-
157
- with gr.Row():
158
- guidance_scale = gr.Slider(minimum=1, maximum=20, step=0.1, label="Guidance Scale", value=5)
159
- num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Number of Inference Steps", value=28)
160
-
161
- with gr.Row():
162
- for prompt, image_file in examples:
163
- with gr.Column():
164
- gr.Image(image_file, label=prompt[:50] + "...") # 프롬프트의 처음 50자만 표시
165
- gr.Button("Use this prompt").click(
166
- fn=use_prompt,
167
- inputs=[],
168
- outputs=input_text,
169
- api_name=False
170
- ).then(
171
- lambda x=prompt: x,
172
- inputs=[],
173
- outputs=input_text
174
- )
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  input_text.submit(
177
  fn=respond,
178
  inputs=[input_text, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
179
  outputs=output_image
 
 
 
 
180
  )
181
 
182
  if __name__ == "__main__":
 
1
+ import gradio as gr
2
+ from gradio_client import Client
3
  import os
 
4
  import logging
5
+ import json
 
 
 
6
  from datetime import datetime
7
 
 
 
 
 
 
 
 
8
  # 로깅 설정
9
  logging.basicConfig(level=logging.INFO)
10
 
11
  # API 클라이언트 설정
12
  api_client = Client("http://211.233.58.202:7960/")
13
 
14
+ # 갤러리 저장 디렉토리 설정
15
+ GALLERY_DIR = "gallery"
16
+ GALLERY_JSON = "gallery.json"
17
+
18
+ # 갤러리 디렉토리 생성
19
+ os.makedirs(GALLERY_DIR, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ def save_to_gallery(image_path, prompt):
22
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
23
+ new_image_path = os.path.join(GALLERY_DIR, f"{timestamp}.png")
24
+
25
+ # 이미지 파일 복사
26
+ with open(image_path, "rb") as src, open(new_image_path, "wb") as dst:
27
+ dst.write(src.read())
28
+
29
+ # 갤러리 정보 저장
30
+ gallery_info = {
31
+ "image": new_image_path,
32
+ "prompt": prompt,
33
+ "timestamp": timestamp
34
+ }
35
+
36
+ if os.path.exists(GALLERY_JSON):
37
+ with open(GALLERY_JSON, "r") as f:
38
+ gallery = json.load(f)
39
+ else:
40
+ gallery = []
41
+
42
+ gallery.append(gallery_info)
43
+
44
+ with open(GALLERY_JSON, "w") as f:
45
+ json.dump(gallery, f, indent=2)
46
+
47
+ return new_image_path
48
+
49
+ def load_gallery():
50
+ if os.path.exists(GALLERY_JSON):
51
+ with open(GALLERY_JSON, "r") as f:
52
+ gallery = json.load(f)
53
+ return [(item["image"], item["prompt"]) for item in reversed(gallery)]
54
+ return []
55
 
56
  def respond(message, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
57
  logging.info(f"Received message: {message}, seed: {seed}, randomize_seed: {randomize_seed}, "
 
60
 
61
  try:
62
  # 이미지 생성 요청
63
+ result = api_client.predict(
64
  prompt=message,
65
  seed=seed,
66
  randomize_seed=randomize_seed,
 
75
  # 결과 확인 및 처리
76
  if isinstance(result, tuple) and len(result) >= 1:
77
  image_path = result[0]
78
+ saved_image_path = save_to_gallery(image_path, message)
79
+ return saved_image_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  else:
81
  raise ValueError("Unexpected API response format")
82
  except Exception as e:
83
  logging.error("Error during API request: %s", str(e))
84
+ return "Failed to generate image due to an error."
 
 
 
 
85
 
86
  css = """
87
  footer {
 
89
  }
90
  """
91
 
92
+
93
+
94
  # 이미지 생성을 위한 예제 프롬프트
95
  examples = [
96
  ["A glamorous young woman with long, wavy blonde hair and smokey eye makeup, posing in a luxury hotel room. She’s wearing a sparkly gold cocktail dress and holding up a white card with 'openfree.ai' written on it in elegant calligraphy. Soft, warm lighting creates a luxurious atmosphere. ", "q1.webp"],
 
115
  ["A fantasy map of a fictional world, with detailed terrain and cities.", "q19.webp"]
116
  ]
117
 
118
+ def use_prompt(prompt):
119
+ return prompt
120
 
121
  with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
122
+ with gr.Tab("Generate"):
123
+ with gr.Row():
124
+ input_text = gr.Textbox(label="Enter your prompt for image generation")
125
+ output_image = gr.Image(label="Generated Image")
126
+
127
+ with gr.Row():
128
+ seed = gr.Slider(minimum=0, maximum=1000000, step=1, label="Seed", value=123)
129
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)
130
+
131
+ with gr.Row():
132
+ width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=1024)
133
+ height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=576)
134
+
135
+ with gr.Row():
136
+ guidance_scale = gr.Slider(minimum=1, maximum=20, step=0.1, label="Guidance Scale", value=5)
137
+ num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Number of Inference Steps", value=28)
138
+
139
+ with gr.Row():
140
+ for prompt, image_file in examples:
141
+ with gr.Column():
142
+ gr.Image(image_file, label=prompt[:50] + "...") # 프롬프트의 처음 50자만 표시
143
+ gr.Button("Use this prompt").click(
144
+ fn=use_prompt,
145
+ inputs=[],
146
+ outputs=input_text,
147
+ api_name=False
148
+ ).then(
149
+ lambda x=prompt: x,
150
+ inputs=[],
151
+ outputs=input_text
152
+ )
 
153
 
154
+ with gr.Tab("Gallery"):
155
+ gallery = gr.Gallery(
156
+ label="Generated Images",
157
+ show_label=False,
158
+ elem_id="gallery",
159
+ columns=[5],
160
+ rows=[3],
161
+ object_fit="contain",
162
+ height="auto"
163
+ )
164
+ refresh_btn = gr.Button("Refresh Gallery")
165
+
166
+ def update_gallery():
167
+ return load_gallery()
168
+
169
+ refresh_btn.click(fn=update_gallery, inputs=None, outputs=gallery)
170
+ demo.load(fn=update_gallery, inputs=None, outputs=gallery)
171
+
172
  input_text.submit(
173
  fn=respond,
174
  inputs=[input_text, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
175
  outputs=output_image
176
+ ).then(
177
+ fn=update_gallery,
178
+ inputs=None,
179
+ outputs=gallery
180
  )
181
 
182
  if __name__ == "__main__":