openfree's picture
Update app.py
1fd6876 verified
raw
history blame
37.2 kB
import os
import gradio as gr
import random
import time
import logging
import google.generativeai as genai
import torch
import numpy as np
from diffusers import DiffusionPipeline
from transformers import pipeline as hf_pipeline
import re
##############################################################################
# 1) ZeroGPU Environment Setup + Device and Dtype Configuration
##############################################################################
try:
import zerogpu
zerogpu.init()
print("ZeroGPU initialized successfully")
device = "cuda" if torch.cuda.is_available() else "cpu"
except ImportError:
print("ZeroGPU package not installed, continuing without it")
if os.getenv("ZERO_GPU"):
print("ZeroGPU environment variable is set but zerogpu package is not installed.")
device = "cuda" if torch.cuda.is_available() else "cpu"
except Exception as e:
print(f"Error initializing ZeroGPU: {e}")
print("Continuing without ZeroGPU")
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.bfloat16 if device == "cuda" else torch.float32
print(f"Using device: {device}, dtype: {dtype}")
##############################################################################
# 2) Load Models: Translation Model, Diffusion Pipeline
##############################################################################
try:
translator = hf_pipeline(
"translation",
model="Helsinki-NLP/opus-mt-ko-en",
device=0 if device == "cuda" else -1
)
pipe = DiffusionPipeline.from_pretrained(
"black-forest-labs/FLUX.1-schnell",
torch_dtype=dtype
).to(device)
print("Models loaded successfully")
except Exception as e:
print(f"Error loading models: {e}")
def dummy_translator(text):
return [{'translation_text': text}]
class DummyPipe:
def __call__(self, **kwargs):
from PIL import Image
import numpy as np
dummy_img = Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8))
class DummyResult:
def __init__(self, img):
self.images = [img]
return DummyResult(dummy_img)
translator = dummy_translator
pipe = DummyPipe()
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 2048
##############################################################################
# Korean detection and input text cleaning functions
##############################################################################
def contains_korean(text):
for char in text:
if ord('κ°€') <= ord(char) <= ord('힣'):
return True
return False
def clean_input_text(text):
"""
Allows only Korean, English, numbers, whitespace and common punctuation marks.
Adjust allowed characters as needed.
"""
allowed = re.compile(r'[^γ„±-γ…Žκ°€-힣a-zA-Z0-9\s\.\,\!\?\-\:\;\'\"]')
cleaned_text = allowed.sub('', text)
return cleaned_text
def log_unexpected_characters(text):
allowed = re.compile(r'[γ„±-γ…Žκ°€-힣a-zA-Z0-9\s\.\,\!\?\-\:\;\'\"]')
unexpected_chars = [char for char in text if not allowed.match(char)]
if unexpected_chars:
print("Unexpected characters found:", set(unexpected_chars))
else:
print("No unexpected characters in the input text.")
##############################################################################
# Image Generation Function
##############################################################################
def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4):
original_prompt = prompt
translated = False
# Clean the input text
prompt = clean_input_text(prompt)
# Pre-process: if input is too long, trim to 1000 characters
if len(prompt) > 1000:
prompt = prompt[:1000]
if contains_korean(prompt):
# When calling translation, add max_length and truncation options to avoid length issues
translation = translator(prompt, max_length=400, truncation=True)
prompt = translation[0]['translation_text']
translated = True
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)
image = pipe(
prompt=prompt,
width=width,
height=height,
num_inference_steps=num_inference_steps,
generator=generator,
guidance_scale=0.0
).images[0]
return image
##############################################################################
# Logging Setup
##############################################################################
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("api_debug.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("idea_generator")
##############################################################################
# Gemini API Key
##############################################################################
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
genai.configure(api_key=GEMINI_API_KEY)
##############################################################################
# Optional Transformation Choice Function
##############################################################################
def choose_alternative(transformation):
if "/" not in transformation:
return transformation
parts = transformation.split("/")
if len(parts) != 2:
return random.choice([part.strip() for part in parts])
left = parts[0].strip()
right = parts[1].strip()
if " " in left:
tokens = left.split(" ", 1)
prefix = tokens[0]
if not right.startswith(prefix):
option1 = left
option2 = prefix + " " + right
else:
option1 = left
option2 = right
return random.choice([option1, option2])
else:
return random.choice([left, right])
##############################################################################
# Transformation Categories Dictionaries
##############################################################################
# Korean version
physical_transformation_categories = {
"μ„Όμ„œ κΈ°λŠ₯": [
"μ‹œκ° μ„Όμ„œ/감지", "청각 μ„Όμ„œ/감지", "촉각 μ„Όμ„œ/감지", "미각 μ„Όμ„œ/감지", "후각 μ„Όμ„œ/감지",
"μ˜¨λ„ μ„Όμ„œ/감지", "μŠ΅λ„ μ„Όμ„œ/감지", "μ••λ ₯ μ„Όμ„œ/감지", "가속도 μ„Όμ„œ/감지", "νšŒμ „ μ„Όμ„œ/감지",
"κ·Όμ ‘ μ„Όμ„œ/감지", "μœ„μΉ˜ μ„Όμ„œ/감지", "μš΄λ™ μ„Όμ„œ/감지", "κ°€μŠ€ μ„Όμ„œ/감지", "적외선 μ„Όμ„œ/감지",
"μžμ™Έμ„  μ„Όμ„œ/감지", "방사선 μ„Όμ„œ/감지", "자기μž₯ μ„Όμ„œ/감지", "μ „κΈ°μž₯ μ„Όμ„œ/감지", "ν™”ν•™λ¬Όμ§ˆ μ„Όμ„œ/감지",
"μƒμ²΄μ‹ ν˜Έ μ„Όμ„œ/감지", "진동 μ„Όμ„œ/감지", "μ†ŒμŒ μ„Όμ„œ/감지", "λΉ› μ„ΈκΈ° μ„Όμ„œ/감지", "λΉ› 파μž₯ μ„Όμ„œ/감지",
"기울기 μ„Όμ„œ/감지", "pH μ„Όμ„œ/감지", "μ „λ₯˜ μ„Όμ„œ/감지", "μ „μ•• μ„Όμ„œ/감지", "이미지 μ„Όμ„œ/감지",
"거리 μ„Όμ„œ/감지", "깊이 μ„Όμ„œ/감지", "쀑λ ₯ μ„Όμ„œ/감지", "속도 μ„Όμ„œ/감지", "흐름 μ„Όμ„œ/감지",
"μˆ˜μœ„ μ„Όμ„œ/감지", "탁도 μ„Όμ„œ/감지", "염도 μ„Όμ„œ/감지", "κΈˆμ† 감지", "μ••μ „ μ„Όμ„œ/감지",
"κ΄‘μ „ μ„Όμ„œ/감지", "μ—΄μ „λŒ€ μ„Όμ„œ/감지", "홀 효과 μ„Όμ„œ/감지", "초음파 μ„Όμ„œ/감지", "λ ˆμ΄λ” μ„Όμ„œ/감지",
"라이닀 μ„Όμ„œ/감지", "ν„°μΉ˜ μ„Όμ„œ/감지", "제슀처 μ„Όμ„œ/감지", "심박 μ„Όμ„œ/감지", "ν˜ˆμ•• μ„Όμ„œ/감지"
],
"크기와 ν˜•νƒœ λ³€ν™”": [
"λΆ€ν”Ό λŠ˜μ–΄λ‚¨/쀄어듦", "길이 λŠ˜μ–΄λ‚¨/쀄어듦", "λ„ˆλΉ„ λŠ˜μ–΄λ‚¨/쀄어듦", "높이 λŠ˜μ–΄λ‚¨/쀄어듦",
"밀도 λ³€ν™”", "무게 증가/κ°μ†Œ", "λͺ¨μ–‘ λ³€ν˜•", "μƒνƒœ λ³€ν™”", "λΆˆκ· λ“± λ³€ν˜•",
"λ³΅μž‘ν•œ ν˜•νƒœ λ³€ν˜•", "λΉ„ν‹€λ¦Ό/κΌ¬μž„", "λΆˆκ· μΌν•œ ν™•μž₯/μΆ•μ†Œ", "λͺ¨μ„œλ¦¬ λ‘₯κΈ€κ²Œ/λ‚ μΉ΄λ‘­κ²Œ",
"깨짐/갈라짐", "μ—¬λŸ¬ 쑰각 λ‚˜λˆ μ§", "λ¬Ό μ €ν•­", "λ¨Όμ§€ μ €ν•­", "찌그러짐/볡원",
"μ ‘νž˜/펼쳐짐", "μ••μ°©/팽창", "λŠ˜μ–΄λ‚¨/μˆ˜μΆ•", "ꡬ겨짐/평평해짐", "λ­‰κ°œμ§/단단해짐",
"말림/펴짐", "κΊΎμž„/κ΅¬λΆ€λŸ¬μ§"
],
"ν‘œλ©΄ 및 μ™Έκ΄€ λ³€ν™”": [
"색상 λ³€ν™”", "질감 λ³€ν™”", "투λͺ…/뢈투λͺ… λ³€ν™”", "λ°˜μ§μž„/무광 λ³€ν™”",
"λΉ› λ°˜μ‚¬ 정도 λ³€ν™”", "무늬 λ³€ν™”", "각도에 λ”°λ₯Έ 색상 λ³€ν™”", "빛에 λ”°λ₯Έ 색상 λ³€ν™”",
"μ˜¨λ„μ— λ”°λ₯Έ 색상 λ³€ν™”", "ν™€λ‘œκ·Έλž¨ 효과", "ν‘œλ©΄ 각도별 λΉ› λ°˜μ‚¬", "ν‘œλ©΄ λͺ¨μ–‘ λ³€ν˜•",
"μ΄ˆλ―Έμ„Έ ν‘œλ©΄ ꡬ쑰 λ³€ν™”", "μžκ°€ μ„Έμ • 효과", "얼룩/νŒ¨ν„΄ 생성", "흐림/μ„ λͺ…함 λ³€ν™”",
"광택/윀기 λ³€ν™”", "색쑰/채도 λ³€ν™”", "λ°œκ΄‘/ν˜•κ΄‘", "λΉ› μ‚°λž€ 효과",
"λΉ› 흑수 λ³€ν™”", "반투λͺ… 효과", "그림자 효과 λ³€ν™”", "μžμ™Έμ„  λ°˜μ‘ λ³€ν™”",
"μ•Όκ΄‘ 효과"
],
"물질의 μƒνƒœ λ³€ν™”": [
"고체/앑체/기체 μ „ν™˜", "κ²°μ •ν™”/μš©ν•΄", "μ‚°ν™”/뢀식", "딱딱해짐/λΆ€λ“œλŸ¬μ›Œμ§",
"특수 μƒνƒœ μ „ν™˜", "λ¬΄μ •ν˜•/κ²°μ •ν˜• μ „ν™˜", "μ„±λΆ„ 뢄리", "λ―Έμ„Έ μž…μž ν˜•μ„±/λΆ„ν•΄",
"μ € ν˜•μ„±/풀어짐", "μ€€μ•ˆμ • μƒνƒœ λ³€ν™”", "λΆ„μž μžκ°€ μ •λ ¬/λΆ„ν•΄", "μƒνƒœλ³€ν™” μ§€μ—° ν˜„μƒ",
"λ…ΉμŒ", "ꡳ음", "증발/응좕", "μŠΉν™”/증착", "μΉ¨μ „/λΆ€μœ ", "λΆ„μ‚°/응집",
"건쑰/슡윀", "팽윀/μˆ˜μΆ•", "동결/해동", "풍화/침식", "μΆ©μ „/λ°©μ „",
"κ²°ν•©/뢄리", "발효/λΆ€νŒ¨"
],
"μ›€μ§μž„ νŠΉμ„± λ³€ν™”": [
"가속/감속", "일정 속도 μœ μ§€", "진동/진동 κ°μ†Œ", "λΆ€λ”ͺ힘/νŠ•κΉ€",
"νšŒμ „ 속도 증가/κ°μ†Œ", "νšŒμ „ λ°©ν–₯ λ³€ν™”", "λΆˆκ·œμΉ™ μ›€μ§μž„", "λ©ˆμ·„λ‹€ λ―Έλ„λŸ¬μ§€λŠ” ν˜„μƒ",
"곡진/λ°˜κ³΅μ§„", "유체 속 μ €ν•­/μ–‘λ ₯ λ³€ν™”", "μ›€μ§μž„ μ €ν•­ λ³€ν™”", "볡합 진동 μ›€μ§μž„",
"특수 유체 속 μ›€μ§μž„", "νšŒμ „-이동 연계 μ›€μ§μž„", "κ΄€μ„± μ •μ§€", "좩격 흑수",
"좩격 전달", "μš΄λ™λŸ‰ 보쑴", "마찰λ ₯ λ³€ν™”", "κ΄€μ„± νƒˆμΆœ", "λΆˆμ•ˆμ • κ· ν˜•",
"동적 μ•ˆμ •μ„±", "흔듀림 감쇠", "경둜 μ˜ˆμΈ‘μ„±", "νšŒν”Ό μ›€μ§μž„"
],
"ꡬ쑰적 λ³€ν™”": [
"λΆ€ν’ˆ μΆ”κ°€/제거", "쑰립/λΆ„ν•΄", "μ ‘κΈ°/펴기", "λ³€ν˜•/원상볡ꡬ", "졜적 ꡬ쑰 λ³€ν™”",
"μžκ°€ μž¬λ°°μ—΄", "μžμ—° νŒ¨ν„΄ ν˜•μ„±/μ†Œλ©Έ", "κ·œμΉ™μ  νŒ¨ν„΄ λ³€ν™”", "λͺ¨λ“ˆμ‹ λ³€ν˜•",
"λ³΅μž‘μ„± 증가 ꡬ쑰", "μ›λž˜ λͺ¨μ–‘ κΈ°μ–΅ 효과", "μ‹œκ°„μ— λ”°λ₯Έ ν˜•νƒœ λ³€ν™”", "λΆ€λΆ„ 제거",
"λΆ€λΆ„ ꡐ체", "κ²°ν•©", "뢄리", "λΆ„ν• /톡합", "쀑첩/κ²ΉμΉ¨", "λ‚΄λΆ€ ꡬ쑰 λ³€ν™”",
"μ™ΈλΆ€ ꡬ쑰 λ³€ν™”", "쀑심좕 이동", "κ· ν˜•μ  λ³€ν™”", "계측 ꡬ쑰 λ³€ν™”", "μ§€μ§€ ꡬ쑰 λ³€ν™”",
"응λ ₯ λΆ„μ‚° ꡬ쑰", "좩격 흑수 ꡬ쑰", "κ·Έλ¦¬λ“œ/맀트릭슀 ꡬ쑰 λ³€ν™”", "μƒν˜Έ μ—°κ²°μ„± λ³€ν™”"
],
"곡간 이동": [
"μ•ž/λ’€ 이동", "쒌/우 이동", "μœ„/μ•„λž˜ 이동", "μ„Έλ‘œμΆ• νšŒμ „(고개 λ„λ•μž„)",
"κ°€λ‘œμΆ• νšŒμ „(고개 μ “κΈ°)", "길이좕 νšŒμ „(μ˜†μœΌλ‘œ κΈ°μšΈμž„)", "원 μš΄λ™", "λ‚˜μ„ ν˜• 이동",
"관성에 μ˜ν•œ λ―Έλ„λŸ¬μ§", "νšŒμ „μΆ• λ³€ν™”", "λΆˆκ·œμΉ™ νšŒμ „", "흔듀림 μš΄λ™", "포물선 이동",
"무쀑λ ₯ λΆ€μœ ", "수면 μœ„ λΆ€μœ ", "점프/도약", "μŠ¬λΌμ΄λ”©", "둀링", "자유 λ‚™ν•˜",
"왕볡 μš΄λ™", "탄성 νŠ•κΉ€", "관톡", "νšŒν”Ό μ›€μ§μž„", "μ§€κ·Έμž¬κ·Έ 이동", "μŠ€μœ™ μš΄λ™"
],
"μ‹œκ°„ κ΄€λ ¨ λ³€ν™”": [
"λ…Έν™”/풍화", "마λͺ¨/뢀식", "색 λ°”λž¨/변색", "손상/회볡", "수λͺ… μ£ΌκΈ° λ³€ν™”",
"μ‚¬μš©μž μƒν˜Έμž‘μš©μ— λ”°λ₯Έ 적응", "ν•™μŠ΅ 기반 ν˜•νƒœ μ΅œμ ν™”", "μ‹œκ°„μ— λ”°λ₯Έ λ¬Όμ„± λ³€ν™”",
"집단 κΈ°μ–΅ 효과", "문화적 의미 λ³€ν™”", "μ§€μ—° λ°˜μ‘", "이전 μƒνƒœ 의쑴 λ³€ν™”",
"점진적 μ‹œκ°„ λ³€ν™”", "진화적 λ³€ν™”", "주기적 μž¬μƒ", "κ³„μ ˆ λ³€ν™” 적응",
"생체리듬 λ³€ν™”", "생애 μ£ΌκΈ° 단계", "μ„±μž₯/퇴화", "자기 볡ꡬ/μž¬μƒ",
"μžμ—° μˆœν™˜ 적응", "지속성/μΌμ‹œμ„±", "κΈ°μ–΅ 효과", "μ§€μ—°λœ μž‘μš©", "λˆ„μ  효과"
],
"λΉ›κ³Ό μ‹œκ° 효과": [
"λ°œκ΄‘/μ†Œλ“±", "λΉ› 투과/차단", "λΉ› μ‚°λž€/집쀑", "색상 μŠ€νŽ™νŠΈλŸΌ λ³€ν™”", "λΉ› 회절",
"λΉ› κ°„μ„­", "ν™€λ‘œκ·Έλž¨ 생성", "λ ˆμ΄μ € 효과", "λΉ› νŽΈκ΄‘", "ν˜•κ΄‘/인광",
"μžμ™Έμ„ /적외선 λ°œκ΄‘", "광학적 μ°©μ‹œ", "λΉ› ꡴절", "그림자 생성/제거",
"μƒ‰μˆ˜μ°¨ 효과", "λ¬΄μ§€κ°œ 효과", "κΈ€λ‘œμš° 효과", "ν”Œλž˜μ‹œ 효과", "μ‘°λͺ… νŒ¨ν„΄",
"λΉ” 효과", "κ΄‘ ν•„ν„° 효과", "λΉ›μ˜ λ°©ν–₯μ„± λ³€ν™”", "투영 효과", "λΉ› 감지/λ°˜μ‘",
"광도 λ³€ν™”"
],
"μ†Œλ¦¬μ™€ 진동 효과": [
"Sound generation/cessation", "Pitch change", "Volume change", "Timbre change",
"Resonance/antiresonance", "Acoustic vibration", "Ultrasonic/infrasonic emission", "Sound concentration/distribution",
"Sound reflection/absorption", "Acoustic Doppler effect", "Sound wave interference", "Acoustic resonance",
"Vibration pattern change", "Percussive effect", "Audio feedback", "Sound shielding/amplification",
"Directional sound", "Sound distortion", "Beat generation", "Harmonics generation", "Frequency modulation",
"Acoustic shockwave", "Sound filtering"
],
"Thermal Changes": [
"Temperature rise/fall", "Thermal expansion/contraction", "Heat transfer/blocking", "Pressure increase/decrease",
"Magnetization due to heat change", "Entropy change", "Thermoelectric effect", "Magnetic-induced thermal change",
"Heat storage/release during phase change", "Thermal stress buildup/release", "Impact of rapid temperature change",
"Radiative cooling/heating", "Exothermic/endothermic", "Heat distribution change", "Heat reflection/absorption",
"Cooling condensation", "Thermal activation", "Thermal discoloration", "Coefficient of thermal expansion change", "Thermal stability change",
"Heat resistance/cold resistance", "Self-heating", "Thermal equilibrium/imbalance", "Thermal deformation", "Heat dispersion/concentration"
],
"Electrical and Magnetic Changes": [
"Magnetism creation/cessation", "Charge increase/decrease", "Electric field creation/cessation", "Magnetic field creation/cessation",
"Superconducting transition", "Ferroelectric property change", "Quantum state change", "Plasma formation/cessation",
"Spin wave transmission", "Electricity generation by light", "Electricity generation by pressure", "Current change in magnetic field",
"Electrical resistance change", "Electrical conductivity change", "Static electricity generation/discharge", "Electromagnetic induction",
"Electromagnetic wave emission/absorption", "Capacitance change", "Magnetic hysteresis", "Electrical polarization",
"Electron flow direction change", "Electrical resonance", "Electrical shielding/exposure", "Magnetic shielding/exposure",
"Magnetic field alignment"
],
"Chemical Change": [
"Surface coating change", "Material composition change", "Chemical reaction change", "Catalytic action start/stop",
"Light-induced chemical reaction", "Electricity-induced chemical reaction", "Monolayer formation", "Molecular-level structural change",
"Biomimetic surface change", "Environmentally responsive material change", "Periodic chemical reaction", "Oxidation", "Reduction",
"Polymerization", "Water splitting", "Compound formation", "Radiation effects", "Acid-base reaction", "Neutralization reaction",
"Ionization", "Chemical adsorption/desorption", "Catalytic efficiency change", "Enzyme activity change", "Colorimetric reaction",
"pH change", "Chemical equilibrium shift", "Bond formation/breakage", "Solubility change"
],
"Biological Change": [
"Growth/shrinkage", "Cell division/death", "Bioluminescence", "Metabolic change", "Immune response",
"Hormone secretion", "Neural response", "Genetic expression", "Adaptation/evolution", "Circadian rhythm change",
"Regeneration/healing", "Aging/maturation", "Biomimetic change", "Biofilm formation", "Biological degradation",
"Enzyme activation/inactivation", "Biological signaling", "Stress response", "Thermoregulation", "Biological clock change",
"Extracellular matrix change", "Biomechanical response", "Cell motility", "Cell polarity change", "Nutritional status change"
],
"Environmental Interaction": [
"Temperature response", "Humidity response", "Pressure response", "Gravity response", "Magnetic field response",
"Light response", "Sound response", "Chemical detection", "Mechanical stimulus detection", "Electrical stimulus response",
"Radiation response", "Vibration detection", "pH response", "Solvent response", "Gas exchange",
"Pollution response", "Weather response", "Seasonal response", "Circadian response", "Ecosystem interaction",
"Symbiotic/competitive interaction", "Predator/prey relationship", "Swarm formation", "Territorial behavior", "Migration/settlement pattern"
]
}
##############################################################################
# Gemini API Call Function (Language Independent)
##############################################################################
def query_gemini_api(prompt):
try:
model = genai.GenerativeModel('gemini-2.0-flash-thinking-exp-01-21')
response = model.generate_content(prompt)
try:
if hasattr(response, 'text'):
return response.text
if hasattr(response, 'candidates') and response.candidates:
candidate = response.candidates[0]
if hasattr(candidate, 'content'):
content = candidate.content
if hasattr(content, 'parts') and content.parts:
if len(content.parts) > 0:
return content.parts[0].text
if hasattr(response, 'parts') and response.parts:
if len(response.parts) > 0:
return response.parts[0].text
return "Unable to generate a response. API response structure is different than expected."
except Exception as inner_e:
logger.error(f"Error processing response: {inner_e}")
return f"An error occurred while processing the response: {str(inner_e)}"
except Exception as e:
logger.error(f"Error calling Gemini API: {e}")
if "API key not valid" in str(e):
return "API key is not valid. Please check your GEMINI_API_KEY environment variable."
return f"An error occurred while calling the API: {str(e)}"
##############################################################################
# Description Expansion Functions (LLM) - Korean and English Versions
##############################################################################
def enhance_with_llm(base_description, obj_name, category):
prompt = f"""
λ‹€μŒμ€ '{obj_name}'의 '{category}' κ΄€λ ¨ κ°„λ‹¨ν•œ μ„€λͺ…μž…λ‹ˆλ‹€:
"{base_description}"
μœ„ λ‚΄μš©μ„ 보닀 κ΅¬μ²΄ν™”ν•˜μ—¬,
1) 창의적인 λͺ¨λΈ/컨셉/ν˜•μƒμ˜ 변화에 λŒ€ν•œ 이해,
2) ν˜μ‹  ν¬μΈνŠΈμ™€ κΈ°λŠ₯μ„± 등을 μ€‘μ‹¬μœΌλ‘œ
3~4λ¬Έμž₯의 μ•„μ΄λ””μ–΄λ‘œ ν™•μž₯ν•΄ μ£Όμ„Έμš”.
"""
return query_gemini_api(prompt)
def enhance_with_llm_en(base_description, obj_name, category):
prompt = f"""
Below is a brief description related to '{category}' for '{obj_name}':
"{base_description}"
Please expand the above content into a more detailed explanation, focusing on:
1) Creative transformation of the model/concept/shape,
2) Innovative aspects and functionality,
in 3-4 sentences.
"""
return query_gemini_api(prompt)
##############################################################################
# Transformation Idea Generation Functions for Both Languages
##############################################################################
def generate_single_object_transformation_for_category_lang(obj, selected_category, categories_dict, lang="ko"):
transformations = categories_dict.get(selected_category)
if not transformations:
return {}
transformation = choose_alternative(random.choice(transformations))
if lang == "ko":
base_description = f"{obj}이(κ°€) {transformation} ν˜„μƒμ„ 보인닀"
else:
base_description = f"{obj} exhibits {transformation}"
return {selected_category: {"base": base_description, "enhanced": None}}
def generate_two_objects_interaction_for_category_lang(obj1, obj2, selected_category, categories_dict, lang="ko"):
transformations = categories_dict.get(selected_category)
if not transformations:
return {}
transformation = choose_alternative(random.choice(transformations))
if lang == "ko":
template = random.choice([
"{obj1}이(κ°€) {obj2}에 κ²°ν•©ν•˜μ—¬ {change}κ°€ λ°œμƒν–ˆλ‹€",
"{obj1}κ³Ό(와) {obj2}이(κ°€) μΆ©λŒν•˜λ©΄μ„œ {change}κ°€ 일어났닀"
])
else:
template = random.choice([
"{obj1} combined with {obj2} resulted in {change}",
"A collision between {obj1} and {obj2} led to {change}"
])
base_description = template.format(obj1=obj1, obj2=obj2, change=transformation)
return {selected_category: {"base": base_description, "enhanced": None}}
def generate_three_objects_interaction_for_category_lang(obj1, obj2, obj3, selected_category, categories_dict, lang="ko"):
transformations = categories_dict.get(selected_category)
if not transformations:
return {}
transformation = choose_alternative(random.choice(transformations))
if lang == "ko":
template = random.choice([
"{obj1}, {obj2}, {obj3}이(κ°€) μ‚Όκ°ν˜• ꡬ쑰둜 κ²°ν•©ν•˜μ—¬ {change}κ°€ λ°œμƒν–ˆλ‹€",
"{obj1}이(κ°€) {obj2}와(κ³Ό) {obj3} μ‚¬μ΄μ—μ„œ 맀개체 역할을 ν•˜λ©° {change}λ₯Ό μ΄‰μ§„ν–ˆλ‹€"
])
else:
template = random.choice([
"{obj1}, {obj2}, and {obj3} formed a triangular structure resulting in {change}",
"{obj1} acted as an intermediary between {obj2} and {obj3}, facilitating {change}"
])
base_description = template.format(obj1=obj1, obj2=obj2, obj3=obj3, change=transformation)
return {selected_category: {"base": base_description, "enhanced": None}}
def enhance_descriptions_lang(results, objects, lang="ko"):
obj_name = " 및 ".join([obj for obj in objects if obj]) if lang=="ko" else " and ".join([obj for obj in objects if obj])
for category, result in results.items():
if lang == "ko":
result["enhanced"] = enhance_with_llm(result["base"], obj_name, category)
else:
result["enhanced"] = enhance_with_llm_en(result["base"], obj_name, category)
return results
def generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang="ko"):
if text2 and text3:
results = generate_three_objects_interaction_for_category_lang(text1, text2, text3, selected_category, categories_dict, lang)
objects = [text1, text2, text3]
elif text2:
results = generate_two_objects_interaction_for_category_lang(text1, text2, selected_category, categories_dict, lang)
objects = [text1, text2]
else:
results = generate_single_object_transformation_for_category_lang(text1, selected_category, categories_dict, lang)
objects = [text1]
return enhance_descriptions_lang(results, objects, lang)
def format_results_lang(results, lang="ko"):
formatted = ""
if lang == "ko":
for category, result in results.items():
formatted += f"## {category}\n**κΈ°λ³Έ 아이디어**: {result['base']}\n\n**ν™•μž₯된 아이디어**: {result['enhanced']}\n\n---\n\n"
else:
for category, result in results.items():
formatted += f"## {category}\n**Base Idea**: {result['base']}\n\n**Expanded Idea**: {result['enhanced']}\n\n---\n\n"
return formatted
def process_inputs_lang(text1, text2, text3, selected_category, categories_dict, lang="ko", progress=gr.Progress()):
text1 = text1.strip() if text1 else None
text2 = text2.strip() if text2 else None
text3 = text3.strip() if text3 else None
if not text1:
return "였λ₯˜: μ΅œμ†Œ ν•˜λ‚˜μ˜ ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”." if lang=="ko" else "Error: Please enter at least one keyword."
if lang == "ko":
progress(0.05, desc="아이디어 생성 μ€€λΉ„ 쀑...")
time.sleep(0.3)
progress(0.1, desc="창의적인 아이디어 생성 μ‹œμž‘...")
else:
progress(0.05, desc="Preparing idea generation...")
time.sleep(0.3)
progress(0.1, desc="Generating creative idea...")
results = generate_transformations_lang(text1, text2, text3, selected_category, categories_dict, lang)
if lang == "ko":
progress(0.8, desc="κ²°κ³Ό ν¬λ§·νŒ… 쀑...")
formatted = format_results_lang(results, lang)
progress(1.0, desc="μ™„λ£Œ!")
else:
progress(0.8, desc="Formatting results...")
formatted = format_results_lang(results, lang)
progress(1.0, desc="Done!")
return formatted
def process_all_lang(text1, text2, text3, selected_category, categories_dict, lang="ko", progress=gr.Progress()):
idea_result = process_inputs_lang(text1, text2, text3, selected_category, categories_dict, lang, progress)
image_result = generate_design_image(
idea_result,
seed=42,
randomize_seed=True,
width=1024,
height=1024,
num_inference_steps=4
)
return idea_result, image_result
##############################################################################
# Warning Message Function for API Key (Language Specific)
##############################################################################
def get_warning_message_lang(lang="ko"):
if not GEMINI_API_KEY:
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."
return ""
##############################################################################
# Add "Business Ideas" category to each dictionary
##############################################################################
physical_transformation_categories["λΉ„μ¦ˆλ‹ˆμŠ€ 아이디어"] = [
"μ‹œμž₯ μž¬μ •μ˜/μ‹ κ·œ μ‹œμž₯ κ°œμ²™",
"λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ ν˜μ‹ /λ””μ§€ν„Έ μ „ν™˜",
"고객 κ²½ν—˜ ν˜μ‹ /μ„œλΉ„μŠ€ ν˜μ‹ ",
"ν˜‘λ ₯ 및 νŒŒνŠΈλ„ˆμ‹­ κ°•ν™”/μƒνƒœκ³„ ꡬ좕",
"κΈ€λ‘œλ²Œ ν™•μž₯/μ§€μ—­ν™” μ „λž΅",
"운영 νš¨μœ¨μ„± μ¦λŒ€/원가 절감",
"λΈŒλžœλ“œ 리포지셔닝/이미지 μ „ν™˜",
"지속 κ°€λŠ₯ν•œ μ„±μž₯/μ‚¬νšŒμ  κ°€μΉ˜ 창좜",
"데이터 기반 μ˜μ‚¬κ²°μ •/AI λ„μž…",
"μ‹ κΈ°μˆ  μœ΅ν•©/ν˜μ‹  투자"
]
physical_transformation_categories_en["Business Ideas"] = [
"Market redefinition/new market creation",
"Business model innovation/digital transformation",
"Customer experience and service innovation",
"Enhanced partnerships and ecosystem building",
"Global expansion and localization strategy",
"Operational efficiency improvement/cost reduction",
"Brand repositioning/image transformation",
"Sustainable growth and social value creation",
"Data-driven decision making/AI adoption",
"Convergence of new technologies/innovative investments"
]
##############################################################################
# Helper function for caching examples in the English tab
##############################################################################
def process_all_lang_example(text1, text2, text3, selected_category):
# κ³ μ •λœ stateκ°’(physical_transformation_categories_en, "en")으둜 호좜
return process_all_lang(text1, text2, text3, selected_category, physical_transformation_categories_en, "en")
##############################################################################
# Gradio UI with Two Tabs: English (Main Home) and Korean
##############################################################################
with gr.Blocks(
title="Idea Transformer",
theme=gr.themes.Soft(primary_hue="teal", secondary_hue="slate", neutral_hue="neutral")
) as demo:
gr.HTML("""
<style>
body {
background: linear-gradient(135deg, #e0eafc, #cfdef3);
font-family: 'Arial', sans-serif;
}
.gradio-container {
padding: 20px;
}
h1, h2 {
text-align: center;
}
h1 {
color: #333;
}
h2 {
color: #555;
}
.output {
background-color: #ffffff;
padding: 15px;
border-radius: 8px;
}
.gr-button {
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
padding: 8px 16px;
}
.progress-message {
color: #2196F3;
font-weight: bold;
margin-top: 10px;
}
</style>
""")
with gr.Tabs():
with gr.Tab(label="English"):
gr.Markdown("# πŸš€ Idea Transformer")
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")
warning_en = gr.Markdown(get_warning_message_lang("en"))
with gr.Row():
with gr.Column(scale=1):
text_input1_en = gr.Textbox(label="Keyword 1 (required)", placeholder="e.g., Smartphone")
text_input2_en = gr.Textbox(label="Keyword 2 (optional)", placeholder="e.g., Artificial Intelligence")
text_input3_en = gr.Textbox(label="Keyword 3 (optional)", placeholder="e.g., Healthcare")
category_radio_en = gr.Radio(
label="Select Category",
choices=list(physical_transformation_categories_en.keys()),
value=list(physical_transformation_categories_en.keys())[0],
info="Select a category."
)
status_msg_en = gr.Markdown("πŸ’‘ Click the 'Generate Idea' button to create an idea and design image based on the selected category.")
processing_indicator_en = gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
<div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
<p style="margin-left: 10px; font-weight: bold; color: #3498db;">Processing...</p>
</div>
<style>
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
""", visible=False)
submit_button_en = gr.Button("Generate Idea", variant="primary")
with gr.Column(scale=2):
idea_output_en = gr.Markdown(label="Idea Output")
generated_image_en = gr.Image(label="Generated Design Image", type="pil")
gr.Examples(
examples=[
["Smartphone", "", "", "Sensor Functions"],
["Car", "", "", "Size and Shape Change"],
["Car", "Artificial Intelligence", "", "Surface and Appearance Change"],
["Drone", "Artificial Intelligence", "", "Material State Change"],
["Sneakers", "Wearable", "Health", "Structural Change"],
],
inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en],
fn=process_all_lang_example,
outputs=[idea_output_en, generated_image_en],
cache_examples=True
)
def show_processing_indicator_en():
return gr.update(visible=True)
def hide_processing_indicator_en():
return gr.update(visible=False)
submit_button_en.click(
fn=show_processing_indicator_en,
inputs=None,
outputs=processing_indicator_en
).then(
fn=process_all_lang,
inputs=[text_input1_en, text_input2_en, text_input3_en, category_radio_en, gr.State(physical_transformation_categories_en), gr.State("en")],
outputs=[idea_output_en, generated_image_en]
).then(
fn=hide_processing_indicator_en,
inputs=None,
outputs=processing_indicator_en
)
with gr.Tab(label="ν•œκ΅­μ–΄"):
gr.Markdown("# πŸš€ 아이디어 트랜슀포머")
gr.Markdown("μž…λ ₯ν•œ **ν‚€μ›Œλ“œ**(μ΅œλŒ€ 3개)와 **μΉ΄ν…Œκ³ λ¦¬**λ₯Ό λ°”νƒ•μœΌλ‘œ, 창의적인 λͺ¨λΈ/컨셉/ν˜•μƒ λ³€ν™” 아이디어λ₯Ό μƒμ„±ν•˜κ³ , ν•΄λ‹Ή ν™•μž₯ 아이디어λ₯Ό ν”„λ‘¬ν”„νŠΈλ‘œ ν•˜μ—¬ λ””μžμΈ 이미지λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€. https://discord.gg/openfreeai")
warning_ko = gr.Markdown(get_warning_message_lang("ko"))
with gr.Row():
with gr.Column(scale=1):
text_input1_ko = gr.Textbox(label="ν‚€μ›Œλ“œ 1 (ν•„μˆ˜)", placeholder="예: 슀마트폰")
text_input2_ko = gr.Textbox(label="ν‚€μ›Œλ“œ 2 (선택)", placeholder="예: 인곡지λŠ₯")
text_input3_ko = gr.Textbox(label="ν‚€μ›Œλ“œ 3 (선택)", placeholder="예: ν—¬μŠ€μΌ€μ–΄")
category_radio_ko = gr.Radio(
label="μΉ΄ν…Œκ³ λ¦¬ 선택",
choices=list(physical_transformation_categories.keys()),
value=list(physical_transformation_categories.keys())[0],
info="좜λ ₯ν•  μΉ΄ν…Œκ³ λ¦¬λ₯Ό μ„ νƒν•˜μ„Έμš”."
)
status_msg_ko = gr.Markdown("πŸ’‘ '아이디어 μƒμ„±ν•˜κΈ°' λ²„νŠΌμ„ ν΄λ¦­ν•˜λ©΄ μ„ νƒν•œ μΉ΄ν…Œκ³ λ¦¬μ— ν•΄λ‹Ήν•˜λŠ” 아이디어와 λ””μžμΈ 이미지가 μƒμ„±λ©λ‹ˆλ‹€.")
processing_indicator_ko = gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; margin: 10px 0;">
<div style="border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite;"></div>
<p style="margin-left: 10px; font-weight: bold; color: #3498db;">처리 μ€‘μž…λ‹ˆλ‹€...</p>
</div>
<style>
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
""", visible=False)
submit_button_ko = gr.Button("아이디어 μƒμ„±ν•˜κΈ°", variant="primary")
with gr.Column(scale=2):
idea_output_ko = gr.Markdown(label="아이디어 κ²°κ³Ό")
generated_image_ko = gr.Image(label="μƒμ„±λœ λ””μžμΈ 이미지", type="pil")
gr.Examples(
examples=[
["슀마트폰", "", "", "μ„Όμ„œ κΈ°λŠ₯"],
["μžλ™μ°¨", "", "", "크기와 ν˜•νƒœ λ³€ν™”"],
["μžλ™μ°¨", "인곡지λŠ₯", "", "ν‘œλ©΄ 및 μ™Έκ΄€ λ³€ν™”"],
["λ“œλ‘ ", "인곡지λŠ₯", "", "물질의 μƒνƒœ λ³€ν™”"],
["μš΄λ™ν™”", "μ›¨μ–΄λŸ¬λΈ”", "건강", "ꡬ쑰적 λ³€ν™”"],
],
inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko]
)
def show_processing_indicator_ko():
return gr.update(visible=True)
def hide_processing_indicator_ko():
return gr.update(visible=False)
submit_button_ko.click(
fn=show_processing_indicator_ko,
inputs=None,
outputs=processing_indicator_ko
).then(
fn=process_all_lang,
inputs=[text_input1_ko, text_input2_ko, text_input3_ko, category_radio_ko, gr.State(physical_transformation_categories), gr.State("ko")],
outputs=[idea_output_ko, generated_image_ko]
).then(
fn=hide_processing_indicator_ko,
inputs=None,
outputs=processing_indicator_ko
)
if __name__ == "__main__":
demo.launch(debug=True)