Spaces:
Running
on
Zero
Running
on
Zero
import gradio as gr | |
import numpy as np | |
import random | |
import torch | |
from diffusers import DiffusionPipeline | |
import warnings | |
import os | |
from datetime import datetime | |
import uuid | |
# κ²½κ³ λ©μμ§ μ¨κΈ°κΈ° | |
warnings.filterwarnings('ignore', category=UserWarning) | |
# μ μ₯ λλ ν 리 μμ± | |
SAVE_DIR = "saved_images" | |
if not os.path.exists(SAVE_DIR): | |
os.makedirs(SAVE_DIR, exist_ok=True) | |
# μ₯μΉ λ° dtype μ€μ | |
dtype = torch.float32 if torch.cuda.is_available() else torch.float32 | |
device = "cuda" if torch.cuda.is_available() else "cpu" | |
# λͺ¨λΈ λ‘λ | |
pipe = DiffusionPipeline.from_pretrained( | |
"black-forest-labs/FLUX.1-schnell", | |
torch_dtype=dtype, | |
device_map="auto", | |
use_safetensors=True | |
).to(device) | |
# λ©λͺ¨λ¦¬ μ΅μ ν | |
pipe.enable_attention_slicing() | |
if device == "cpu": | |
pipe.enable_sequential_cpu_offload() | |
MAX_SEED = np.iinfo(np.int32).max | |
MAX_IMAGE_SIZE = 2048 | |
def generate_diagram(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4): | |
"""FLUX AIλ₯Ό μ¬μ©νμ¬ λ€μ΄μ΄κ·Έλ¨ μμ±""" | |
try: | |
if randomize_seed: | |
seed = random.randint(0, MAX_SEED) | |
generator = torch.Generator(device=device).manual_seed(seed) | |
with torch.no_grad(): | |
image = pipe( | |
prompt=prompt, | |
width=width, | |
height=height, | |
num_inference_steps=num_inference_steps, | |
generator=generator, | |
guidance_scale=0.0 | |
).images[0] | |
# μ΄λ―Έμ§ μ μ₯ | |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
unique_id = str(uuid.uuid4())[:8] | |
filename = f"diagram_{timestamp}_{unique_id}.png" | |
save_path = os.path.join(SAVE_DIR, filename) | |
image.save(save_path) | |
return image, seed | |
except Exception as e: | |
raise gr.Error(f"λ€μ΄μ΄κ·Έλ¨ μμ± μ€ μ€λ₯ λ°μ: {str(e)}") | |
finally: | |
if torch.cuda.is_available(): | |
torch.cuda.empty_cache() | |
# Enhanced examples with more detailed prompts and specific styling | |
EXAMPLES = [ | |
{ | |
"title": "Knowledge Tree", | |
"prompt": """A handrawn colorful mind map diagram, educational style, vibrant colors, clear hierarchy, golden ratio layout. | |
KNOWLEDGE | |
βββ ACQUISITION [Brain with Lightning ~60px] | |
β βββ READING [Open Book with Glow] | |
β βββ PRACTICE [Hands-on Tools] | |
β βββ OBSERVATION [Eye with Magnifier] | |
βββ PROCESSING [Gear Network ~50px] | |
β βββ ANALYSIS [Graph Trending Up] | |
β βββ SYNTHESIS [Puzzle Pieces] | |
βββ RETENTION [Memory Chip ~45px] | |
β βββ SHORT-TERM [Quick Flash] | |
β βββ LONG-TERM [Solid Archive] | |
βββ APPLICATION | |
βββ CREATION [Artist Palette] | |
βββ INNOVATION [Lightbulb Constellation]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Digital Transformation", | |
"prompt": """A handrawn colorful mind map diagram, tech-focused style, neon accents, circuit board patterns. | |
DIGITAL TRANSFORM | |
βββ CLOUD [Cloud with Data Rain ~55px] | |
β βββ STORAGE [Database Cluster] | |
β βββ COMPUTING [Server Array] | |
βββ AUTOMATION [Robot Arm ~50px] | |
β βββ WORKFLOWS [Flowchart] | |
β βββ AI/ML [Neural Network] | |
βββ SECURITY [Shield Matrix ~45px] | |
β βββ ENCRYPTION [Lock Code] | |
β βββ MONITORING [Radar Screen] | |
βββ INTEGRATION | |
βββ APIS [Puzzle Connect] | |
βββ MICROSERVICES [Building Blocks]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Creative Process", | |
"prompt": """A handrawn colorful mind map diagram, artistic style, watercolor effects, flowing connections. | |
CREATIVITY | |
βββ INSPIRATION [Constellation Stars ~60px] | |
β βββ NATURE [Organic Patterns] | |
β βββ CULTURE [Global Icons] | |
βββ IDEATION [Floating Bubbles ~50px] | |
β βββ BRAINSTORM [Thunder Cloud] | |
β βββ REFINEMENT [Diamond Polish] | |
βββ EXECUTION [Artist Tools ~45px] | |
β βββ TECHNIQUE [Skilled Hands] | |
β βββ MEDIUM [Palette Mix] | |
βββ PRESENTATION | |
βββ GALLERY [Frame Display] | |
βββ FEEDBACK [Echo Ripples]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Future Cities", | |
"prompt": """A handrawn colorful mind map diagram, futuristic style, holographic elements, sustainable themes. | |
SMART CITY | |
βββ MOBILITY [Hover Transport ~60px] | |
β βββ AUTONOMOUS [Self-Driving] | |
β βββ CONNECTED [Network Grid] | |
βββ ENERGY [Solar Crystal ~55px] | |
β βββ RENEWABLE [Green Power] | |
β βββ STORAGE [Battery Hub] | |
βββ LIVING [Eco Building ~50px] | |
β βββ VERTICAL [Sky Gardens] | |
β βββ COMMUNITY [People Connect] | |
βββ INFRASTRUCTURE | |
βββ AI GRID [Neural City] | |
βββ ECO SYSTEM [Nature Tech]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Health Evolution", | |
"prompt": """A handrawn colorful mind map diagram, medical style, DNA helix patterns, wellness focus. | |
HEALTH 3.0 | |
βββ PREVENTION [Shield DNA ~60px] | |
β βββ LIFESTYLE [Activity Pulse] | |
β βββ MONITORING [Health Watch] | |
βββ TREATMENT [Caduceus Tech ~55px] | |
β βββ PERSONALIZED [DNA Code] | |
β βββ REGENERATIVE [Cell Renew] | |
βββ ENHANCEMENT [Upgrade Spiral ~50px] | |
β βββ COGNITIVE [Brain Boost] | |
β βββ PHYSICAL [Body Optimize] | |
βββ INTEGRATION | |
βββ AI HEALTH [Smart Doctor] | |
βββ COMMUNITY [Global Care]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Space Exploration", | |
"prompt": """A handrawn colorful mind map diagram, cosmic style, star field background, planetary elements. | |
SPACE FRONTIER | |
βββ DISCOVERY [Telescope Array ~60px] | |
β βββ MAPPING [Star Charts] | |
β βββ ANALYSIS [Data Stream] | |
βββ TRAVEL [Rocket Launch ~55px] | |
β βββ PROPULSION [Energy Core] | |
β βββ NAVIGATION [Space Map] | |
βββ COLONIZATION [Dome City ~50px] | |
β βββ HABITATS [Life Sphere] | |
β βββ RESOURCES [Mine Extract] | |
βββ RESEARCH | |
βββ ASTROBIOLOGY [Life Search] | |
βββ PHYSICS [Space Time]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Ocean Innovation", | |
"prompt": """A handrawn colorful mind map diagram, marine style, wave patterns, aqua themes. | |
OCEAN TECH | |
βββ EXPLORATION [Deep Submersible ~60px] | |
β βββ MAPPING [Sonar Wave] | |
β βββ RESEARCH [Lab Bubble] | |
βββ CONSERVATION [Marine Life ~55px] | |
β βββ PROTECTION [Reef Shield] | |
β βββ RESTORATION [Growth Core] | |
βββ HARVESTING [Sustainable Net ~50px] | |
β βββ ENERGY [Wave Power] | |
β βββ RESOURCES [Bio Extract] | |
βββ MONITORING | |
βββ AI SYSTEMS [Smart Sensors] | |
βββ ECOLOGY [Life Web]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Quantum Computing", | |
"prompt": """A handrawn colorful mind map diagram, quantum style, wave-particle duality, matrix patterns. | |
QUANTUM TECH | |
βββ COMPUTATION [Qubit Matrix ~60px] | |
β βββ PROCESSING [Wave Function] | |
β βββ ALGORITHMS [Code Quantum] | |
βββ APPLICATIONS [Use Cases ~55px] | |
β βββ SIMULATION [Model World] | |
β βββ OPTIMIZATION [Peak Find] | |
βββ INFRASTRUCTURE [Q-Hardware ~50px] | |
β βββ CONTROL [Pulse Shape] | |
β βββ COOLING [Zero Point] | |
βββ DEVELOPMENT | |
βββ SOFTWARE [Q-Code Web] | |
βββ INTEGRATION [Classical Bridge]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "Bio Engineering", | |
"prompt": """A handrawn colorful mind map diagram, biological style, DNA patterns, organic flow. | |
BIOTECH | |
βββ GENETICS [DNA Helix ~60px] | |
β βββ EDITING [CRISPR Tool] | |
β βββ SYNTHESIS [Gene Build] | |
βββ APPLICATIONS [Lab Array ~55px] | |
β βββ MEDICINE [Heal Cell] | |
β βββ AGRICULTURE [Grow Plus] | |
βββ PLATFORMS [Bio Factory ~50px] | |
β βββ SENSORS [Live Detect] | |
β βββ PROCESSORS [Cell Compute] | |
βββ INTEGRATION | |
βββ AI BIOLOGY [Smart Life] | |
βββ ECOSYSTEM [Nature Net]""", | |
"width": 1024, | |
"height": 1024 | |
}, | |
{ | |
"title": "AI Evolution", | |
"prompt": """A handrawn colorful mind map diagram, neural network style, digital patterns, intelligence flow. | |
AI FUTURE | |
βββ COGNITION [Brain Network ~60px] | |
β βββ LEARNING [Growth Path] | |
β βββ REASONING [Logic Tree] | |
βββ PERCEPTION [Sensor Array ~55px] | |
β βββ VISION [Eye Matrix] | |
β βββ LANGUAGE [Word Web] | |
βββ INTERACTION [Connect Hub ~50px] | |
β βββ HUMAN [Bridge Link] | |
β βββ MACHINE [Code Path] | |
βββ EVOLUTION | |
βββ CONSCIOUSNESS [Mind Spark] | |
βββ CREATIVITY [Art Core]""", | |
"width": 1024, | |
"height": 1024 | |
} | |
] | |
# Convert examples to Gradio format | |
GRADIO_EXAMPLES = [ | |
[example["prompt"], example["width"], example["height"]] | |
for example in EXAMPLES | |
] | |
def generate_diagram(prompt, width=1024, height=1024): | |
"""FLUX AIλ₯Ό μ¬μ©νμ¬ λ€μ΄μ΄κ·Έλ¨ μμ±""" | |
try: | |
# μλ μ€μ | |
seed = random.randint(0, MAX_SEED) | |
generator = torch.Generator(device=device).manual_seed(seed) | |
# μ΄λ―Έμ§ μμ± | |
image = pipeline( | |
prompt=prompt, | |
width=width, | |
height=height, | |
num_inference_steps=4, | |
generator=generator, | |
).images[0] | |
# μ΄λ―Έμ§ μ μ₯ | |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
unique_id = str(uuid.uuid4())[:8] | |
filename = f"diagram_{timestamp}_{unique_id}.png" | |
save_path = os.path.join(SAVE_DIR, filename) | |
image.save(save_path) | |
return image | |
except Exception as e: | |
raise gr.Error(f"λ€μ΄μ΄κ·Έλ¨ μμ± μ€ μ€λ₯ λ°μ: {str(e)}") | |
# CSS μ€νμΌ | |
css=""" | |
#col-container { | |
margin: 0 auto; | |
max-width: 520px; | |
} | |
""" | |
# Gradio μΈν°νμ΄μ€ μμ± | |
with gr.Blocks(css=css) as demo: | |
with gr.Column(elem_id="col-container"): | |
gr.Markdown("""# FLUX λ€μ΄μ΄κ·Έλ¨ μμ±κΈ° | |
FLUX AIλ₯Ό μ¬μ©νμ¬ μλ¦λ€μ΄ μκ·Έλ¦Ό μ€νμΌμ λ€μ΄μ΄κ·Έλ¨μ μμ±ν©λλ€ | |
""") | |
with gr.Row(): | |
prompt = gr.Text( | |
label="ν둬ννΈ", | |
show_label=False, | |
max_lines=1, | |
placeholder="λ€μ΄μ΄κ·Έλ¨ ꡬ쑰λ₯Ό μ λ ₯νμΈμ...", | |
container=False, | |
) | |
run_button = gr.Button("μμ±", scale=0) | |
result = gr.Image(label="μμ±λ λ€μ΄μ΄κ·Έλ¨", show_label=False) | |
with gr.Accordion("κ³ κΈ μ€μ ", open=False): | |
seed = gr.Slider( | |
label="μλ", | |
minimum=0, | |
maximum=MAX_SEED, | |
step=1, | |
value=0, | |
) | |
randomize_seed = gr.Checkbox(label="λλ€ μλ", value=True) | |
with gr.Row(): | |
width = gr.Slider( | |
label="λλΉ", | |
minimum=256, | |
maximum=MAX_IMAGE_SIZE, | |
step=32, | |
value=1024, | |
) | |
height = gr.Slider( | |
label="λμ΄", | |
minimum=256, | |
maximum=MAX_IMAGE_SIZE, | |
step=32, | |
value=1024, | |
) | |
num_inference_steps = gr.Slider( | |
label="μΆλ‘ λ¨κ³ μ", | |
minimum=1, | |
maximum=50, | |
step=1, | |
value=4, | |
) | |
# μμ μΆκ° | |
gr.Examples( | |
examples=EXAMPLES, # μ΄μ μ μ μλ μμ λ€ μ¬μ© | |
fn=generate_diagram, | |
inputs=[prompt], | |
outputs=[result, seed], | |
cache_examples=True | |
) | |
# μ΄λ²€νΈ νΈλ€λ¬ | |
gr.on( | |
triggers=[run_button.click, prompt.submit], | |
fn=generate_diagram, | |
inputs=[prompt, seed, randomize_seed, width, height, num_inference_steps], | |
outputs=[result, seed] | |
) | |
# μ± μ€ν | |
if __name__ == "__main__": | |
demo.queue() | |
demo.launch( | |
server_name="0.0.0.0", | |
server_port=7860, | |
share=False, | |
show_error=True, | |
debug=True | |
) |