File size: 8,263 Bytes
dc42c56
adc1f6f
dc42c56
 
 
 
 
 
4288c52
 
adc1f6f
dc42c56
 
 
 
6f6de6b
4288c52
 
 
 
 
dc42c56
 
 
 
08e64b3
d236b81
 
0b430df
dc42c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288c52
dc42c56
5ef30f3
4288c52
dc42c56
4288c52
f8e02fa
 
 
 
 
 
 
 
 
 
 
dc42c56
f8e02fa
 
 
 
 
dc42c56
f8e02fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288c52
f8e02fa
 
 
 
 
 
dc42c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288c52
 
f8e02fa
 
 
2a57e3c
dc42c56
 
 
 
4288c52
 
dc42c56
 
 
 
 
4288c52
 
dc42c56
4288c52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc42c56
271841b
2a57e3c
271841b
dc42c56
 
 
 
4288c52
 
 
 
 
 
 
 
 
 
 
271841b
 
 
adc1f6f
4288c52
 
 
 
 
adc1f6f
dc42c56
15c5397
271841b
adc1f6f
dc42c56
15c5397
 
adc1f6f
15c5397
 
adc1f6f
15c5397
e66a23b
ac86abb
 
 
 
 
 
 
 
dc42c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288c52
 
 
adc1f6f
dc42c56
75ed7e3
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
import gradio as gr 
import numpy as np
import random
import torch
from PIL import Image
import time
from datetime import datetime
from optimum.intel import OVStableDiffusionPipeline
import re
from functools import lru_cache

# Đảm bảo tính tái tạo
torch.manual_seed(0)
np.random.seed(0)
random.seed(0)

# Tối ưu hóa bộ nhớ và tốc độ
torch.set_num_threads(1)  # Giảm xung đột thread
torch.backends.mkldnn.enabled = True  # Kích hoạt MKL-DNN
torch.backends.openmp.enabled = True

print("🔧 Loading OpenVINO pipeline: HARRY07979/sd-v1-5-openvino")

try:
    pipeline = OVStableDiffusionPipeline.from_pretrained(
        "HARRY07979/stable-diffusion-v1-5-openvino",
        safety_checker=None,
        feature_extractor=None,
        torch_dtype=torch.float32
    )
except Exception as e:
    print(f"Error loading pipeline from remote repository: {e}")
    try:
        pipeline = OVStableDiffusionPipeline.from_pretrained(
            "/path/to/local/model",
            safety_checker=None,
            feature_extractor=True,
            torch_dtype=torch.float32,
            local_files_only=True,
        )
    except Exception as e:
        print(f"Error loading local model: {e}")
        raise RuntimeError("Failed to load the pipeline.")

# Tối ưu hóa pipeline
pipeline.to("cpu")
# Loại bỏ dòng pipeline.model.half() vì không hỗ trợ với OVStableDiffusionPipeline
pipeline.compile()  # Biên dịch mô hình nếu hỗ trợ

# Tối ưu hóa từ điển NSFW - sử dụng set để tìm kiếm nhanh hơn
NSFW_HIGH = {
    "nude", "naked", "sex", "porn", "xxx", "fuck", "dick", "cock", "pussy", "vagina", "penis",
    "boobs", "tits", "breasts", "bra", "panties", "underwear", "lingerie", "orgasm", "cum",
    "blowjob", "handjob", "masturbate", "rape", "gangbang", "incest", "hentai", "lewd",
    "erotic", "kinky", "bondage", "bdsm", "squirt", "creampie", "threesome", "orgy", "yaoi",
    "yuri", "futanari", "cunnilingus", "fellatio", "anal", "paizuri", "bukkake", "guro",
    "vore", "tentacle", "netorare", "cuckold", "exhibitionism", "voyeurism", "poop", "pee",
    "poo", "shit", "piss", "scat", "diarrhea", "vomit", "gore", "blood", "murder",
    "torture", "suicide", "decapitation", "mutilation", "drugs", "cocaine", "heroin",
    "lsd", "ecstasy", "vlxx"
}

NSFW_MEDIUM = {
    "bikini", "swimwear", "sexy", "succubus", "leather", "latex", "stockings", "miniskirt",
    "cleavage", "thighs", "ass", "butt", "skirt", "dress", "topless", "wet", "moaning",
    "spread", "legs apart", "tight", "revealing", "provocative", "suggestive", "flirty"
}

NSFW_PHRASES = {
    "spreading legs", "removing bra", "pulling panties", "sucking dick", "licking pussy",
    "penetrating", "fucking scene", "hard cock", "wet pussy", "big tits", "exposed breasts",
    "nipples visible", "ass spread", "thigh gap", "camel toe", "pussy lips", "cum on face",
    "blowjob scene", "anal sex", "titty fuck", "gang rape", "group sex", "public sex",
    "hidden camera", "peeing girl", "pooping girl", "covered in blood", "cutting flesh",
    "snorting cocaine", "injecting heroin", "hallucinating", "smoking weed"
}

