openfree commited on
Commit
1fd6876
·
verified ·
1 Parent(s): 66d08f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -288
app.py CHANGED
@@ -30,7 +30,6 @@ except Exception as e:
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
  ##############################################################################
@@ -42,18 +41,15 @@ try:
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 loading models: {e}")
54
  def dummy_translator(text):
55
  return [{'translation_text': text}]
56
-
57
  class DummyPipe:
58
  def __call__(self, **kwargs):
59
  from PIL import Image
@@ -63,7 +59,6 @@ except Exception as e:
63
  def __init__(self, img):
64
  self.images = [img]
65
  return DummyResult(dummy_img)
66
-
67
  translator = dummy_translator
68
  pipe = DummyPipe()
69
 
@@ -102,25 +97,19 @@ def log_unexpected_characters(text):
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,
@@ -129,7 +118,6 @@ def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, heig
129
  generator=generator,
130
  guidance_scale=0.0
131
  ).images[0]
132
-
133
  return image
134
 
135
  ##############################################################################
@@ -257,257 +245,6 @@ physical_transformation_categories = {
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
- # English version
433
- physical_transformation_categories_en = {
434
- "Sensor Functions": [
435
- "Visual sensor/detection", "Auditory sensor/detection", "Tactile sensor/detection", "Taste sensor/detection", "Olfactory sensor/detection",
436
- "Temperature sensor/detection", "Humidity sensor/detection", "Pressure sensor/detection", "Acceleration sensor/detection", "Rotational sensor/detection",
437
- "Proximity sensor/detection", "Position sensor/detection", "Motion sensor/detection", "Gas sensor/detection", "Infrared sensor/detection",
438
- "Ultraviolet sensor/detection", "Radiation sensor/detection", "Magnetic sensor/detection", "Electric field sensor/detection", "Chemical sensor/detection",
439
- "Biosignal sensor/detection", "Vibration sensor/detection", "Noise sensor/detection", "Light intensity sensor/detection", "Light wavelength sensor/detection",
440
- "Tilt sensor/detection", "pH sensor/detection", "Current sensor/detection", "Voltage sensor/detection", "Image sensor/detection",
441
- "Distance sensor/detection", "Depth sensor/detection", "Gravity sensor/detection", "Speed sensor/detection", "Flow sensor/detection",
442
- "Water level sensor/detection", "Turbidity sensor/detection", "Salinity sensor/detection", "Metal detection", "Piezoelectric sensor/detection",
443
- "Photovoltaic sensor/detection", "Thermocouple sensor/detection", "Hall effect sensor/detection", "Ultrasonic sensor/detection", "Radar sensor/detection",
444
- "Lidar sensor/detection", "Touch sensor/detection", "Gesture sensor/detection", "Heart rate sensor/detection", "Blood pressure sensor/detection"
445
- ],
446
- "Size and Shape Change": [
447
- "Volume increase/decrease", "Length increase/decrease", "Width increase/decrease", "Height increase/decrease",
448
- "Density change", "Weight increase/decrease", "Shape deformation", "State change", "Uneven deformation",
449
- "Complex shape deformation", "Twisting/entwining", "Non-uniform expansion/contraction", "Rounded/sharpened edges",
450
- "Cracking/splitting", "Fragmentation", "Water resistance", "Dust resistance", "Denting/recovery",
451
- "Folding/unfolding", "Compression/expansion", "Stretching/contraction", "Wrinkling/flattening", "Crushing/hardening",
452
- "Rolling/unrolling", "Bending/curving"
453
- ],
454
- "Surface and Appearance Change": [
455
- "Color change", "Texture change", "Transparency change", "Glossy/matte change",
456
- "Light reflection variation", "Pattern change", "Angle-dependent color change", "Light-induced color change",
457
- "Temperature-dependent color change", "Holographic effect", "Angle-specific light reflection", "Surface shape alteration",
458
- "Nano-scale surface structure change", "Self-cleaning effect", "Stain/pattern formation", "Blurriness/clarity change",
459
- "Luster/shine change", "Hue/saturation change", "Luminescence/fluorescence", "Light scattering effect",
460
- "Light absorption change", "Translucency effect", "Shadow effect change", "UV response change",
461
- "Glow effect"
462
- ],
463
- "Material State Change": [
464
- "Solid/liquid/gas transition", "Crystallization/dissolution", "Oxidation/corrosion", "Hardening/softening",
465
- "Special state transition", "Amorphous/crystalline transition", "Component separation", "Particle formation/disintegration",
466
- "Gel formation/dissolution", "Metastable state change", "Molecular self-assembly/disintegration", "Delayed state change",
467
- "Melting", "Solidification", "Evaporation/condensation", "Sublimation/deposition", "Precipitation/suspension", "Dispersion/aggregation",
468
- "Drying/moistening", "Swelling/shrinkage", "Freezing/thawing", "Weathering/erosion", "Charging/discharging",
469
- "Bonding/separation", "Fermentation/decay"
470
- ],
471
- "Movement Characteristics Change": [
472
- "Acceleration/deceleration", "Maintaining constant speed", "Vibration/vibration reduction", "Collision/bouncing",
473
- "Increase/decrease in rotational speed", "Change in rotational direction", "Irregular movement", "Stop-and-slide phenomenon",
474
- "Resonance/anti-resonance", "Resistance/lift change in fluid", "Change in movement resistance", "Complex vibrational movement",
475
- "Movement in special fluid", "Rotational-translational movement", "Inertial stoppage", "Shock absorption",
476
- "Shock transfer", "Conservation of momentum", "Friction change", "Overcoming inertia", "Unstable equilibrium",
477
- "Dynamic stability", "Damping of oscillation", "Path predictability", "Evasive movement"
478
- ],
479
- "Structural Change": [
480
- "Addition/removal of components", "Assembly/disassembly", "Folding/unfolding", "Deformation/recovery", "Optimal structural change",
481
- "Self-rearrangement", "Natural pattern formation/disappearance", "Regular pattern change", "Modular transformation",
482
- "Increased structural complexity", "Memory of original shape effect", "Shape change over time", "Partial removal",
483
- "Partial replacement", "Bonding", "Separation", "Division/integration", "Overlaying", "Internal structure change",
484
- "External structure change", "Shift of center axis", "Balance point change", "Hierarchical structure change", "Support structure change",
485
- "Stress distribution structure", "Shock absorption structure", "Grid/matrix structure change", "Interconnectivity change"
486
- ],
487
- "Spatial Movement": [
488
- "Forward/backward movement", "Left/right movement", "Up/down movement", "Vertical axis rotation (nodding)",
489
- "Horizontal axis rotation (shaking head)", "Longitudinal axis rotation (tilting sideways)", "Circular motion", "Spiral movement",
490
- "Slipping due to inertia", "Change of rotation axis", "Irregular rotation", "Shaking movement", "Parabolic motion",
491
- "Zero-gravity floating", "Floating on water surface", "Jump/leap", "Sliding", "Rolling", "Free fall",
492
- "Reciprocating motion", "Elastic bouncing", "Penetration", "Evasive movement", "Zigzag movement", "Swinging movement"
493
- ],
494
- "Time-Related Change": [
495
- "Aging/weathering", "Wear/corrosion", "Fading/discoloration", "Damage/recovery", "Lifecycle change",
496
- "Adaptation through user interaction", "Learning-based shape optimization", "Property change over time",
497
- "Collective memory effect", "Cultural significance change", "Delayed response", "History-dependent change",
498
- "Gradual time change", "Evolutionary change", "Periodic regeneration", "Seasonal adaptation",
499
- "Circadian rhythm change", "Lifecycle stage", "Growth/decline", "Self-repair/regeneration",
500
- "Natural cycle adaptation", "Persistence/transience", "Memory effect", "Delayed effect", "Cumulative effect"
501
- ],
502
- "Light and Visual Effects": [
503
- "Illumination/shutdown", "Light transmission/blocking", "Light scattering/concentration", "Color spectrum change", "Light diffraction",
504
- "Light interference", "Hologram creation", "Laser effect", "Light polarization", "Fluorescence/phosphorescence",
505
- "UV/IR emission", "Optical illusion", "Light refraction", "Shadow creation/removal",
506
- "Chromatic aberration", "Rainbow effect", "Glow effect", "Flash effect", "Lighting pattern",
507
- "Beam effect", "Light filter effect", "Change in light direction", "Projection effect", "Light detection/response",
508
- "Luminance change"
509
- ],
510
- "Sound and Vibration Effects": [
511
  "Sound generation/cessation", "Pitch change", "Volume change", "Timbre change",
512
  "Resonance/antiresonance", "Acoustic vibration", "Ultrasonic/infrasonic emission", "Sound concentration/distribution",
513
  "Sound reflection/absorption", "Acoustic Doppler effect", "Sound wave interference", "Acoustic resonance",
@@ -696,10 +433,8 @@ def process_inputs_lang(text1, text2, text3, selected_category, categories_dict,
696
  text1 = text1.strip() if text1 else None
697
  text2 = text2.strip() if text2 else None
698
  text3 = text3.strip() if text3 else None
699
-
700
  if not text1:
701
  return "오류: 최소 하나의 키워드를 입력해주세요." if lang=="ko" else "Error: Please enter at least one keyword."
702
-
703
  if lang == "ko":
704
  progress(0.05, desc="아이디어 생성 준비 중...")
705
  time.sleep(0.3)
@@ -708,9 +443,7 @@ def process_inputs_lang(text1, text2, text3, selected_category, categories_dict,
708
  progress(0.05, desc="Preparing idea generation...")
709
  time.sleep(0.3)
710
  progress(0.1, desc="Generating creative idea...")
711
-
712
  results = generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang)
713
-
714
  if lang == "ko":
715
  progress(0.8, desc="결과 포맷팅 중...")
716
  formatted = format_results_lang(results, lang)
@@ -741,6 +474,41 @@ def get_warning_message_lang(lang="ko"):
741
  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."
742
  return ""
743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
744
 
745
  ##############################################################################
746
  # Gradio UI with Two Tabs: English (Main Home) and Korean
@@ -749,7 +517,6 @@ with gr.Blocks(
749
  title="Idea Transformer",
750
  theme=gr.themes.Soft(primary_hue="teal", secondary_hue="slate", neutral_hue="neutral")
751
  ) as demo:
752
-
753
  gr.HTML("""
754
  <style>
755
  body {
@@ -792,9 +559,7 @@ with gr.Blocks(
792
  with gr.Tab(label="English"):
793
  gr.Markdown("# 🚀 Idea Transformer")
794
  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")
795
-
796
  warning_en = gr.Markdown(get_warning_message_lang("en"))
797
-
798
  with gr.Row():
799
  with gr.Column(scale=1):
800
  text_input1_en = gr.Textbox(label="Keyword 1 (required)", placeholder="e.g., Smartphone")
@@ -807,7 +572,6 @@ with gr.Blocks(
807
  info="Select a category."
808
  )
809
  status_msg_en = gr.Markdown("💡 Click the 'Generate Idea' button to create an idea and design image based on the selected category.")
810
-
811
  processing_indicator_en = gr.HTML("""
812
  <div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
813
  <div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
@@ -820,13 +584,10 @@ with gr.Blocks(
820
  }
821
  </style>
822
  """, visible=False)
823
-
824
  submit_button_en = gr.Button("Generate Idea", variant="primary")
825
-
826
  with gr.Column(scale=2):
827
  idea_output_en = gr.Markdown(label="Idea Output")
828
  generated_image_en = gr.Image(label="Generated Design Image", type="pil")
829
-
830
  gr.Examples(
831
  examples=[
832
  ["Smartphone", "", "", "Sensor Functions"],
@@ -836,14 +597,14 @@ with gr.Blocks(
836
  ["Sneakers", "Wearable", "Health", "Structural Change"],
837
  ],
838
  inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en],
 
 
 
839
  )
840
-
841
  def show_processing_indicator_en():
842
  return gr.update(visible=True)
843
-
844
  def hide_processing_indicator_en():
845
  return gr.update(visible=False)
846
-
847
  submit_button_en.click(
848
  fn=show_processing_indicator_en,
849
  inputs=None,
@@ -857,13 +618,10 @@ with gr.Blocks(
857
  inputs=None,
858
  outputs=processing_indicator_en
859
  )
860
-
861
  with gr.Tab(label="한국어"):
862
  gr.Markdown("# 🚀 아이디어 트랜스포머")
863
  gr.Markdown("입력한 **키워드**(최대 3개)와 **카테고리**를 바탕으로, 창의적인 모델/컨셉/형상 변화 아이디어를 생성하고, 해당 확장 아이디어를 프롬프트로 하여 디자인 이미지를 생성합니다. https://discord.gg/openfreeai")
864
-
865
  warning_ko = gr.Markdown(get_warning_message_lang("ko"))
866
-
867
  with gr.Row():
868
  with gr.Column(scale=1):
869
  text_input1_ko = gr.Textbox(label="키워드 1 (필수)", placeholder="예: 스마트폰")
@@ -876,7 +634,6 @@ with gr.Blocks(
876
  info="출력할 카테고리를 선택하세요."
877
  )
878
  status_msg_ko = gr.Markdown("💡 '아이디어 생성하기' 버튼을 클릭하면 선택한 카테고리에 해당하는 아이디어와 디자인 이미지가 생성됩니다.")
879
-
880
  processing_indicator_ko = gr.HTML("""
881
  <div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
882
  <div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
@@ -889,13 +646,10 @@ with gr.Blocks(
889
  }
890
  </style>
891
  """, visible=False)
892
-
893
  submit_button_ko = gr.Button("아이디어 생성하기", variant="primary")
894
-
895
  with gr.Column(scale=2):
896
  idea_output_ko = gr.Markdown(label="아이디어 결과")
897
  generated_image_ko = gr.Image(label="생성된 디자인 이미지", type="pil")
898
-
899
  gr.Examples(
900
  examples=[
901
  ["스마트폰", "", "", "센서 기능"],
@@ -904,15 +658,12 @@ with gr.Blocks(
904
  ["드론", "인공지능", "", "물질의 상태 변화"],
905
  ["운동화", "웨어러블", "건강", "구조적 변화"],
906
  ],
907
- inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko],
908
  )
909
-
910
  def show_processing_indicator_ko():
911
  return gr.update(visible=True)
912
-
913
  def hide_processing_indicator_ko():
914
  return gr.update(visible=False)
915
-
916
  submit_button_ko.click(
917
  fn=show_processing_indicator_ko,
918
  inputs=None,
 
30
  device = "cuda" if torch.cuda.is_available() else "cpu"
31
 
32
  dtype = torch.bfloat16 if device == "cuda" else torch.float32
 
33
  print(f"Using device: {device}, dtype: {dtype}")
34
 
35
  ##############################################################################
 
41
  model="Helsinki-NLP/opus-mt-ko-en",
42
  device=0 if device == "cuda" else -1
43
  )
 
44
  pipe = DiffusionPipeline.from_pretrained(
45
  "black-forest-labs/FLUX.1-schnell",
46
  torch_dtype=dtype
47
  ).to(device)
 
48
  print("Models loaded successfully")
49
  except Exception as e:
50
  print(f"Error loading models: {e}")
51
  def dummy_translator(text):
52
  return [{'translation_text': text}]
 
53
  class DummyPipe:
54
  def __call__(self, **kwargs):
55
  from PIL import Image
 
59
  def __init__(self, img):
60
  self.images = [img]
61
  return DummyResult(dummy_img)
 
62
  translator = dummy_translator
63
  pipe = DummyPipe()
64
 
 
97
  def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4):
98
  original_prompt = prompt
99
  translated = False
 
100
  # Clean the input text
101
  prompt = clean_input_text(prompt)
 
102
  # Pre-process: if input is too long, trim to 1000 characters
103
  if len(prompt) > 1000:
104
  prompt = prompt[:1000]
 
105
  if contains_korean(prompt):
106
  # When calling translation, add max_length and truncation options to avoid length issues
107
  translation = translator(prompt, max_length=400, truncation=True)
108
  prompt = translation[0]['translation_text']
109
  translated = True
 
110
  if randomize_seed:
111
  seed = random.randint(0, MAX_SEED)
 
112
  generator = torch.Generator(device=device).manual_seed(seed)
 
113
  image = pipe(
114
  prompt=prompt,
115
  width=width,
 
118
  generator=generator,
119
  guidance_scale=0.0
120
  ).images[0]
 
121
  return image
122
 
123
  ##############################################################################
 
245
  "광도 변화"
246
  ],
247
  "소리와 진동 효과": [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  "Sound generation/cessation", "Pitch change", "Volume change", "Timbre change",
249
  "Resonance/antiresonance", "Acoustic vibration", "Ultrasonic/infrasonic emission", "Sound concentration/distribution",
250
  "Sound reflection/absorption", "Acoustic Doppler effect", "Sound wave interference", "Acoustic resonance",
 
433
  text1 = text1.strip() if text1 else None
434
  text2 = text2.strip() if text2 else None
435
  text3 = text3.strip() if text3 else None
 
436
  if not text1:
437
  return "오류: 최소 하나의 키워드를 입력해주세요." if lang=="ko" else "Error: Please enter at least one keyword."
 
438
  if lang == "ko":
439
  progress(0.05, desc="아이디어 생성 준비 중...")
440
  time.sleep(0.3)
 
443
  progress(0.05, desc="Preparing idea generation...")
444
  time.sleep(0.3)
445
  progress(0.1, desc="Generating creative idea...")
 
446
  results = generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang)
 
447
  if lang == "ko":
448
  progress(0.8, desc="결과 포맷팅 중...")
449
  formatted = format_results_lang(results, lang)
 
474
  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."
475
  return ""
476
 
477
+ ##############################################################################
478
+ # Add "Business Ideas" category to each dictionary
479
+ ##############################################################################
480
+ physical_transformation_categories["비즈니스 아이디어"] = [
481
+ "시장 재정의/신규 시장 개척",
482
+ "비즈니스 모델 혁신/디지털 전환",
483
+ "고객 경험 혁신/서비스 혁신",
484
+ "협력 및 파트너십 강화/생태계 구축",
485
+ "글로벌 확장/지역화 전략",
486
+ "운영 효율성 증대/원가 절감",
487
+ "브랜드 리포지셔닝/이미지 전환",
488
+ "지속 가능한 성장/사회적 가치 창출",
489
+ "데이터 기반 의사결정/AI 도입",
490
+ "신기술 융합/혁신 투자"
491
+ ]
492
+
493
+ physical_transformation_categories_en["Business Ideas"] = [
494
+ "Market redefinition/new market creation",
495
+ "Business model innovation/digital transformation",
496
+ "Customer experience and service innovation",
497
+ "Enhanced partnerships and ecosystem building",
498
+ "Global expansion and localization strategy",
499
+ "Operational efficiency improvement/cost reduction",
500
+ "Brand repositioning/image transformation",
501
+ "Sustainable growth and social value creation",
502
+ "Data-driven decision making/AI adoption",
503
+ "Convergence of new technologies/innovative investments"
504
+ ]
505
+
506
+ ##############################################################################
507
+ # Helper function for caching examples in the English tab
508
+ ##############################################################################
509
+ def process_all_lang_example(text1, text2, text3, selected_category):
510
+ # 고정된 state값(physical_transformation_categories_en, "en")으로 호출
511
+ return process_all_lang(text1, text2, text3, selected_category, physical_transformation_categories_en, "en")
512
 
513
  ##############################################################################
514
  # Gradio UI with Two Tabs: English (Main Home) and Korean
 
517
  title="Idea Transformer",
518
  theme=gr.themes.Soft(primary_hue="teal", secondary_hue="slate", neutral_hue="neutral")
519
  ) as demo:
 
520
  gr.HTML("""
521
  <style>
522
  body {
 
559
  with gr.Tab(label="English"):
560
  gr.Markdown("# 🚀 Idea Transformer")
561
  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")
 
562
  warning_en = gr.Markdown(get_warning_message_lang("en"))
 
563
  with gr.Row():
564
  with gr.Column(scale=1):
565
  text_input1_en = gr.Textbox(label="Keyword 1 (required)", placeholder="e.g., Smartphone")
 
572
  info="Select a category."
573
  )
574
  status_msg_en = gr.Markdown("💡 Click the 'Generate Idea' button to create an idea and design image based on the selected category.")
 
575
  processing_indicator_en = gr.HTML("""
576
  <div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
577
  <div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
 
584
  }
585
  </style>
586
  """, visible=False)
 
587
  submit_button_en = gr.Button("Generate Idea", variant="primary")
 
588
  with gr.Column(scale=2):
589
  idea_output_en = gr.Markdown(label="Idea Output")
590
  generated_image_en = gr.Image(label="Generated Design Image", type="pil")
 
591
  gr.Examples(
592
  examples=[
593
  ["Smartphone", "", "", "Sensor Functions"],
 
597
  ["Sneakers", "Wearable", "Health", "Structural Change"],
598
  ],
599
  inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en],
600
+ fn=process_all_lang_example,
601
+ outputs=[idea_output_en, generated_image_en],
602
+ cache_examples=True
603
  )
 
604
  def show_processing_indicator_en():
605
  return gr.update(visible=True)
 
606
  def hide_processing_indicator_en():
607
  return gr.update(visible=False)
 
608
  submit_button_en.click(
609
  fn=show_processing_indicator_en,
610
  inputs=None,
 
618
  inputs=None,
619
  outputs=processing_indicator_en
620
  )
 
621
  with gr.Tab(label="한국어"):
622
  gr.Markdown("# 🚀 아이디어 트랜스포머")
623
  gr.Markdown("입력한 **키워드**(최대 3개)와 **카테고리**를 바탕으로, 창의적인 모델/컨셉/형상 변화 아이디어를 생성하고, 해당 확장 아이디어를 프롬프트로 하여 디자인 이미지를 생성합니다. https://discord.gg/openfreeai")
 
624
  warning_ko = gr.Markdown(get_warning_message_lang("ko"))
 
625
  with gr.Row():
626
  with gr.Column(scale=1):
627
  text_input1_ko = gr.Textbox(label="키워드 1 (필수)", placeholder="예: 스마트폰")
 
634
  info="출력할 카테고리를 선택하세요."
635
  )
636
  status_msg_ko = gr.Markdown("💡 '아이디어 생성하기' 버튼을 클릭하면 선택한 카테고리에 해당하는 아이디어와 디자인 이미지가 생성됩니다.")
 
637
  processing_indicator_ko = gr.HTML("""
638
  <div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
639
  <div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
 
646
  }
647
  </style>
648
  """, visible=False)
 
649
  submit_button_ko = gr.Button("아이디어 생성하기", variant="primary")
 
650
  with gr.Column(scale=2):
651
  idea_output_ko = gr.Markdown(label="아이디어 결과")
652
  generated_image_ko = gr.Image(label="생성된 디자인 이미지", type="pil")
 
653
  gr.Examples(
654
  examples=[
655
  ["스마트폰", "", "", "센서 기능"],
 
658
  ["드론", "인공지능", "", "물질의 상태 변화"],
659
  ["운동화", "웨어러블", "건강", "구조적 변화"],
660
  ],
661
+ inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko]
662
  )
 
663
  def show_processing_indicator_ko():
664
  return gr.update(visible=True)
 
665
  def hide_processing_indicator_ko():
666
  return gr.update(visible=False)
 
667
  submit_button_ko.click(
668
  fn=show_processing_indicator_ko,
669
  inputs=None,