File size: 2,321 Bytes
405af98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler

# Danh sách các model nhẹ, phù hợp cho CPU
MODELS = {
    "SD v1.5 (Cơ bản)": "runwayml/stable-diffusion-v1-5",
    "Tiny SD (Siêu nhanh - Khuyên dùng)": "segmind/tiny-sd",
    "Dreamlike Photoreal": "dreamlike-art/dreamlike-photoreal-2.0"
}

current_model_id = ""
pipe = None

def load_model(model_id, progress=gr.Progress()):
    global pipe, current_model_id
    if model_id != current_model_id:
        progress(0, desc="Đang tải model mới... (Vui lòng đợi)")
        pipe = StableDiffusionPipeline.from_pretrained(
            model_id, 
            torch_dtype=torch.float32,
            safety_checker=None # Tắt để tiết kiệm RAM
        )
        # Tối ưu scheduler để chạy nhanh hơn
        pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
        current_model_id = model_id
    return pipe

def generate(prompt, model_name, steps, progress=gr.Progress(track_tqdm=True)):
    if not prompt:
        return None
    
    # 1. Load model đã chọn
    model_id = MODELS[model_name]
    pipeline = load_model(model_id)
    
    # 2. Tạo ảnh với Progress Bar
    # track_tqdm=True sẽ tự động bắt các bước loop của diffusers để hiện %
    image = pipeline(
        prompt, 
        num_inference_steps=int(steps),
        guidance_scale=7.0
    ).images[0]
    
    return image

# Giao diện UI
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown(f"# 🎨 Stable Diffusion Free CPU - Minh Đức AI")
    
    with gr.Row():
        with gr.Column():
            prompt = gr.Textbox(label="Mô tả ảnh", placeholder="Một con mèo đi thám hiểm mặt trăng...")
            model_name = gr.Dropdown(choices=list(MODELS.keys()), value="Tiny SD (Siêu nhanh - Khuyên dùng)", label="Chọn Model")
            steps = gr.Slider(minimum=10, maximum=30, value=15, step=1, label="Số bước chạy (Steps - Càng cao càng chậm)")
            btn = gr.Button("Bắt đầu tạo ảnh", variant="primary")
        
        with gr.Column():
            output = gr.Image(label="Kết quả")

    btn.click(fn=generate, inputs=[prompt, model_name, steps], outputs=output)

demo.launch()