SENSITIVE_CONTEXT = {
    "spread", "removing", "pulling", "sucking", "licking", "penetrating",
    "fucking", "hard", "wet", "exposed", "visible", "ass", "tight", "revealing"
}

# Tối ưu hóa hàm NSFW detection
@lru_cache(maxsize=1024)
def detect_nsfw(prompt: str):
    prompt_lower = prompt.lower()
    
    # Kiểm tra từ khóa cao
    words = set(re.findall(r'\b\w+\b', prompt_lower))
    if words & NSFW_HIGH:
        return True
    
    # Kiểm tra cụm từ NSFW
    for phrase in NSFW_PHRASES:
        if phrase in prompt_lower:
            return True
    
    # Kiểm tra từ khóa trung bình + ngữ cảnh nhạy cảm
    medium_matches = words & NSFW_MEDIUM
    if medium_matches and (words & SENSITIVE_CONTEXT):
        return True
    
    return False

def infer(
    prompt: str,
    negative_prompt: str,
    seed: int,
    randomize_seed: bool,
    width: int,
    height: int,
    guidance_scale: float,
    num_inference_steps: int,
    progress=gr.Progress(track_tqdm=True),
):
    print("=" * 60)
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S %d/%m/%Y")
    print(f"⏰ Run at: {current_time}")
    print(f"📝 Prompt: {prompt}")
    print(f"🚫 Negative Prompt: {negative_prompt or '[None]'}")
    
    # Tối ưu hóa kiểm tra NSFW
    if detect_nsfw(prompt):
        raise gr.Error("⚠️ Prompt contains NSFW content. Please use a safe prompt.")
    
    if randomize_seed:
        seed = random.randint(0, np.iinfo(np.int32).max)
        print(f"🎲 Random Seed generated: {seed}")
    else:
        print(f"🔢 Using fixed Seed: {seed}")
    
    # Tối ưu hóa kích thước ảnh
    width = (width // 8) * 8
    height = (height // 8) * 8
    print(f"🖼️ Image Size: {width}x{height}")
    print(f"🎯 Guidance Scale: {guidance_scale}")
    print(f"📈 Inference Steps: {num_inference_steps}")
    
    # Tối ưu hóa generator
    generator = torch.Generator("cpu").manual_seed(seed)
    
    # Sử dụng inference_mode để tăng tốc
    with torch.inference_mode():
        result = pipeline(
            prompt=prompt,
            negative_prompt=negative_prompt,
            guidance_scale=guidance_scale,
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator,
            # Tối ưu hóa batch
            batch_size=1,
            # Tăng chất lượng
            eta=0.0,  # Giảm nhiễu
            use_karras_sigmas=True,  # Cải thiện chất lượng
        )
    
    image = result.images[0]
    return image, seed

css = """
#col-container {
    margin: 0 auto;
    max-width: 640px;
}
.donate-button {
    background-color: #FFDD00 !important;
    color: #000000 !important;
}
"""

# Hàm JavaScript để mở trang donate khi nhấn nút
donate_js = """
function() {
    window.open('https://buymeacoffee.com/harry07?status=1', '_blank');
}
"""

with gr.Blocks(css=css) as demo:
    with gr.Column(elem_id="col-container"):
        with gr.Row():
            gr.Markdown("## Stable Diffusion v1.5 DEMO")
            # Thêm nút Donate với biểu tượng ☕
            donate_btn = gr.Button("☕ Donate", elem_classes="donate-button")
        
        with gr.Row():
            prompt = gr.Text(label="Prompt", placeholder="Enter your prompt", show_label=False)
            run_button = gr.Button("Generate", variant="primary")
        result = gr.Image(label="Generated Image", show_label=False)
        with gr.Accordion("Advanced Settings", open=False):
            negative_prompt = gr.Text(label="Negative prompt", placeholder="Enter negative prompt")
            seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, value=0)
            randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
            with gr.Row():
                width = gr.Slider(label="Width", minimum=256, maximum=1024, step=8, value=512)
                height = gr.Slider(label="Height", minimum=256, maximum=1024, step=8, value=512)
            with gr.Row():
                guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=15.0, step=0.1, value=7.5)
                num_inference_steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=35)
        gr.Examples(
            examples=[
                "A fantasy landscape, vivid colors, sunset light",
                "Portrait of a cyberpunk robot girl, neon lighting",
                "An epic sci-fi scene: spaceship battle in space",
            ],
            inputs=[prompt]
        )
    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=infer,
        inputs=[
            prompt,
            negative_prompt,
            seed,
            randomize_seed,
            width,
            height,
            guidance_scale,
            num_inference_steps,
        ],
        outputs=[result, seed],
    )
    
    # Gán sự kiện click cho nút Donate
    donate_btn.click(None, js=donate_js)

if __name__ == "__main__":
    demo.launch(share=True)