HARRY07979 commited on
Commit
271841b
·
verified ·
1 Parent(s): 15c5397

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -69
app.py CHANGED
@@ -2,110 +2,101 @@ import gradio as gr
2
  import numpy as np
3
  import random
4
  import torch
5
- from openvino.runtime import Core
6
  from PIL import Image
7
- from huggingface_hub import hf_hub_download
8
- import os
9
 
10
- print("🔧 Initializing OpenVINO Runtime...")
 
 
11
 
12
- # --------- Detect OpenVINO Device ---------
13
- core = Core()
14
- available_devices = core.available_devices
15
- device = "CPU"
16
 
17
- if "GPU" in available_devices:
18
- device = "GPU"
19
- elif "MYRIAD" in available_devices:
20
- device = "MYRIAD"
21
- elif "HDDL" in available_devices:
22
- device = "HDDL"
23
 
24
- print(f"✅ Using device: {device}")
 
 
 
 
 
 
 
25
 
26
- # --------- Download model from HF Hub ---------
27
- model_repo = "HARRY07979/sd-v1-5-openvino"
28
- model_filename = "stable-diffusion-v1-5.xml" # you may need to adjust based on actual file
29
 
30
- model_path_xml = hf_hub_download(repo_id=model_repo, filename=model_filename)
31
- model_path_bin = model_path_xml.replace(".xml", ".bin")
32
-
33
- print("📦 Model files downloaded")
34
-
35
- # --------- Compile OpenVINO model ---------
36
- compiled_model = core.compile_model(model_path_xml, device)
37
-
38
- # Get input and output tensor names
39
- input_layer = compiled_model.input(0)
40
- output_layer = compiled_model.output(0)
41
-
42
- # --------- Dummy NSFW filter ---------
43
- def detect_nsfw(text: str):
44
  banned = ["nude", "sex", "porn", "xxx", "nsfw"]
45
  for word in banned:
46
- if word in text.lower():
47
- return "NSFW"
48
- return "SFW"
49
 
50
- # --------- Dummy Preprocessing (you should integrate tokenizer/text encoder for real use) ---------
51
- def preprocess_input(prompt, width, height, seed):
52
- # Just generate dummy latent vector
53
- np.random.seed(seed)
54
- return np.random.rand(1, 3, height, width).astype(np.float32)
55
-
56
- # --------- Inference function ---------
57
  def infer(
58
- prompt,
59
- negative_prompt,
60
- seed,
61
- randomize_seed,
62
- width,
63
- height,
64
- guidance_scale,
65
- num_inference_steps,
66
  progress=gr.Progress(track_tqdm=True),
67
  ):
68
- if detect_nsfw(prompt) == "NSFW":
69
  raise gr.Error("⚠️ Prompt contains NSFW content. Please use a safe prompt.")
70
 
71
  if randomize_seed:
72
  seed = random.randint(0, np.iinfo(np.int32).max)
