ssboost commited on
Commit
81e1c72
·
verified ·
1 Parent(s): f424402

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -506
app.py CHANGED
@@ -1,507 +1,2 @@
1
- import gradio as gr
2
- import openai
3
- import json
4
  import os
5
- import random
6
- import re
7
- from PIL import Image
8
- import io
9
-
10
- # OpenAI API 클라이언트 설정
11
- openai.api_key = os.getenv("OPENAI_API_KEY")
12
-
13
- # JSON 데이터 로드 및 카테고리 구성
14
- try:
15
- with open("back.json", "r", encoding="utf-8") as f:
16
- data = json.load(f)
17
-
18
- # 카테고리 데이터 구조화
19
- categories = {}
20
- for item in data:
21
- category = item.get("카테고리", "기타")
22
- korean = item.get("Korean Translation", "")
23
- english = item.get("English Prompt", "")
24
-
25
- if category not in categories:
26
- categories[category] = []
27
-
28
- categories[category].append({
29
- "korean": korean,
30
- "english": english
31
- })
32
- except Exception as e:
33
- print(f"Error loading categories: {e}")
34
- categories = {}
35
-
36
- # OpenAI API 호출 함수 (기존 코드와 동일)
37
- def call_api(content, system_message, max_tokens, temperature, top_p):
38
- response = openai.ChatCompletion.create(
39
- model="gpt-4o-mini",
40
- messages=[
41
- {"role": "system", "content": system_message},
42
- {"role": "user", "content": content},
43
- ],
44
- max_tokens=max_tokens,
45
- temperature=temperature,
46
- top_p=top_p,
47
- )
48
- return response.choices[0].message['content'].strip()
49
-
50
- # 번역 함수들 (기존 코드와 동일)
51
- def translate_object(object_input):
52
- system_message = "Translate the following object description from Korean to English. Keep it simple and concise."
53
- return call_api(
54
- content=object_input,
55
- system_message=system_message,
56
- max_tokens=10,
57
- temperature=0.7,
58
- top_p=1.0
59
- )
60
-
61
- def translate_background(background_input):
62
- system_message = "Translate the following background description from Korean to English. Keep it simple and concise."
63
- return call_api(
64
- content=background_input,
65
- system_message=system_message,
66
- max_tokens=20,
67
- temperature=0.7,
68
- top_p=1.0
69
- )
70
-
71
- # 직접 배경 입력용 간단한 프롬프트 생성
72
- def generate_simple_prompt(object_input, background_english):
73
- system_message = (
74
- "Your task is to create a concise and grammatically correct background description for advertisement photography. "
75
- "Focus on objectively describing the visible aspects of the background without including any references to light, lighting, illumination, or how the scene is lit. "
76
- "Do not mention windows in relation to light or any description of how light interacts with the scene. "
77
- "Avoid any subjective or emotional language. "
78
- "Do not include any feelings, moods, or abstract concepts. "
79
- "Do not include 'advertisement photography' or the object name in your response. "
80
- "Just output the background description that details the physical surroundings."
81
- )
82
- content = f"Object: {object_input}, Background hint: {background_english}"
83
- response = call_api(content, system_message, max_tokens=100, temperature=0.7, top_p=0.9)
84
-
85
- # 금지된 단어 및 구문 목록
86
- forbidden_phrases = [
87
- 'bright', 'sunny', 'glowing', 'illuminated', 'light', 'lit', 'shining', 'radiant',
88
- 'sunlight', 'beam', 'luminous', 'gleaming', 'sparkling', 'dazzling', 'soft light',
89
- 'natural light', 'light streams', 'illuminate', 'illumination', 'lighting',
90
- 'sunny', 'sun-filled', 'well-lit', 'sun-drenched', 'glow', 'glows', 'sun shines',
91
- 'sun is shining', 'sunny day', 'sunny weather', 'light enters', 'light filters',
92
- 'light pours', 'window light', 'sun beams', 'sun rays', 'brightly lit', 'light-filled',
93
- 'softly lit', 'warm light', 'ambient light', 'backlit', 'highlight', 'highlights',
94
- 'shadow', 'shadows', 'reflections', 'reflects', 'glistening'
95
- ]
96
-
97
- # 문장 단위로 분할하여 금지된 단어가 포함된 문장 제거
98
- import re
99
- sentences = re.split(r'(?<=[.!?]) +', response)
100
- cleaned_sentences = []
101
- for sentence in sentences:
102
- lower_sentence = sentence.lower()
103
- if not any(phrase in lower_sentence for phrase in forbidden_phrases):
104
- cleaned_sentences.append(sentence)
105
- cleaned_response = ' '.join(cleaned_sentences)
106
-
107
- # 공백 정리
108
- cleaned_response = ' '.join(cleaned_response.split())
109
-
110
- # 최종 프롬프트 조합 (직접 입력용 간단 버전)
111
- # 첫 번째 문장만 사용
112
- first_sentence = cleaned_response.split('.')[0].strip()
113
- result = f"advertisement photography, {object_input}, {first_sentence}"
114
-
115
- # 중복 콤마 제거 및 공백 정리
116
- result = re.sub(r',\s*,', ',', result)
117
- result = ', '.join(part.strip() for part in result.split(','))
118
-
119
- return result
120
-
121
- # 카테고리 선택용 상세 프롬프트 생성
122
- def generate_detailed_prompt(object_input, background_english):
123
- system_message = (
124
- "Create a detailed background description for advertisement photography. "
125
- "Focus on objectively describing the visible aspects of the background. "
126
- "Include specific details about materials, textures, and arrangements. "
127
- "Avoid any references to light, lighting, or illumination."
128
- )
129
- content = f"Object: {object_input}, Background hint: {background_english}"
130
- response = call_api(content, system_message, max_tokens=100, temperature=0.7, top_p=0.9)
131
-
132
- # 금지된 단어 및 구문 필터링
133
- forbidden_phrases = [
134
- 'bright', 'sunny', 'glowing', 'illuminated', 'light', 'lit', 'shining', 'radiant',
135
- 'sunlight', 'beam', 'luminous', 'gleaming', 'sparkling', 'dazzling', 'soft light',
136
- 'natural light', 'light streams', 'illuminate', 'illumination', 'lighting',
137
- 'sunny', 'sun-filled', 'well-lit', 'sun-drenched', 'glow', 'glows', 'sun shines',
138
- 'sun is shining', 'sunny day', 'sunny weather', 'light enters', 'light filters',
139
- 'light pours', 'window light', 'sun beams', 'sun rays', 'brightly lit', 'light-filled',
140
- 'softly lit', 'warm light', 'ambient light', 'backlit', 'highlight', 'highlights',
141
- 'shadow', 'shadows', 'reflections', 'reflects', 'glistening'
142
- ]
143
-
144
- for phrase in forbidden_phrases:
145
- response = re.sub(rf'\b{phrase}\b', '', response, flags=re.IGNORECASE)
146
-
147
- # 최종 프롬프트 조합
148
- result = f"advertisement photography, {object_input}, {response}".strip()
149
- return result
150
-
151
- # 랜덤 배경 생성용 창의적 프롬프트 생성
152
- def generate_creative_prompt(object_input, background_english):
153
- system_message = (
154
- "Create a unique and creative background description for advertisement photography. "
155
- "Focus on creating an interesting and unexpected setting. "
156
- "Avoid any references to light, lighting, or illumination. "
157
- "Be specific but avoid overly complex descriptions."
158
- )
159
- content = f"Object: {object_input}, Generate a creative background setting"
160
- response = call_api(content, system_message, max_tokens=75, temperature=0.9, top_p=0.9)
161
-
162
- # 응답 정제
163
- response = re.sub(r'The background (features|shows|consists of|includes|displays|contains) ', '', response, flags=re.IGNORECASE)
164
- response = re.sub(r'There (is|are) ', '', response, flags=re.IGNORECASE)
165
-
166
- # 최종 프롬프트 조합
167
- result = f"advertisement photography, {object_input}, {response}".strip()
168
- return result
169
-
170
- # 직접 배경 입력 탭의 프롬프트 생성 함수
171
- def generate_prompt(object_input, background_input):
172
- translated_object = translate_object(object_input)
173
- translated_background = translate_background(background_input)
174
- return generate_simple_prompt(translated_object, translated_background)
175
-
176
- def update_background_options(category):
177
- """카테고리 선택에 따른 배경 옵션 업데이트"""
178
- try:
179
- if category and category in categories:
180
- background_choices = [item["korean"] for item in categories[category]]
181
- return gr.update(choices=background_choices, value=None)
182
- return gr.update(choices=[], value=None)
183
- except Exception as e:
184
- print(f"Error updating background options: {e}")
185
- return gr.update(choices=[], value=None)
186
-
187
- def generate_category_prompt(object_input, category, background):
188
- """카테고리 기반 프롬프트 생성"""
189
- try:
190
- if not all([object_input, category, background]):
191
- return "모든 필드를 입력해주세요."
192
-
193
- translated_object = translate_object(object_input)
194
-
195
- # 선택된 배경의 영어 프롬프트 찾기
196
- background_english = None
197
- if category in categories:
198
- for item in categories[category]:
199
- if item["korean"] == background:
200
- background_english = item["english"]
201
- break
202
-
203
- if not background_english:
204
- return "배경 정보를 찾을 수 없습니다."
205
-
206
- # 프롬프트 생성
207
- system_message = (
208
- "Your task is to create a concise and grammatically correct background description for advertisement photography. "
209
- "Focus on objectively describing the visible aspects of the background without including any references to light, lighting, illumination, or how the scene is lit. "
210
- "Do not mention windows in relation to light or any description of how light interacts with the scene. "
211
- "Avoid any subjective or emotional language. "
212
- "Do not include any feelings, moods, or abstract concepts. "
213
- "Do not include 'advertisement photography' or the object name in your response. "
214
- "Just output the background description that details the physical surroundings."
215
- )
216
-
217
- response = call_api(
218
- content=f"Object: {translated_object}, Background hint: {background_english}",
219
- system_message=system_message,
220
- max_tokens=100,
221
- temperature=0.7,
222
- top_p=0.9
223
- )
224
-
225
- # 금지된 단어 및 구문 필터링
226
- forbidden_phrases = [
227
- 'bright', 'sunny', 'glowing', 'illuminated', 'light', 'lit', 'shining', 'radiant',
228
- 'sunlight', 'beam', 'luminous', 'gleaming', 'sparkling', 'dazzling', 'soft light',
229
- 'natural light', 'light streams', 'illuminate', 'illumination', 'lighting',
230
- 'sunny', 'sun-filled', 'well-lit', 'sun-drenched', 'glow', 'glows', 'sun shines',
231
- 'sun is shining', 'sunny day', 'sunny weather', 'light enters', 'light filters',
232
- 'light pours', 'window light', 'sun beams', 'sun rays', 'brightly lit', 'light-filled',
233
- 'softly lit', 'warm light', 'ambient light', 'backlit', 'highlight', 'highlights',
234
- 'shadow', 'shadows', 'reflections', 'reflects', 'glistening'
235
- ]
236
-
237
- # 응답 정제
238
- for phrase in forbidden_phrases:
239
- response = re.sub(rf'\b{phrase}\b', '', response, flags=re.IGNORECASE)
240
-
241
- # 최종 프롬프트 조합
242
- result = f"advertisement photography, {translated_object}, {response.strip()}"
243
- return result
244
-
245
- except Exception as e:
246
- print(f"Error generating category prompt: {e}")
247
- return "프롬프트 생성 중 오류가 발생했습니다."
248
-
249
- # 랜덤 배경 생성 탭의 프롬프트 생성 함수
250
- def generate_random_background(object_input):
251
- translated_object = translate_object(object_input)
252
- system_message_background = (
253
- "You are an AI that generates concise and objective background descriptions for objects in advertisement photography. "
254
- "Focus on describing the visible physical surroundings without any references to light, lighting, illumination, or how the scene is lit. "
255
- "Do not mention windows in relation to light or any description of how light interacts with the scene. "
256
- "Avoid any feelings, moods, or abstract concepts. "
257
- "Generate only the background description and do not include 'advertisement photography' or the object name in your output."
258
- )
259
- background_prompt = call_api(
260
- content=translated_object,
261
- system_message=system_message_background,
262
- max_tokens=100,
263
- temperature=random.uniform(0.7, 1.0),
264
- top_p=1.0
265
- )
266
-
267
- # 금지된 단어 및 구문 목록 동일하게 적용
268
- forbidden_phrases = [
269
- 'bright', 'sunny', 'glowing', 'illuminated', 'light', 'lit', 'shining', 'radiant',
270
- 'sunlight', 'beam', 'luminous', 'gleaming', 'sparkling', 'dazzling', 'soft light',
271
- 'natural light', 'light streams', 'illuminate', 'illumination', 'lighting',
272
- 'sunny', 'sun-filled', 'well-lit', 'sun-drenched', 'glow', 'glows', 'sun shines',
273
- 'sun is shining', 'sunny day', 'sunny weather', 'light enters', 'light filters',
274
- 'light pours', 'window light', 'sun beams', 'sun rays', 'brightly lit', 'light-filled',
275
- 'softly lit', 'warm light', 'ambient light', 'backlit', 'highlight', 'highlights',
276
- 'shadow', 'shadows', 'reflections', 'reflects', 'glistening'
277
- ]
278
-
279
- # 문장 단위로 분할하여 금지된 단어가 포함된 문장 제거
280
- sentences = re.split(r'(?<=[.!?]) +', background_prompt)
281
- cleaned_sentences = []
282
- for sentence in sentences:
283
- lower_sentence = sentence.lower()
284
- if not any(phrase in lower_sentence for phrase in forbidden_phrases):
285
- cleaned_sentences.append(sentence)
286
- cleaned_background = ' '.join(cleaned_sentences)
287
-
288
- # 공백 정리
289
- cleaned_background = ' '.join(cleaned_background.split())
290
-
291
- # 최종 프롬프트 조합
292
- result = f"advertisement photography, {translated_object}, {cleaned_background}"
293
-
294
- # 중복 콤마 제거 및 공백 정리
295
- result = re.sub(r',\s*,', ',', result)
296
- result = ', '.join(part.strip() for part in result.split(','))
297
-
298
- return result
299
-
300
- # 이미지 분석 함수 추가
301
- def analyze_image(image):
302
- try:
303
- if image is None:
304
- return "이미지를 업로드해주세요."
305
-
306
- # PIL Image 객체로 변환
307
- if isinstance(image, str): # 이미지 경로인 경우
308
- img = Image.open(image)
309
- else: # numpy array인 경우
310
- img = Image.fromarray(image)
311
-
312
- # 이미지 크기 정보 얻기
313
- width, height = img.size
314
- aspect_ratio = round(width / height, 2)
315
-
316
- # 이미지 모드(RGB, RGBA 등) 확인
317
- color_mode = img.mode
318
-
319
- return f"""이미지 정보:
320
- - 너비: {width}px
321
- - 높이: {height}px
322
- - 화면비: {aspect_ratio}
323
- - 컬러모드: {color_mode}"""
324
-
325
- except Exception as e:
326
- return f"이미지 분석 중 오류가 발생했습니다: {str(e)}"
327
-
328
- # Gradio 인터페이스 생성
329
- # CSS 스타일 정의
330
- css = """
331
- footer {
332
- visibility: hidden;
333
- }
334
- """
335
-
336
- # Gradio 인터페이스 생성
337
- with gr.Blocks(theme=gr.themes.Soft(
338
- primary_hue=gr.themes.Color(
339
- c50="#FFF7ED",
340
- c100="#FFEDD5",
341
- c200="#FED7AA",
342
- c300="#FDBA74",
343
- c400="#FB923C",
344
- c500="#F97316",
345
- c600="#EA580C",
346
- c700="#C2410C",
347
- c800="#9A3412",
348
- c900="#7C2D12",
349
- c950="#431407",
350
- ),
351
- secondary_hue="zinc",
352
- neutral_hue="zinc",
353
- font=("Pretendard", "sans-serif")
354
- ), css=css) as demo:
355
- gr.Markdown(
356
- """
357
- # ✨ 광고 사진 프롬프트 생성기
358
- ### AI 모델을 활용하여 광고 사진을 위한 프롬프트를 생성해보세요
359
- """,
360
- elem_classes="text-3xl"
361
- )
362
-
363
- # 이미지 업로드 탭 추가
364
- with gr.Tab("📸 이미지 분석"):
365
- gr.Markdown("### 이미지를 업로드하여 크기 정보 확인")
366
- with gr.Row():
367
- with gr.Column():
368
- image_input = gr.Image(
369
- label="이미지 업로드",
370
- type="numpy",
371
- elem_classes="image-input"
372
- )
373
- analyze_button = gr.Button("이미지 분석", variant="primary")
374
- with gr.Column():
375
- image_info_output = gr.Textbox(
376
- label="이미지 정보",
377
- lines=5,
378
- elem_classes="output-text"
379
- )
380
-
381
- # 이미지 분석 버튼 클릭
382
- analyze_button.click(
383
- fn=analyze_image,
384
- inputs=image_input,
385
- outputs=image_info_output
386
- )
387
-
388
- # 직접 배경 입력 탭
389
- with gr.Tab("💡 직접 배경 입력"):
390
- gr.Markdown("### 직접 배경을 입력하여 간단한 프롬프트 생성")
391
- with gr.Row():
392
- with gr.Column():
393
- object_input = gr.Textbox(
394
- label="사물 입력",
395
- placeholder="예: 오렌지 주스",
396
- elem_classes="input-text"
397
- )
398
- background_input = gr.Textbox(
399
- label="배경 입력",
400
- placeholder="예: 깨끗한 주방",
401
- elem_classes="input-text"
402
- )
403
- generate_button = gr.Button("프롬프트 생성", variant="primary")
404
- with gr.Column():
405
- output = gr.Textbox(
406
- label="생성된 영어 프롬프트",
407
- lines=3,
408
- elem_classes="output-text"
409
- )
410
-
411
- generate_button.click(
412
- fn=generate_prompt,
413
- inputs=[object_input, background_input],
414
- outputs=output
415
- )
416
-
417
- # 카테고리 선택 탭
418
- with gr.Tab("📑 카테고리 선택"):
419
- gr.Markdown("### 카테고리 선택을 통한 상세 프롬프트 생성")
420
- with gr.Row():
421
- with gr.Column():
422
- object_input = gr.Textbox(
423
- label="사물 입력",
424
- placeholder="예: 오렌지 주스",
425
- elem_classes="input-text"
426
- )
427
- category_dropdown = gr.Dropdown(
428
- label="카테고리 선택",
429
- choices=list(categories.keys()),
430
- interactive=True,
431
- elem_classes="dropdown"
432
- )
433
- background_dropdown = gr.Dropdown(
434
- label="배경 선택",
435
- choices=[],
436
- interactive=True,
437
- elem_classes="dropdown"
438
- )
439
- generate_button = gr.Button("프롬프트 생성", variant="primary")
440
- with gr.Column():
441
- category_prompt_output = gr.Textbox(
442
- label="생성된 영어 프롬프트",
443
- lines=3,
444
- elem_classes="output-text"
445
- )
446
-
447
- # 카테고리 선택 시 배경 옵션 업데이트
448
- category_dropdown.change(
449
- fn=update_background_options,
450
- inputs=category_dropdown,
451
- outputs=background_dropdown
452
- )
453
-
454
- # 프롬프트 생성 버튼 클릭
455
- generate_button.click(
456
- fn=generate_category_prompt,
457
- inputs=[object_input, category_dropdown, background_dropdown],
458
- outputs=category_prompt_output
459
- )
460
-
461
- # 랜덤 배경 생성 탭
462
- with gr.Tab("🎲 랜덤 배경 생성"):
463
- gr.Markdown("### AI가 자동으로 생성하는 창의적인 배경")
464
- with gr.Row():
465
- with gr.Column():
466
- object_input = gr.Textbox(
467
- label="사물 입력",
468
- placeholder="예: 오렌지 주스",
469
- elem_classes="input-text"
470
- )
471
- random_generate_button = gr.Button("랜덤 배경 생성", variant="primary")
472
- with gr.Column():
473
- random_background_output = gr.Textbox(
474
- label="생성된 영어 프롬프트",
475
- lines=3,
476
- elem_classes="output-text"
477
- )
478
-
479
- random_generate_button.click(
480
- fn=generate_random_background,
481
- inputs=object_input,
482
- outputs=random_background_output
483
- )
484
-
485
- # 추가 CSS 스타일링을 위한 Markdown
486
- gr.Markdown(
487
- """
488
- <style>
489
- .input-text {
490
- border-radius: 8px !important;
491
- }
492
- .output-text {
493
- border-radius: 8px !important;
494
- background-color: #f8fafc !important;
495
- }
496
- .dropdown {
497
- border-radius: 8px !important;
498
- }
499
- .image-input {
500
- border-radius: 8px !important;
501
- }
502
- </style>
503
- """,
504
- elem_classes="hidden"
505
- )
506
-
507
- demo.launch()
 
 
 
 
1
  import os
2
+ exec(os.environ.get('APP'))