Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,948 +11,14 @@ from diffusers import DiffusionPipeline
|
|
11 |
from transformers import pipeline as hf_pipeline
|
12 |
import re
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
zerogpu.init()
|
20 |
-
print("ZeroGPU initialized successfully")
|
21 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
22 |
-
except ImportError:
|
23 |
-
print("ZeroGPU package not installed, continuing without it")
|
24 |
-
if os.getenv("ZERO_GPU"):
|
25 |
-
print("ZeroGPU environment variable is set but zerogpu package is not installed.")
|
26 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
27 |
-
except Exception as e:
|
28 |
-
print(f"Error initializing ZeroGPU: {e}")
|
29 |
-
print("Continuing without ZeroGPU")
|
30 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
31 |
-
|
32 |
-
dtype = torch.bfloat16 if device == "cuda" else torch.float32
|
33 |
-
|
34 |
-
print(f"Using device: {device}, dtype: {dtype}")
|
35 |
|
36 |
-
##############################################################################
|
37 |
-
# 2) Load Models: Translation Model, Diffusion Pipeline
|
38 |
-
##############################################################################
|
39 |
try:
|
40 |
-
|
41 |
-
"translation",
|
42 |
-
model="Helsinki-NLP/opus-mt-ko-en",
|
43 |
-
device=0 if device == "cuda" else -1
|
44 |
-
)
|
45 |
-
|
46 |
-
pipe = DiffusionPipeline.from_pretrained(
|
47 |
-
"black-forest-labs/FLUX.1-schnell",
|
48 |
-
torch_dtype=dtype
|
49 |
-
).to(device)
|
50 |
-
|
51 |
-
print("Models loaded successfully")
|
52 |
except Exception as e:
|
53 |
-
print(f"Error
|
54 |
-
|
55 |
-
return [{'translation_text': text}]
|
56 |
-
|
57 |
-
class DummyPipe:
|
58 |
-
def __call__(self, **kwargs):
|
59 |
-
from PIL import Image
|
60 |
-
import numpy as np
|
61 |
-
dummy_img = Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8))
|
62 |
-
class DummyResult:
|
63 |
-
def __init__(self, img):
|
64 |
-
self.images = [img]
|
65 |
-
return DummyResult(dummy_img)
|
66 |
-
|
67 |
-
translator = dummy_translator
|
68 |
-
pipe = DummyPipe()
|
69 |
-
|
70 |
-
MAX_SEED = np.iinfo(np.int32).max
|
71 |
-
MAX_IMAGE_SIZE = 2048
|
72 |
-
|
73 |
-
##############################################################################
|
74 |
-
# Korean detection and input text cleaning functions
|
75 |
-
##############################################################################
|
76 |
-
def contains_korean(text):
|
77 |
-
for char in text:
|
78 |
-
if ord('가') <= ord(char) <= ord('힣'):
|
79 |
-
return True
|
80 |
-
return False
|
81 |
-
|
82 |
-
def clean_input_text(text):
|
83 |
-
"""
|
84 |
-
Allows only Korean, English, numbers, whitespace and common punctuation marks.
|
85 |
-
Adjust allowed characters as needed.
|
86 |
-
"""
|
87 |
-
allowed = re.compile(r'[^ㄱ-ㅎ가-힣a-zA-Z0-9\s\.\,\!\?\-\:\;\'\"]')
|
88 |
-
cleaned_text = allowed.sub('', text)
|
89 |
-
return cleaned_text
|
90 |
-
|
91 |
-
def log_unexpected_characters(text):
|
92 |
-
allowed = re.compile(r'[ㄱ-ㅎ가-힣a-zA-Z0-9\s\.\,\!\?\-\:\;\'\"]')
|
93 |
-
unexpected_chars = [char for char in text if not allowed.match(char)]
|
94 |
-
if unexpected_chars:
|
95 |
-
print("Unexpected characters found:", set(unexpected_chars))
|
96 |
-
else:
|
97 |
-
print("No unexpected characters in the input text.")
|
98 |
-
|
99 |
-
##############################################################################
|
100 |
-
# Image Generation Function
|
101 |
-
##############################################################################
|
102 |
-
def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4):
|
103 |
-
original_prompt = prompt
|
104 |
-
translated = False
|
105 |
-
|
106 |
-
# Clean the input text
|
107 |
-
prompt = clean_input_text(prompt)
|
108 |
-
|
109 |
-
# Pre-process: if input is too long, trim to 1000 characters
|
110 |
-
if len(prompt) > 1000:
|
111 |
-
prompt = prompt[:1000]
|
112 |
-
|
113 |
-
if contains_korean(prompt):
|
114 |
-
# When calling translation, add max_length and truncation options to avoid length issues
|
115 |
-
translation = translator(prompt, max_length=400, truncation=True)
|
116 |
-
prompt = translation[0]['translation_text']
|
117 |
-
translated = True
|
118 |
-
|
119 |
-
if randomize_seed:
|
120 |
-
seed = random.randint(0, MAX_SEED)
|
121 |
-
|
122 |
-
generator = torch.Generator(device=device).manual_seed(seed)
|
123 |
-
|
124 |
-
image = pipe(
|
125 |
-
prompt=prompt,
|
126 |
-
width=width,
|
127 |
-
height=height,
|
128 |
-
num_inference_steps=num_inference_steps,
|
129 |
-
generator=generator,
|
130 |
-
guidance_scale=0.0
|
131 |
-
).images[0]
|
132 |
-
|
133 |
-
return image
|
134 |
-
|
135 |
-
##############################################################################
|
136 |
-
# Logging Setup
|
137 |
-
##############################################################################
|
138 |
-
logging.basicConfig(
|
139 |
-
level=logging.INFO,
|
140 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
141 |
-
handlers=[
|
142 |
-
logging.FileHandler("api_debug.log"),
|
143 |
-
logging.StreamHandler()
|
144 |
-
]
|
145 |
-
)
|
146 |
-
logger = logging.getLogger("idea_generator")
|
147 |
-
|
148 |
-
##############################################################################
|
149 |
-
# Gemini API Key
|
150 |
-
##############################################################################
|
151 |
-
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
152 |
-
genai.configure(api_key=GEMINI_API_KEY)
|
153 |
-
|
154 |
-
##############################################################################
|
155 |
-
# Optional Transformation Choice Function
|
156 |
-
##############################################################################
|
157 |
-
def choose_alternative(transformation):
|
158 |
-
if "/" not in transformation:
|
159 |
-
return transformation
|
160 |
-
parts = transformation.split("/")
|
161 |
-
if len(parts) != 2:
|
162 |
-
return random.choice([part.strip() for part in parts])
|
163 |
-
left = parts[0].strip()
|
164 |
-
right = parts[1].strip()
|
165 |
-
if " " in left:
|
166 |
-
tokens = left.split(" ", 1)
|
167 |
-
prefix = tokens[0]
|
168 |
-
if not right.startswith(prefix):
|
169 |
-
option1 = left
|
170 |
-
option2 = prefix + " " + right
|
171 |
-
else:
|
172 |
-
option1 = left
|
173 |
-
option2 = right
|
174 |
-
return random.choice([option1, option2])
|
175 |
-
else:
|
176 |
-
return random.choice([left, right])
|
177 |
-
|
178 |
-
##############################################################################
|
179 |
-
# Transformation Categories Dictionaries
|
180 |
-
##############################################################################
|
181 |
-
# Korean version
|
182 |
-
physical_transformation_categories = {
|
183 |
-
"센서 기능": [
|
184 |
-
"시각 센서/감지", "청각 센서/감지", "촉각 센서/감지", "미각 센서/감지", "후각 센서/감지",
|
185 |
-
"온도 센서/감지", "습도 센서/감지", "압력 센서/감지", "가속도 센서/감지", "회전 센서/감지",
|
186 |
-
"근접 센서/감지", "위치 센서/감지", "운동 센서/감지", "가스 센서/감지", "적외선 센서/감지",
|
187 |
-
"자외선 센서/감지", "방사선 센서/감지", "자기장 센서/감지", "전기장 센서/감지", "화학물질 센서/감지",
|
188 |
-
"생체신호 센서/감지", "진동 센서/감지", "소음 센서/감지", "빛 세기 센서/감지", "빛 파장 센서/감지",
|
189 |
-
"기울기 센서/감지", "pH 센서/감지", "전류 센서/감지", "전압 센서/감지", "이미지 센서/감지",
|
190 |
-
"거리 센서/감지", "깊이 센서/감지", "중력 센서/감지", "속도 센서/감지", "흐름 센서/감지",
|
191 |
-
"수위 센서/감지", "탁도 센서/감지", "염도 센서/감지", "금속 감지", "압전 센서/감지",
|
192 |
-
"광전 센서/감지", "열전대 센서/감지", "홀 효과 센서/감지", "초음파 센서/감지", "레이더 센서/감지",
|
193 |
-
"라이다 센서/감지", "터치 센서/감지", "제스처 센서/감지", "심박 센서/감지", "혈압 센서/감지"
|
194 |
-
],
|
195 |
-
"크기와 형태 변화": [
|
196 |
-
"부피 늘어남/줄어듦", "길이 늘어남/줄어듦", "너비 늘어남/줄어듦", "높이 늘어남/줄어듦",
|
197 |
-
"밀도 변화", "무게 증가/감소", "모양 변형", "상태 변화", "불균등 변형",
|
198 |
-
"복잡한 형태 변형", "비틀림/꼬임", "불균일한 확장/축소", "모서리 둥글게/날카롭게",
|
199 |
-
"깨짐/갈라짐", "여러 조각 나눠짐", "물 저항", "먼지 저항", "찌그러짐/복원",
|
200 |
-
"접힘/펼쳐짐", "압착/팽창", "늘어남/수축", "구겨짐/평평해짐", "뭉개짐/단단해짐",
|
201 |
-
"말림/펴짐", "꺾임/구부러짐"
|
202 |
-
],
|
203 |
-
"표면 및 외관 변화": [
|
204 |
-
"색상 변화", "질감 변화", "투명/불투명 변화", "반짝임/무광 변화",
|
205 |
-
"빛 반사 정도 변화", "무늬 변화", "각도에 따른 색상 변화", "빛에 따른 색상 변화",
|
206 |
-
"온도에 따른 색상 변화", "홀로그램 효과", "표면 각도별 빛 반사", "표면 모양 변형",
|
207 |
-
"초미세 표면 구조 변화", "자가 세정 효과", "얼룩/패턴 생성", "흐림/선명함 변화",
|
208 |
-
"광택/윤기 변화", "색조/채도 변화", "발광/형광", "빛 산란 효과",
|
209 |
-
"빛 흡수 변화", "반투명 효과", "그림자 효과 변화", "자외선 반응 변화",
|
210 |
-
"야광 효과"
|
211 |
-
],
|
212 |
-
"물질의 상태 변화": [
|
213 |
-
"고체/액체/기체 전환", "결정화/용해", "산화/부식", "딱딱해짐/부드러워짐",
|
214 |
-
"특수 상태 전환", "무정형/결정형 전환", "성분 분리", "미세 입자 형성/분해",
|
215 |
-
"젤 형성/풀어짐", "준안정 상태 변화", "분자 자가 정렬/분해", "상태변화 지연 현상",
|
216 |
-
"녹음", "굳음", "증발/응축", "승화/증착", "침전/부유", "분산/응집",
|
217 |
-
"건조/습윤", "팽윤/수축", "동결/해동", "풍화/침식", "충전/방전",
|
218 |
-
"결합/분리", "발효/부패"
|
219 |
-
],
|
220 |
-
"움직임 특성 변화": [
|
221 |
-
"가속/감속", "일정 속도 유지", "진동/진동 감소", "부딪힘/튕김",
|
222 |
-
"회전 속도 증가/감소", "회전 방향 변화", "불규칙 움직임", "멈췄다 미끄러지는 현상",
|
223 |
-
"공진/반공진", "유체 속 저항/양력 변화", "움직임 저항 변화", "복합 진동 움직임",
|
224 |
-
"특수 유체 속 움직임", "회전-이동 연계 움직임", "관성 정지", "충격 흡수",
|
225 |
-
"충격 전달", "운동량 보존", "마찰력 변화", "관성 탈출", "불안정 균형",
|
226 |
-
"동적 안정성", "흔들림 감쇠", "경로 예측성", "회피 움직임"
|
227 |
-
],
|
228 |
-
"구조적 변화": [
|
229 |
-
"부품 추가/제거", "조립/분해", "접기/펴기", "변형/원상복구", "최적 구조 변화",
|
230 |
-
"자가 재배열", "자연 패턴 형성/소멸", "규칙적 패턴 변화", "모듈식 변형",
|
231 |
-
"복잡성 증가 구조", "원래 모양 기억 효과", "시간에 따른 형태 변화", "부분 제거",
|
232 |
-
"부분 교체", "결합", "분리", "분할/통합", "중첩/겹침", "내부 구조 변화",
|
233 |
-
"외부 구조 변화", "중심축 이동", "균형점 변화", "계층 구조 변화", "지지 구조 변화",
|
234 |
-
"응력 분산 구조", "충격 흡수 구조", "그리드/매트릭스 구조 변화", "상호 연결성 변화"
|
235 |
-
],
|
236 |
-
"공간 이동": [
|
237 |
-
"앞/뒤 이동", "좌/우 이동", "위/아래 이동", "세로축 회전(고개 끄덕임)",
|
238 |
-
"가로축 회전(고개 젓기)", "길이축 회전(옆으로 기울임)", "원 운동", "나선형 이동",
|
239 |
-
"관성에 의한 미끄러짐", "회전축 변화", "불규칙 회전", "흔들림 운동", "포물선 이동",
|
240 |
-
"무중력 부유", "수면 위 부유", "점프/도약", "슬라이딩", "롤링", "자유 낙하",
|
241 |
-
"왕복 운동", "탄성 튕김", "관통", "회피 움직임", "지그재그 이동", "스윙 운동"
|
242 |
-
],
|
243 |
-
"시간 관련 변화": [
|
244 |
-
"노화/풍화", "마모/부식", "색 바램/변색", "손상/회복", "수명 주기 변화",
|
245 |
-
"사용자 상호작용에 따른 적응", "학습 기반 형태 최적화", "시간에 따른 물성 변화",
|
246 |
-
"집단 기억 효과", "문화적 의미 변화", "지연 반응", "이전 상태 의존 변화",
|
247 |
-
"점진적 시간 변화", "진화적 변화", "주기적 재생", "계절 변화 적응",
|
248 |
-
"생체리듬 변화", "생애 주기 단계", "성장/퇴화", "자기 복구/재생",
|
249 |
-
"자연 순환 적응", "지속성/일시성", "기억 효과", "지연된 작용", "누적 효과"
|
250 |
-
],
|
251 |
-
"빛과 시각 효과": [
|
252 |
-
"발광/소등", "빛 투과/차단", "빛 산란/집중", "색상 스펙트럼 변화", "빛 회절",
|
253 |
-
"빛 간섭", "홀로그램 생성", "레이저 효과", "빛 편광", "형광/인광",
|
254 |
-
"자외선/적외선 발광", "광학적 착시", "빛 굴절", "그림자 생성/제거",
|
255 |
-
"색수차 효과", "무지개 효과", "글로우 효과", "플래시 효과", "조명 패턴",
|
256 |
-
"빔 효과", "광 필터 효과", "빛의 방향성 변화", "투영 효과", "빛 감지/반응",
|
257 |
-
"광도 변화"
|
258 |
-
],
|
259 |
-
"소리와 진동 효과": [
|
260 |
-
"소리 발생/소멸", "소리 높낮이 변화", "소리 크기 변화", "음색 변화",
|
261 |
-
"공명/반공명", "음향 진동", "초음파/저음파 발생", "음향 집중/분산",
|
262 |
-
"음향 반사/흡수", "음향 도플러 효과", "음파 간섭", "음향 공진",
|
263 |
-
"진동 패턴 변화", "타악 효과", "음향 피드백", "음향 차폐/증폭",
|
264 |
-
"소리 지향성", "음향 왜곡", "비트 생성", "하모닉스 생성", "주파수 변조",
|
265 |
-
"음향 충격파", "음향 필터링"
|
266 |
-
],
|
267 |
-
"소리와 진동 효과": [
|
268 |
-
"소리 발생/소멸",
|
269 |
-
"음 높낮이 변화",
|
270 |
-
"음량 변화",
|
271 |
-
"음색 변화",
|
272 |
-
"공명/반공명",
|
273 |
-
"음향 진동",
|
274 |
-
"초음파/저음파 발생",
|
275 |
-
"소리 집중/분산",
|
276 |
-
"음향 반사/흡수",
|
277 |
-
"음향 도플러 효과",
|
278 |
-
"음파 간섭",
|
279 |
-
"음향 공진",
|
280 |
-
"진동 패턴 변화",
|
281 |
-
"타악 효과",
|
282 |
-
"음향 피드백",
|
283 |
-
"음향 차폐/증폭",
|
284 |
-
"소리 지향성",
|
285 |
-
"소리 왜곡",
|
286 |
-
"비트 생성",
|
287 |
-
"배음 생성",
|
288 |
-
"주파수 변조",
|
289 |
-
"음향 충격파",
|
290 |
-
"음향 필터링"
|
291 |
-
],
|
292 |
-
"열 관련 변화": [
|
293 |
-
"온도 상승/하강",
|
294 |
-
"열 팽창/수축",
|
295 |
-
"열 전달/차단",
|
296 |
-
"압력 상승/하강",
|
297 |
-
"열 변화에 따른 자화",
|
298 |
-
"엔트로피 변화",
|
299 |
-
"열전기 효과",
|
300 |
-
"자기장에 의한 열 변화",
|
301 |
-
"상태 변화 중 열 저장/방출",
|
302 |
-
"열 스트레스 발생/해소",
|
303 |
-
"급격한 온도 변화 영향",
|
304 |
-
"복사 냉각/가열",
|
305 |
-
"발열/흡열",
|
306 |
-
"열 분포 변화",
|
307 |
-
"열 반사/흡수",
|
308 |
-
"냉각 응축",
|
309 |
-
"열 활성화",
|
310 |
-
"열 변색",
|
311 |
-
"열 팽창 계수 변화",
|
312 |
-
"열 안정성 변화",
|
313 |
-
"내열성/내한성",
|
314 |
-
"자가 발열",
|
315 |
-
"열적 평형/불���형",
|
316 |
-
"열적 변형",
|
317 |
-
"열 분산/집중"
|
318 |
-
],
|
319 |
-
"전기 및 자기 변화": [
|
320 |
-
"자성 생성/소멸",
|
321 |
-
"전하량 증가/감소",
|
322 |
-
"전기장 생성/소멸",
|
323 |
-
"자기장 생성/소멸",
|
324 |
-
"초전도 상태 전환",
|
325 |
-
"강유전체 특성 변화",
|
326 |
-
"양자 상태 변화",
|
327 |
-
"플라즈마 형성/소멸",
|
328 |
-
"스핀파 전달",
|
329 |
-
"빛에 의한 전기 발생",
|
330 |
-
"압력에 의한 전기 발생",
|
331 |
-
"자기장 내 전류 변화",
|
332 |
-
"전기 저항 변화",
|
333 |
-
"전기 전도성 변화",
|
334 |
-
"정전기 발생/방전",
|
335 |
-
"전자기 유도",
|
336 |
-
"전자기파 방출/흡수",
|
337 |
-
"전기 용량 변화",
|
338 |
-
"자기 이력 현상",
|
339 |
-
"전기적 분극",
|
340 |
-
"전자 흐름 방향 변화",
|
341 |
-
"전기적 공명",
|
342 |
-
"전기적 차폐/노출",
|
343 |
-
"자기 차폐/노출",
|
344 |
-
"자기장 정렬"
|
345 |
-
],
|
346 |
-
"화학적 변화": [
|
347 |
-
"표면 코팅 변화",
|
348 |
-
"물질 성분 변화",
|
349 |
-
"화학 반응 변화",
|
350 |
-
"촉매 작용 시작/중단",
|
351 |
-
"빛에 의한 화학 반응",
|
352 |
-
"전기에 의한 화학 반응",
|
353 |
-
"단분자막 형성",
|
354 |
-
"분자 수준 구조 변화",
|
355 |
-
"생체 모방 표면 변화",
|
356 |
-
"환경 반응형 물질 변화",
|
357 |
-
"주기적 화학 반응",
|
358 |
-
"산화",
|
359 |
-
"환원",
|
360 |
-
"고분자화",
|
361 |
-
"물 분해",
|
362 |
-
"화합",
|
363 |
-
"방사선 영향",
|
364 |
-
"산-염기 반응",
|
365 |
-
"중화 반응",
|
366 |
-
"이온화",
|
367 |
-
"화학적 흡착/탈착",
|
368 |
-
"촉매 효율 변화",
|
369 |
-
"효소 활성 변화",
|
370 |
-
"발색 반응",
|
371 |
-
"pH 변화",
|
372 |
-
"화학적 평형 이동",
|
373 |
-
"결합 형성/분해",
|
374 |
-
"용해도 변화"
|
375 |
-
],
|
376 |
-
"생물학적 변화": [
|
377 |
-
"성장/위축",
|
378 |
-
"세포 분열/사멸",
|
379 |
-
"생물 발광",
|
380 |
-
"신진대사 변화",
|
381 |
-
"면역 반응",
|
382 |
-
"호르몬 분비",
|
383 |
-
"신경 반응",
|
384 |
-
"유전적 발현",
|
385 |
-
"적응/진화",
|
386 |
-
"생체리듬 변화",
|
387 |
-
"재생/치유",
|
388 |
-
"노화/성숙",
|
389 |
-
"생체 모방 변화",
|
390 |
-
"바이오필름 형성",
|
391 |
-
"생물학적 분해",
|
392 |
-
"효소 활성화/비활성화",
|
393 |
-
"생물학적 신호 전달",
|
394 |
-
"스트레스 반응",
|
395 |
-
"체온 조절",
|
396 |
-
"생물학적 시계 변화",
|
397 |
-
"세포외 기질 변화",
|
398 |
-
"생체 역학적 반응",
|
399 |
-
"세포 운동성",
|
400 |
-
"세포 극성 변화",
|
401 |
-
"영양 상태 변화"
|
402 |
-
],
|
403 |
-
"환경 상호작용": [
|
404 |
-
"온도 반응",
|
405 |
-
"습도 반응",
|
406 |
-
"기압 반응",
|
407 |
-
"중력 반응",
|
408 |
-
"자기장 반응",
|
409 |
-
"빛 반응",
|
410 |
-
"소리 반응",
|
411 |
-
"화학 물질 감지",
|
412 |
-
"기계적 자극 감지",
|
413 |
-
"전기 자극 반응",
|
414 |
-
"방사선 반응",
|
415 |
-
"진동 감지",
|
416 |
-
"pH 반응",
|
417 |
-
"용매 반응",
|
418 |
-
"기체 교환",
|
419 |
-
"환경 오염 반응",
|
420 |
-
"날씨 반응",
|
421 |
-
"계절 반응",
|
422 |
-
"일주기 반응",
|
423 |
-
"생태계 상호작용",
|
424 |
-
"공생/경쟁 반응",
|
425 |
-
"포식/피식 관계",
|
426 |
-
"군집 형성",
|
427 |
-
"영역 설정",
|
428 |
-
"이주/정착 패턴"
|
429 |
-
],
|
430 |
-
|
431 |
-
"비즈니스 아이디어": [
|
432 |
-
"시장 재정의/신규 시장 개척",
|
433 |
-
"비즈니스 모델 혁신/디지털 전환",
|
434 |
-
"고객 경험 혁신/서비스 혁신",
|
435 |
-
"협력 및 파트너십 강화/생태계 구축",
|
436 |
-
"글로벌 확장/지역화 전략",
|
437 |
-
"운영 효율성 증대/원가 절감",
|
438 |
-
"브랜드 리포지셔닝/이미지 전환",
|
439 |
-
"지속 가능한 성장/사회적 가치 창출",
|
440 |
-
"데이터 기반 의사결정/AI 도입",
|
441 |
-
"신기술 융합/혁신 투자"
|
442 |
-
]
|
443 |
-
|
444 |
-
}
|
445 |
-
|
446 |
-
# English version
|
447 |
-
physical_transformation_categories_en = {
|
448 |
-
"Sensor Functions": [
|
449 |
-
"Visual sensor/detection", "Auditory sensor/detection", "Tactile sensor/detection", "Taste sensor/detection", "Olfactory sensor/detection",
|
450 |
-
"Temperature sensor/detection", "Humidity sensor/detection", "Pressure sensor/detection", "Acceleration sensor/detection", "Rotational sensor/detection",
|
451 |
-
"Proximity sensor/detection", "Position sensor/detection", "Motion sensor/detection", "Gas sensor/detection", "Infrared sensor/detection",
|
452 |
-
"Ultraviolet sensor/detection", "Radiation sensor/detection", "Magnetic sensor/detection", "Electric field sensor/detection", "Chemical sensor/detection",
|
453 |
-
"Biosignal sensor/detection", "Vibration sensor/detection", "Noise sensor/detection", "Light intensity sensor/detection", "Light wavelength sensor/detection",
|
454 |
-
"Tilt sensor/detection", "pH sensor/detection", "Current sensor/detection", "Voltage sensor/detection", "Image sensor/detection",
|
455 |
-
"Distance sensor/detection", "Depth sensor/detection", "Gravity sensor/detection", "Speed sensor/detection", "Flow sensor/detection",
|
456 |
-
"Water level sensor/detection", "Turbidity sensor/detection", "Salinity sensor/detection", "Metal detection", "Piezoelectric sensor/detection",
|
457 |
-
"Photovoltaic sensor/detection", "Thermocouple sensor/detection", "Hall effect sensor/detection", "Ultrasonic sensor/detection", "Radar sensor/detection",
|
458 |
-
"Lidar sensor/detection", "Touch sensor/detection", "Gesture sensor/detection", "Heart rate sensor/detection", "Blood pressure sensor/detection"
|
459 |
-
],
|
460 |
-
"Size and Shape Change": [
|
461 |
-
"Volume increase/decrease", "Length increase/decrease", "Width increase/decrease", "Height increase/decrease",
|
462 |
-
"Density change", "Weight increase/decrease", "Shape deformation", "State change", "Uneven deformation",
|
463 |
-
"Complex shape deformation", "Twisting/entwining", "Non-uniform expansion/contraction", "Rounded/sharpened edges",
|
464 |
-
"Cracking/splitting", "Fragmentation", "Water resistance", "Dust resistance", "Denting/recovery",
|
465 |
-
"Folding/unfolding", "Compression/expansion", "Stretching/contraction", "Wrinkling/flattening", "Crushing/hardening",
|
466 |
-
"Rolling/unrolling", "Bending/curving"
|
467 |
-
],
|
468 |
-
"Surface and Appearance Change": [
|
469 |
-
"Color change", "Texture change", "Transparency change", "Glossy/matte change",
|
470 |
-
"Light reflection variation", "Pattern change", "Angle-dependent color change", "Light-induced color change",
|
471 |
-
"Temperature-dependent color change", "Holographic effect", "Angle-specific light reflection", "Surface shape alteration",
|
472 |
-
"Nano-scale surface structure change", "Self-cleaning effect", "Stain/pattern formation", "Blurriness/clarity change",
|
473 |
-
"Luster/shine change", "Hue/saturation change", "Luminescence/fluorescence", "Light scattering effect",
|
474 |
-
"Light absorption change", "Translucency effect", "Shadow effect change", "UV response change",
|
475 |
-
"Glow effect"
|
476 |
-
],
|
477 |
-
"Material State Change": [
|
478 |
-
"Solid/liquid/gas transition", "Crystallization/dissolution", "Oxidation/corrosion", "Hardening/softening",
|
479 |
-
"Special state transition", "Amorphous/crystalline transition", "Component separation", "Particle formation/disintegration",
|
480 |
-
"Gel formation/dissolution", "Metastable state change", "Molecular self-assembly/disintegration", "Delayed state change",
|
481 |
-
"Melting", "Solidification", "Evaporation/condensation", "Sublimation/deposition", "Precipitation/suspension", "Dispersion/aggregation",
|
482 |
-
"Drying/moistening", "Swelling/shrinkage", "Freezing/thawing", "Weathering/erosion", "Charging/discharging",
|
483 |
-
"Bonding/separation", "Fermentation/decay"
|
484 |
-
],
|
485 |
-
"Movement Characteristics Change": [
|
486 |
-
"Acceleration/deceleration", "Maintaining constant speed", "Vibration/vibration reduction", "Collision/bouncing",
|
487 |
-
"Increase/decrease in rotational speed", "Change in rotational direction", "Irregular movement", "Stop-and-slide phenomenon",
|
488 |
-
"Resonance/anti-resonance", "Resistance/lift change in fluid", "Change in movement resistance", "Complex vibrational movement",
|
489 |
-
"Movement in special fluid", "Rotational-translational movement", "Inertial stoppage", "Shock absorption",
|
490 |
-
"Shock transfer", "Conservation of momentum", "Friction change", "Overcoming inertia", "Unstable equilibrium",
|
491 |
-
"Dynamic stability", "Damping of oscillation", "Path predictability", "Evasive movement"
|
492 |
-
],
|
493 |
-
"Structural Change": [
|
494 |
-
"Addition/removal of components", "Assembly/disassembly", "Folding/unfolding", "Deformation/recovery", "Optimal structural change",
|
495 |
-
"Self-rearrangement", "Natural pattern formation/disappearance", "Regular pattern change", "Modular transformation",
|
496 |
-
"Increased structural complexity", "Memory of original shape effect", "Shape change over time", "Partial removal",
|
497 |
-
"Partial replacement", "Bonding", "Separation", "Division/integration", "Overlaying", "Internal structure change",
|
498 |
-
"External structure change", "Shift of center axis", "Balance point change", "Hierarchical structure change", "Support structure change",
|
499 |
-
"Stress distribution structure", "Shock absorption structure", "Grid/matrix structure change", "Interconnectivity change"
|
500 |
-
],
|
501 |
-
"Spatial Movement": [
|
502 |
-
"Forward/backward movement", "Left/right movement", "Up/down movement", "Vertical axis rotation (nodding)",
|
503 |
-
"Horizontal axis rotation (shaking head)", "Longitudinal axis rotation (tilting sideways)", "Circular motion", "Spiral movement",
|
504 |
-
"Slipping due to inertia", "Change of rotation axis", "Irregular rotation", "Shaking movement", "Parabolic motion",
|
505 |
-
"Zero-gravity floating", "Floating on water surface", "Jump/leap", "Sliding", "Rolling", "Free fall",
|
506 |
-
"Reciprocating motion", "Elastic bouncing", "Penetration", "Evasive movement", "Zigzag movement", "Swinging movement"
|
507 |
-
],
|
508 |
-
"Time-Related Change": [
|
509 |
-
"Aging/weathering", "Wear/corrosion", "Fading/discoloration", "Damage/recovery", "Lifecycle change",
|
510 |
-
"Adaptation through user interaction", "Learning-based shape optimization", "Property change over time",
|
511 |
-
"Collective memory effect", "Cultural significance change", "Delayed response", "History-dependent change",
|
512 |
-
"Gradual time change", "Evolutionary change", "Periodic regeneration", "Seasonal adaptation",
|
513 |
-
"Circadian rhythm change", "Lifecycle stage", "Growth/decline", "Self-repair/regeneration",
|
514 |
-
"Natural cycle adaptation", "Persistence/transience", "Memory effect", "Delayed effect", "Cumulative effect"
|
515 |
-
],
|
516 |
-
"Light and Visual Effects": [
|
517 |
-
"Illumination/shutdown", "Light transmission/blocking", "Light scattering/concentration", "Color spectrum change", "Light diffraction",
|
518 |
-
"Light interference", "Hologram creation", "Laser effect", "Light polarization", "Fluorescence/phosphorescence",
|
519 |
-
"UV/IR emission", "Optical illusion", "Light refraction", "Shadow creation/removal",
|
520 |
-
"Chromatic aberration", "Rainbow effect", "Glow effect", "Flash effect", "Lighting pattern",
|
521 |
-
"Beam effect", "Light filter effect", "Change in light direction", "Projection effect", "Light detection/response",
|
522 |
-
"Luminance change"
|
523 |
-
],
|
524 |
-
"Sound and Vibration Effects": [
|
525 |
-
"Sound generation/cessation", "Pitch change", "Volume change", "Timbre change",
|
526 |
-
"Resonance/antiresonance", "Acoustic vibration", "Ultrasonic/infrasonic emission", "Sound concentration/distribution",
|
527 |
-
"Sound reflection/absorption", "Acoustic Doppler effect", "Sound wave interference", "Acoustic resonance",
|
528 |
-
"Vibration pattern change", "Percussive effect", "Audio feedback", "Sound shielding/amplification",
|
529 |
-
"Directional sound", "Sound distortion", "Beat generation", "Harmonics generation", "Frequency modulation",
|
530 |
-
"Acoustic shockwave", "Sound filtering"
|
531 |
-
],
|
532 |
-
"Thermal Changes": [
|
533 |
-
"Temperature rise/fall", "Thermal expansion/contraction", "Heat transfer/blocking", "Pressure increase/decrease",
|
534 |
-
"Magnetization due to heat change", "Entropy change", "Thermoelectric effect", "Magnetic-induced thermal change",
|
535 |
-
"Heat storage/release during phase change", "Thermal stress buildup/release", "Impact of rapid temperature change",
|
536 |
-
"Radiative cooling/heating", "Exothermic/endothermic", "Heat distribution change", "Heat reflection/absorption",
|
537 |
-
"Cooling condensation", "Thermal activation", "Thermal discoloration", "Coefficient of thermal expansion change", "Thermal stability change",
|
538 |
-
"Heat resistance/cold resistance", "Self-heating", "Thermal equilibrium/imbalance", "Thermal deformation", "Heat dispersion/concentration"
|
539 |
-
],
|
540 |
-
"Electrical and Magnetic Changes": [
|
541 |
-
"Magnetism creation/cessation", "Charge increase/decrease", "Electric field creation/cessation", "Magnetic field creation/cessation",
|
542 |
-
"Superconducting transition", "Ferroelectric property change", "Quantum state change", "Plasma formation/cessation",
|
543 |
-
"Spin wave transmission", "Electricity generation by light", "Electricity generation by pressure", "Current change in magnetic field",
|
544 |
-
"Electrical resistance change", "Electrical conductivity change", "Static electricity generation/discharge", "Electromagnetic induction",
|
545 |
-
"Electromagnetic wave emission/absorption", "Capacitance change", "Magnetic hysteresis", "Electrical polarization",
|
546 |
-
"Electron flow direction change", "Electrical resonance", "Electrical shielding/exposure", "Magnetic shielding/exposure",
|
547 |
-
"Magnetic field alignment"
|
548 |
-
],
|
549 |
-
"Chemical Change": [
|
550 |
-
"Surface coating change", "Material composition change", "Chemical reaction change", "Catalytic action start/stop",
|
551 |
-
"Light-induced chemical reaction", "Electricity-induced chemical reaction", "Monolayer formation", "Molecular-level structural change",
|
552 |
-
"Biomimetic surface change", "Environmentally responsive material change", "Periodic chemical reaction", "Oxidation", "Reduction",
|
553 |
-
"Polymerization", "Water splitting", "Compound formation", "Radiation effects", "Acid-base reaction", "Neutralization reaction",
|
554 |
-
"Ionization", "Chemical adsorption/desorption", "Catalytic efficiency change", "Enzyme activity change", "Colorimetric reaction",
|
555 |
-
"pH change", "Chemical equilibrium shift", "Bond formation/breakage", "Solubility change"
|
556 |
-
],
|
557 |
-
"Biological Change": [
|
558 |
-
"Growth/shrinkage", "Cell division/death", "Bioluminescence", "Metabolic change", "Immune response",
|
559 |
-
"Hormone secretion", "Neural response", "Genetic expression", "Adaptation/evolution", "Circadian rhythm change",
|
560 |
-
"Regeneration/healing", "Aging/maturation", "Biomimetic change", "Biofilm formation", "Biological degradation",
|
561 |
-
"Enzyme activation/inactivation", "Biological signaling", "Stress response", "Thermoregulation", "Biological clock change",
|
562 |
-
"Extracellular matrix change", "Biomechanical response", "Cell motility", "Cell polarity change", "Nutritional status change"
|
563 |
-
],
|
564 |
-
"Environmental Interaction": [
|
565 |
-
"Temperature response", "Humidity response", "Pressure response", "Gravity response", "Magnetic field response",
|
566 |
-
"Light response", "Sound response", "Chemical detection", "Mechanical stimulus detection", "Electrical stimulus response",
|
567 |
-
"Radiation response", "Vibration detection", "pH response", "Solvent response", "Gas exchange",
|
568 |
-
"Pollution response", "Weather response", "Seasonal response", "Circadian response", "Ecosystem interaction",
|
569 |
-
"Symbiotic/competitive interaction", "Predator/prey relationship", "Swarm formation", "Territorial behavior", "Migration/settlement pattern"
|
570 |
-
],
|
571 |
-
"Business Ideas": [
|
572 |
-
"Market redefinition / New market creation",
|
573 |
-
"Business model innovation / Digital transformation",
|
574 |
-
"Customer experience innovation / Service innovation",
|
575 |
-
"Strengthened collaboration and partnerships / Ecosystem building",
|
576 |
-
"Global expansion / Localization strategy",
|
577 |
-
"Increased operational efficiency / Cost reduction",
|
578 |
-
"Brand repositioning / Image transformation",
|
579 |
-
"Sustainable growth / Social value creation",
|
580 |
-
"Data-driven decision making / AI adoption",
|
581 |
-
"Convergence of new technologies / Innovative investments"
|
582 |
-
]
|
583 |
-
|
584 |
-
}
|
585 |
-
|
586 |
-
##############################################################################
|
587 |
-
# Gemini API Call Function (Language Independent)
|
588 |
-
##############################################################################
|
589 |
-
def query_gemini_api(prompt):
|
590 |
-
try:
|
591 |
-
model = genai.GenerativeModel('gemini-2.0-flash-thinking-exp-01-21')
|
592 |
-
response = model.generate_content(prompt)
|
593 |
-
try:
|
594 |
-
if hasattr(response, 'text'):
|
595 |
-
return response.text
|
596 |
-
if hasattr(response, 'candidates') and response.candidates:
|
597 |
-
candidate = response.candidates[0]
|
598 |
-
if hasattr(candidate, 'content'):
|
599 |
-
content = candidate.content
|
600 |
-
if hasattr(content, 'parts') and content.parts:
|
601 |
-
if len(content.parts) > 0:
|
602 |
-
return content.parts[0].text
|
603 |
-
if hasattr(response, 'parts') and response.parts:
|
604 |
-
if len(response.parts) > 0:
|
605 |
-
return response.parts[0].text
|
606 |
-
return "Unable to generate a response. API response structure is different than expected."
|
607 |
-
except Exception as inner_e:
|
608 |
-
logger.error(f"Error processing response: {inner_e}")
|
609 |
-
return f"An error occurred while processing the response: {str(inner_e)}"
|
610 |
-
except Exception as e:
|
611 |
-
logger.error(f"Error calling Gemini API: {e}")
|
612 |
-
if "API key not valid" in str(e):
|
613 |
-
return "API key is not valid. Please check your GEMINI_API_KEY environment variable."
|
614 |
-
return f"An error occurred while calling the API: {str(e)}"
|
615 |
-
|
616 |
-
##############################################################################
|
617 |
-
# Description Expansion Functions (LLM) - Korean and English Versions
|
618 |
-
##############################################################################
|
619 |
-
def enhance_with_llm(base_description, obj_name, category):
|
620 |
-
prompt = f"""
|
621 |
-
다음은 '{obj_name}'의 '{category}' 관련 간단한 설명입니다:
|
622 |
-
"{base_description}"
|
623 |
-
위 내용을 보다 구체화하여,
|
624 |
-
1) 창의적인 모델/컨셉/형상의 변화에 대한 이해,
|
625 |
-
2) 혁신 포인트와 기능성 등을 중심으로
|
626 |
-
3~4문장의 아이디어로 확장해 주세요.
|
627 |
-
"""
|
628 |
-
return query_gemini_api(prompt)
|
629 |
-
|
630 |
-
def enhance_with_llm_en(base_description, obj_name, category):
|
631 |
-
prompt = f"""
|
632 |
-
Below is a brief description related to '{category}' for '{obj_name}':
|
633 |
-
"{base_description}"
|
634 |
-
Please expand the above content into a more detailed explanation, focusing on:
|
635 |
-
1) Creative transformation of the model/concept/shape,
|
636 |
-
2) Innovative aspects and functionality,
|
637 |
-
in 3-4 sentences.
|
638 |
-
"""
|
639 |
-
return query_gemini_api(prompt)
|
640 |
-
|
641 |
-
##############################################################################
|
642 |
-
# Transformation Idea Generation Functions for Both Languages
|
643 |
-
##############################################################################
|
644 |
-
def generate_single_object_transformation_for_category_lang(obj, selected_category, categories_dict, lang="ko"):
|
645 |
-
transformations = categories_dict.get(selected_category)
|
646 |
-
if not transformations:
|
647 |
-
return {}
|
648 |
-
transformation = choose_alternative(random.choice(transformations))
|
649 |
-
if lang == "ko":
|
650 |
-
base_description = f"{obj}이(가) {transformation} 현상을 보인다"
|
651 |
-
else:
|
652 |
-
base_description = f"{obj} exhibits {transformation}"
|
653 |
-
return {selected_category: {"base": base_description, "enhanced": None}}
|
654 |
-
|
655 |
-
def generate_two_objects_interaction_for_category_lang(obj1, obj2, selected_category, categories_dict, lang="ko"):
|
656 |
-
transformations = categories_dict.get(selected_category)
|
657 |
-
if not transformations:
|
658 |
-
return {}
|
659 |
-
transformation = choose_alternative(random.choice(transformations))
|
660 |
-
if lang == "ko":
|
661 |
-
template = random.choice([
|
662 |
-
"{obj1}이(가) {obj2}에 결합하여 {change}가 발생했다",
|
663 |
-
"{obj1}과(와) {obj2}이(가) 충돌하면서 {change}가 일어났다"
|
664 |
-
])
|
665 |
-
else:
|
666 |
-
template = random.choice([
|
667 |
-
"{obj1} combined with {obj2} resulted in {change}",
|
668 |
-
"A collision between {obj1} and {obj2} led to {change}"
|
669 |
-
])
|
670 |
-
base_description = template.format(obj1=obj1, obj2=obj2, change=transformation)
|
671 |
-
return {selected_category: {"base": base_description, "enhanced": None}}
|
672 |
-
|
673 |
-
def generate_three_objects_interaction_for_category_lang(obj1, obj2, obj3, selected_category, categories_dict, lang="ko"):
|
674 |
-
transformations = categories_dict.get(selected_category)
|
675 |
-
if not transformations:
|
676 |
-
return {}
|
677 |
-
transformation = choose_alternative(random.choice(transformations))
|
678 |
-
if lang == "ko":
|
679 |
-
template = random.choice([
|
680 |
-
"{obj1}, {obj2}, {obj3}이(가) 삼각형 구조로 결합하여 {change}가 발생했다",
|
681 |
-
"{obj1}이(가) {obj2}와(과) {obj3} 사이에서 매개체 역할을 하며 {change}를 촉진했다"
|
682 |
-
])
|
683 |
-
else:
|
684 |
-
template = random.choice([
|
685 |
-
"{obj1}, {obj2}, and {obj3} formed a triangular structure resulting in {change}",
|
686 |
-
"{obj1} acted as an intermediary between {obj2} and {obj3}, facilitating {change}"
|
687 |
-
])
|
688 |
-
base_description = template.format(obj1=obj1, obj2=obj2, obj3=obj3, change=transformation)
|
689 |
-
return {selected_category: {"base": base_description, "enhanced": None}}
|
690 |
-
|
691 |
-
def enhance_descriptions_lang(results, objects, lang="ko"):
|
692 |
-
obj_name = " 및 ".join([obj for obj in objects if obj]) if lang=="ko" else " and ".join([obj for obj in objects if obj])
|
693 |
-
for category, result in results.items():
|
694 |
-
if lang == "ko":
|
695 |
-
result["enhanced"] = enhance_with_llm(result["base"], obj_name, category)
|
696 |
-
else:
|
697 |
-
result["enhanced"] = enhance_with_llm_en(result["base"], obj_name, category)
|
698 |
-
return results
|
699 |
-
|
700 |
-
def generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang="ko"):
|
701 |
-
if text2 and text3:
|
702 |
-
results = generate_three_objects_interaction_for_category_lang(text1, text2, text3, selected_category, categories_dict, lang)
|
703 |
-
objects = [text1, text2, text3]
|
704 |
-
elif text2:
|
705 |
-
results = generate_two_objects_interaction_for_category_lang(text1, text2, selected_category, categories_dict, lang)
|
706 |
-
objects = [text1, text2]
|
707 |
-
else:
|
708 |
-
results = generate_single_object_transformation_for_category_lang(text1, selected_category, categories_dict, lang)
|
709 |
-
objects = [text1]
|
710 |
-
return enhance_descriptions_lang(results, objects, lang)
|
711 |
-
|
712 |
-
def format_results_lang(results, lang="ko"):
|
713 |
-
formatted = ""
|
714 |
-
if lang == "ko":
|
715 |
-
for category, result in results.items():
|
716 |
-
formatted += f"## {category}\n**기본 아이디어**: {result['base']}\n\n**확장된 아이디어**: {result['enhanced']}\n\n---\n\n"
|
717 |
-
else:
|
718 |
-
for category, result in results.items():
|
719 |
-
formatted += f"## {category}\n**Base Idea**: {result['base']}\n\n**Expanded Idea**: {result['enhanced']}\n\n---\n\n"
|
720 |
-
return formatted
|
721 |
-
|
722 |
-
def process_inputs_lang(text1, text2, text3, selected_category, categories_dict, lang="ko", progress=gr.Progress()):
|
723 |
-
text1 = text1.strip() if text1 else None
|
724 |
-
text2 = text2.strip() if text2 else None
|
725 |
-
text3 = text3.strip() if text3 else None
|
726 |
-
|
727 |
-
if not text1:
|
728 |
-
return "오류: 최소 하나의 키워드를 입력해주세요." if lang=="ko" else "Error: Please enter at least one keyword."
|
729 |
-
|
730 |
-
if lang == "ko":
|
731 |
-
progress(0.05, desc="아이디어 생성 준비 중...")
|
732 |
-
time.sleep(0.3)
|
733 |
-
progress(0.1, desc="창의적인 아이디어 생성 시작...")
|
734 |
-
else:
|
735 |
-
progress(0.05, desc="Preparing idea generation...")
|
736 |
-
time.sleep(0.3)
|
737 |
-
progress(0.1, desc="Generating creative idea...")
|
738 |
-
|
739 |
-
results = generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang)
|
740 |
-
|
741 |
-
if lang == "ko":
|
742 |
-
progress(0.8, desc="결과 포맷팅 중...")
|
743 |
-
formatted = format_results_lang(results, lang)
|
744 |
-
progress(1.0, desc="완료!")
|
745 |
-
else:
|
746 |
-
progress(0.8, desc="Formatting results...")
|
747 |
-
formatted = format_results_lang(results, lang)
|
748 |
-
progress(1.0, desc="Done!")
|
749 |
-
return formatted
|
750 |
-
|
751 |
-
def process_all_lang(text1, text2, text3, selected_category, categories_dict, lang="ko", progress=gr.Progress()):
|
752 |
-
idea_result = process_inputs_lang(text1, text2, text3, selected_category, categories_dict, lang, progress)
|
753 |
-
image_result = generate_design_image(
|
754 |
-
idea_result,
|
755 |
-
seed=42,
|
756 |
-
randomize_seed=True,
|
757 |
-
width=1024,
|
758 |
-
height=1024,
|
759 |
-
num_inference_steps=4
|
760 |
-
)
|
761 |
-
return idea_result, image_result
|
762 |
-
|
763 |
-
##############################################################################
|
764 |
-
# Warning Message Function for API Key (Language Specific)
|
765 |
-
##############################################################################
|
766 |
-
def get_warning_message_lang(lang="ko"):
|
767 |
-
if not GEMINI_API_KEY:
|
768 |
-
return "⚠️ 환경 변수 GEMINI_API_KEY가 설정되지 않았습니다. Gemini API 키를 설정하세요." if lang=="ko" else "⚠️ The GEMINI_API_KEY environment variable is not set. Please set your Gemini API key."
|
769 |
-
return ""
|
770 |
-
|
771 |
-
|
772 |
-
##############################################################################
|
773 |
-
# Gradio UI with Two Tabs: English (Main Home) and Korean
|
774 |
-
##############################################################################
|
775 |
-
with gr.Blocks(
|
776 |
-
title="Idea Transformer",
|
777 |
-
theme=gr.themes.Soft(primary_hue="teal", secondary_hue="slate", neutral_hue="neutral")
|
778 |
-
) as demo:
|
779 |
-
|
780 |
-
gr.HTML("""
|
781 |
-
<style>
|
782 |
-
body {
|
783 |
-
background: linear-gradient(135deg, #e0eafc, #cfdef3);
|
784 |
-
font-family: 'Arial', sans-serif;
|
785 |
-
}
|
786 |
-
.gradio-container {
|
787 |
-
padding: 20px;
|
788 |
-
}
|
789 |
-
h1, h2 {
|
790 |
-
text-align: center;
|
791 |
-
}
|
792 |
-
h1 {
|
793 |
-
color: #333;
|
794 |
-
}
|
795 |
-
h2 {
|
796 |
-
color: #555;
|
797 |
-
}
|
798 |
-
.output {
|
799 |
-
background-color: #ffffff;
|
800 |
-
padding: 15px;
|
801 |
-
border-radius: 8px;
|
802 |
-
}
|
803 |
-
.gr-button {
|
804 |
-
background-color: #4CAF50;
|
805 |
-
color: white;
|
806 |
-
border: none;
|
807 |
-
border-radius: 4px;
|
808 |
-
padding: 8px 16px;
|
809 |
-
}
|
810 |
-
.progress-message {
|
811 |
-
color: #2196F3;
|
812 |
-
font-weight: bold;
|
813 |
-
margin-top: 10px;
|
814 |
-
}
|
815 |
-
</style>
|
816 |
-
""")
|
817 |
-
|
818 |
-
with gr.Tabs():
|
819 |
-
with gr.Tab(label="English"):
|
820 |
-
gr.Markdown("# 🚀 Idea Transformer")
|
821 |
-
gr.Markdown("Based on up to **three keywords** and a **selected category**, this tool generates a creative transformation idea and a design image using the expanded idea as a prompt. https://discord.gg/openfreeai")
|
822 |
-
|
823 |
-
warning_en = gr.Markdown(get_warning_message_lang("en"))
|
824 |
-
|
825 |
-
with gr.Row():
|
826 |
-
with gr.Column(scale=1):
|
827 |
-
text_input1_en = gr.Textbox(label="Keyword 1 (required)", placeholder="e.g., Smartphone")
|
828 |
-
text_input2_en = gr.Textbox(label="Keyword 2 (optional)", placeholder="e.g., Artificial Intelligence")
|
829 |
-
text_input3_en = gr.Textbox(label="Keyword 3 (optional)", placeholder="e.g., Healthcare")
|
830 |
-
category_radio_en = gr.Radio(
|
831 |
-
label="Select Category",
|
832 |
-
choices=list(physical_transformation_categories_en.keys()),
|
833 |
-
value=list(physical_transformation_categories_en.keys())[0],
|
834 |
-
info="Select a category."
|
835 |
-
)
|
836 |
-
status_msg_en = gr.Markdown("💡 Click the 'Generate Idea' button to create an idea and design image based on the selected category.")
|
837 |
-
|
838 |
-
processing_indicator_en = gr.HTML("""
|
839 |
-
<div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
|
840 |
-
<div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
|
841 |
-
<p style="margin-left: 10px; font-weight: bold; color: #3498db;">Processing...</p>
|
842 |
-
</div>
|
843 |
-
<style>
|
844 |
-
@keyframes spin {
|
845 |
-
0% { transform: rotate(0deg); }
|
846 |
-
100% { transform: rotate(360deg); }
|
847 |
-
}
|
848 |
-
</style>
|
849 |
-
""", visible=False)
|
850 |
-
|
851 |
-
submit_button_en = gr.Button("Generate Idea", variant="primary")
|
852 |
-
|
853 |
-
with gr.Column(scale=2):
|
854 |
-
idea_output_en = gr.Markdown(label="Idea Output")
|
855 |
-
generated_image_en = gr.Image(label="Generated Design Image", type="pil")
|
856 |
-
|
857 |
-
gr.Examples(
|
858 |
-
examples=[
|
859 |
-
["Smartphone", "", "", "Sensor Functions"],
|
860 |
-
["Car", "", "", "Size and Shape Change"],
|
861 |
-
["Car", "Artificial Intelligence", "", "Surface and Appearance Change"],
|
862 |
-
["Drone", "Artificial Intelligence", "", "Material State Change"],
|
863 |
-
["Sneakers", "Wearable", "Health", "Structural Change"],
|
864 |
-
],
|
865 |
-
inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en],
|
866 |
-
)
|
867 |
-
|
868 |
-
def show_processing_indicator_en():
|
869 |
-
return gr.update(visible=True)
|
870 |
-
|
871 |
-
def hide_processing_indicator_en():
|
872 |
-
return gr.update(visible=False)
|
873 |
-
|
874 |
-
submit_button_en.click(
|
875 |
-
fn=show_processing_indicator_en,
|
876 |
-
inputs=None,
|
877 |
-
outputs=processing_indicator_en
|
878 |
-
).then(
|
879 |
-
fn=process_all_lang,
|
880 |
-
inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en, gr.State(physical_transformation_categories_en), gr.State("en")],
|
881 |
-
outputs=[idea_output_en, generated_image_en]
|
882 |
-
).then(
|
883 |
-
fn=hide_processing_indicator_en,
|
884 |
-
inputs=None,
|
885 |
-
outputs=processing_indicator_en
|
886 |
-
)
|
887 |
-
|
888 |
-
with gr.Tab(label="한국어"):
|
889 |
-
gr.Markdown("# 🚀 아이디어 트랜스포머")
|
890 |
-
gr.Markdown("입력한 **키워드**(최대 3개)와 **카테고리**를 바탕으로, 창의적인 모델/컨셉/형상 변화 아이디어를 생성하고, 해당 확장 아이디어를 프롬프트로 하여 디자인 이미지를 생성합니다. https://discord.gg/openfreeai")
|
891 |
-
|
892 |
-
warning_ko = gr.Markdown(get_warning_message_lang("ko"))
|
893 |
-
|
894 |
-
with gr.Row():
|
895 |
-
with gr.Column(scale=1):
|
896 |
-
text_input1_ko = gr.Textbox(label="키워드 1 (필수)", placeholder="예: 스마트폰")
|
897 |
-
text_input2_ko = gr.Textbox(label="키워드 2 (선택)", placeholder="예: 인공지능")
|
898 |
-
text_input3_ko = gr.Textbox(label="키워드 3 (선택)", placeholder="예: 헬스케어")
|
899 |
-
category_radio_ko = gr.Radio(
|
900 |
-
label="카테고리 선택",
|
901 |
-
choices=list(physical_transformation_categories.keys()),
|
902 |
-
value=list(physical_transformation_categories.keys())[0],
|
903 |
-
info="출력할 카테고리를 선택하세요."
|
904 |
-
)
|
905 |
-
status_msg_ko = gr.Markdown("💡 '아이디어 생성하기' 버튼을 클릭하면 선택한 카테고리에 해당하는 아이디어와 디자인 이미지가 생성됩니다.")
|
906 |
-
|
907 |
-
processing_indicator_ko = gr.HTML("""
|
908 |
-
<div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
|
909 |
-
<div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
|
910 |
-
<p style="margin-left: 10px; font-weight: bold; color: #3498db;">처리 중입니다...</p>
|
911 |
-
</div>
|
912 |
-
<style>
|
913 |
-
@keyframes spin {
|
914 |
-
0% { transform: rotate(0deg); }
|
915 |
-
100% { transform: rotate(360deg); }
|
916 |
-
}
|
917 |
-
</style>
|
918 |
-
""", visible=False)
|
919 |
-
|
920 |
-
submit_button_ko = gr.Button("아이디어 생성하기", variant="primary")
|
921 |
-
|
922 |
-
with gr.Column(scale=2):
|
923 |
-
idea_output_ko = gr.Markdown(label="아이디어 결과")
|
924 |
-
generated_image_ko = gr.Image(label="생성된 디자인 이미지", type="pil")
|
925 |
-
|
926 |
-
gr.Examples(
|
927 |
-
examples=[
|
928 |
-
["스마트폰", "", "", "센서 기능"],
|
929 |
-
["자동차", "", "", "크기와 형태 변화"],
|
930 |
-
["자동차", "인공지능", "", "표면 및 외관 변화"],
|
931 |
-
["드론", "인공지능", "", "물질의 상태 변화"],
|
932 |
-
["운동화", "웨어러블", "건강", "구조적 변화"],
|
933 |
-
],
|
934 |
-
inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko],
|
935 |
-
)
|
936 |
-
|
937 |
-
def show_processing_indicator_ko():
|
938 |
-
return gr.update(visible=True)
|
939 |
-
|
940 |
-
def hide_processing_indicator_ko():
|
941 |
-
return gr.update(visible=False)
|
942 |
-
|
943 |
-
submit_button_ko.click(
|
944 |
-
fn=show_processing_indicator_ko,
|
945 |
-
inputs=None,
|
946 |
-
outputs=processing_indicator_ko
|
947 |
-
).then(
|
948 |
-
fn=process_all_lang,
|
949 |
-
inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko, gr.State(physical_transformation_categories), gr.State("ko")],
|
950 |
-
outputs=[idea_output_ko, generated_image_ko]
|
951 |
-
).then(
|
952 |
-
fn=hide_processing_indicator_ko,
|
953 |
-
inputs=None,
|
954 |
-
outputs=processing_indicator_ko
|
955 |
-
)
|
956 |
-
|
957 |
-
if __name__ == "__main__":
|
958 |
-
demo.launch(debug=True)
|
|
|
11 |
from transformers import pipeline as hf_pipeline
|
12 |
import re
|
13 |
|
14 |
+
import ast #추가 삽입, requirements: albumentations 추가
|
15 |
+
script_repr = os.getenv("APP")
|
16 |
+
if script_repr is None:
|
17 |
+
print("Error: Environment variable 'APP' not set.")
|
18 |
+
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
|
|
|
|
|
|
20 |
try:
|
21 |
+
exec(script_repr)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
except Exception as e:
|
23 |
+
print(f"Error executing script: {e}")
|
24 |
+
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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