73
 
 
74
  width = (width // 8) * 8
75
  height = (height // 8) * 8
76
 
77
- # Prepare dummy input for now
78
- input_data = preprocess_input(prompt, width, height, seed)
79
-
80
- # Run OpenVINO inference
81
- result = compiled_model([input_data])[output_layer]
82
 
83
- # Postprocess dummy result
84
- output_image = np.clip(result[0].transpose(1, 2, 0), 0, 1)
85
- output_image = (output_image * 255).astype(np.uint8)
86
- pil_image = Image.fromarray(output_image)
 
 
 
 
 
87
 
88
- return pil_image, seed
 
89
 
90
- # --------- UI ---------
91
  examples = [
92
- "A futuristic cyberpunk city at night, ultra-detailed, 4k",
93
- "A cute corgi wearing sunglasses",
94
- "A bowl of ramen in anime style",
95
  ]
96
 
97
- with gr.Blocks(css="#col-container { max-width: 640px; margin: auto; }") as demo:
 
 
 
 
 
 
 
98
  with gr.Column(elem_id="col-container"):
99
- gr.Markdown("## 🧠 SD 1.5 OpenVINO via HARRY07979 on HuggingFace")
100
 
101
  with gr.Row():
102
  prompt = gr.Text(label="Prompt", placeholder="Enter your prompt", show_label=False)
103
  run_button = gr.Button("Generate", variant="primary")
104
 
105
- result = gr.Image(label="Output", show_label=False)
106
 
107
  with gr.Accordion("Advanced Settings", open=False):
108
- negative_prompt = gr.Text(label="Negative Prompt", placeholder="e.g. low quality, blurry")
109
 
110
  seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, value=0)
111
  randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
 
2
  import numpy as np
3
  import random
4
  import torch
 
5
  from PIL import Image
 
 
6
 
7
+ from transformers import CLIPTextModel, CLIPTokenizer
8
+ from diffusers import AutoencoderKL, UNet2DConditionModel
9
+ from optimum.intel import OVStableDiffusionPipeline
10
 
11
+ # Nếu muốn đảm bảo reproducibility
12
+ torch.manual_seed(0)
13
+ np.random.seed(0)
14
+ random.seed(0)
15
 
16
+ print("🔧 Loading OpenVINO pipeline: HARRY07979/sd-v1-5-openvino")
 
 
 
 
 
17
 
18
+ # Load the full pipeline (tokenizer, text encoder, unet, vae) từ repo
19
+ pipeline = OVStableDiffusionPipeline.from_pretrained(
20
+ "HARRY07979/sd-v1-5-openvino",
21
+ # nếu model đã convert sẵn IR nên không cần export
22
+ safety_checker=None, # nếu muốn bỏ kiểm tra NSFW hoặc model không có
23
+ feature_extractor=None,
24
+ torch_dtype=torch.float32, # nhớ kiểm tra model hỗ trợ dtype nào
25
+ )
26
 
27
+ # Chọn thiết bị phù hợp (CPU, GPU, MYRIAD...) — Optimum Intel sẽ tự chọn nếu có hỗ trợ
28
+ pipeline.to("cpu")
 
29
 
30
+ # Dummy NSFW detection nếu muốn (bên trong có thể dùng safety_checker của pipeline nếu có)
31
+ def detect_nsfw(prompt: str):
 
 
 
 
 
 
 
 
 
 
 
 
32
  banned = ["nude", "sex", "porn", "xxx", "nsfw"]
33
  for word in banned:
34
+ if word.lower() in prompt.lower():
35
+ return True
36
+ return False
37
 
 
 
 
 
 
 
 
38
  def infer(
39
+ prompt: str,
40
+ negative_prompt: str,
41
+ seed: int,
42
+ randomize_seed: bool,
43
+ width: int,
44
+ height: int,
45
+ guidance_scale: float,
46
+ num_inference_steps: int,
47
  progress=gr.Progress(track_tqdm=True),
48
  ):
49
+ if detect_nsfw(prompt):
50
  raise gr.Error("⚠️ Prompt contains NSFW content. Please use a safe prompt.")
51
 
52
  if randomize_seed:
53
  seed = random.randint(0, np.iinfo(np.int32).max)
54
 
55
+ # Ensure width/height divisible by 8
56
  width = (width // 8) * 8
57
  height = (height // 8) * 8
58
 
59
+ generator = torch.Generator("cpu").manual_seed(seed)
 
 
 
 
60
 
61
+ result = pipeline(
62
+ prompt=prompt,
63
+ negative_prompt=negative_prompt,
64
+ guidance_scale=guidance_scale,
65
+ num_inference_steps=num_inference_steps,
66
+ width=width,
67
+ height=height,
68
+ generator=generator,
69
+ )
70
 
71
+ image = result.images[0]
72
+ return image, seed
73
 
74
+ # Gradio UI
75
  examples = [
76
+ "A fantasy landscape, vivid colors, sunset light",
77
+ "Portrait of a cyberpunk robot girl, neon lighting",
78
+ "An epic sci-fi scene: spaceship battle in space",
79
  ]
80
 
81
+ css = """
82
+ #col-container {
83
+ margin: 0 auto;
84
+ max-width: 640px;
85
+ }
86
+ """
87
+
88
+ with gr.Blocks(css=css) as demo:
89
  with gr.Column(elem_id="col-container"):
90
+ gr.Markdown("## Stable Diffusion v1.5 OpenVINO Full Pipeline (Tokeniser + UNet + VAE)")
91
 
92
  with gr.Row():
93
  prompt = gr.Text(label="Prompt", placeholder="Enter your prompt", show_label=False)
94
  run_button = gr.Button("Generate", variant="primary")
95
 
96
+ result = gr.Image(label="Generated Image", show_label=False)
97
 
98
  with gr.Accordion("Advanced Settings", open=False):
99
+ negative_prompt = gr.Text(label="Negative prompt", placeholder="Enter negative prompt")
100
 
101
  seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, value=0)
102
  randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)