hsuwill000 commited on
Commit
028bc5d
·
verified ·
1 Parent(s): abaa980

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -117
app.py CHANGED
@@ -1,130 +1,93 @@
1
- import gradio as gr
2
- from gradio_client import Client
3
- from PIL import Image
4
  import os
5
- import time
6
- import traceback
7
- import asyncio
8
- from huggingface_hub import HfApi
9
-
10
- # Your Hugging Face API key (ensure this is set in your environment or replace directly)
11
- api_key = os.getenv('MY_API_KEY')
12
- api = HfApi(token=api_key)
13
-
14
- # List of repos (private spaces)
15
- repos = [
16
- "hsuwill000/LCM-absolutereality-openvino-8bit_00",
17
- "hsuwill000/LCM-absolutereality-openvino-8bit_01",
18
- "hsuwill000/LCM-absolutereality-openvino-8bit_02",
19
- "hsuwill000/LCM-absolutereality-openvino-8bit_03",
20
- "hsuwill000/LCM-absolutereality-openvino-8bit_04",
21
- "hsuwill000/LCM-absolutereality-openvino-8bit_05",
22
- "hsuwill000/LCM-absolutereality-openvino-8bit_06",
23
- "hsuwill000/LCM-absolutereality-openvino-8bit_07",
24
- "hsuwill000/LCM-absolutereality-openvino-8bit_08",
25
- "hsuwill000/LCM-absolutereality-openvino-8bit_09",
26
- "hsuwill000/LCM-absolutereality-openvino-8bit_10",
27
- ]
28
-
29
- class CustomClient(Client):
30
- def __init__(self, *args, timeout=30, **kwargs):
31
- super().__init__(*args, **kwargs)
32
- self.timeout = timeout
33
-
34
- def _request(self, method, url, **kwargs):
35
- kwargs['timeout'] = self.timeout
36
- return super()._request(method, url, **kwargs)
37
 
38
- # Counter for image filenames to avoid overwriting
39
- count = 0
 
40
 
41
- async def infer_single_gradio(client, prompt):
42
- global count
43
- # Prepare the inputs for the prediction
44
- inputs = {
45
- "prompt": prompt,
46
- #"num_inference_steps": 10 # Number of inference steps for the model
47
- }
48
 
49
- try:
50
- # Send the request to the model and receive the image
51
- result = await asyncio.to_thread(client.predict, inputs, api_name="/infer")
52
-
53
- # Open the resulting image
54
- image = Image.open(result)
55
-
56
- # Create a unique filename to save the image
57
- filename = f"img_{count:08d}.jpg"
58
- while os.path.exists(filename):
59
- count += 1
60
- filename = f"img_{count:08d}.jpg"
61
-
62
- # Save the image locally
63
- image.save(filename)
64
- print(f"Saved image as {filename}")
65
-
66
- # Return the image to be displayed in Gradio
67
- return image
68
 
69
- except Exception as e:
70
- # Handle any errors that occur
71
- print(f"An exception occurred: {str(e)}")
72
- print("Stack trace:")
73
- traceback.print_exc() # Print stack trace for debugging
74
- return None # Return nothing if an error occurs
 
75
 
76
- async def infer_gradio(prompt: str, output_images: gr.Gallery):
77
- #can't work Clear previous images from the gallery
78
- #output_images.update([])
 
 
79
 
80
- # Record the start time
81
- start_time = time.time()
 
 
 
 
 
 
 
 
82
 
83
- # Create a list of tasks (one for each repo)
84
- tasks = []
85
- for repo in repos:
86
- runtime_info = api.get_space_runtime(repo)
87
- if runtime_info.stage == 'APP_STARTING':
88
- continue
89
- if runtime_info.stage in ['SLEEPING', 'PAUSED']:
90
- print(f"{repo} is now SLEEPING or PAUSED.")
91
- api.restart_space(repo_id=repo)
92
- continue
93
- # Create a CustomClient instance for each repo
94
- client = CustomClient(repo, hf_token=api_key, timeout=300)
95
- task = infer_single_gradio(client, prompt)
96
- tasks.append(task)
97
 
98
- # Run all tasks concurrently (i.e., generate images from all repos)
99
- results = await asyncio.gather(*tasks)
100
 
101
- # Calculate the time taken for image generation
102
- end_time = time.time()
103
- time_taken = end_time - start_time
104
- print(f"Time taken to generate the image(s): {time_taken:.2f} seconds")
 
 
 
105
 
106
- # Return the results (images)
107
- return results # Return all the images as a list
108
-
109
- # Define Gradio Interface
110
- with gr.Blocks() as demo:
111
- with gr.Row(): # Use a Row to place the prompt input and the button side by side
112
- prompt_input = gr.Textbox(
113
- label="Enter Your Prompt",
114
- show_label="False",
115
- placeholder="Type your prompt for image generation here",
116
- lines=1, # Set the input to be only one line tall
117
- interactive=True # Allow user to interact with the textbox
118
- )
119
 
120
- # Change the button text to "RUN:" and align it with the prompt input
121
- run_button = gr.Button("RUN")
122
-
123
- # Output image display area (will show multiple images)
124
- output_images = gr.Gallery(label="Generated Images", elem_id="gallery", show_label=False)
125
-
126
- # Connecting the button click to the image generation function
127
- run_button.click(infer_gradio, inputs=[prompt_input], outputs=output_images)
 
 
 
 
 
 
 
 
 
128
 
129
- # Launch Gradio app
130
- demo.launch()
 
 
 
 
1
  import os
2
+ import gradio as gr
3
+ from transformers import AutoModelForCausalLM
4
+ from optimum.intel.openvino import OVStableDiffusionPipeline
5
+ import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # 定義模型 ID 與存儲路徑
8
+ model_id = "Kouki79/Realistic_Vision6_LCM"
9
+ export_path = "exported_model_openvino_int8"
10
 
11
+ # 設定圖片大小
12
+ HIGH = 1024
13
+ WIDTH = 512
 
 
 
 
14
 
15
+ print("🔍 檢查 OpenVINO 模型是否已存在...")
16
+ if not os.path.exists(export_path) or not os.listdir(export_path):
17
+ print("⚠️ 尚未轉換 OpenVINO 8-bit 模型,開始轉換...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ # 轉換 Hugging Face 模型為 OpenVINO 8-bit
20
+ model = OVStableDiffusionPipeline.from_pretrained(
21
+ model_id,
22
+ export=True, # 自動轉換為 OpenVINO
23
+ device="CPU",
24
+ precision="int8", # 啟用 8-bit 量化
25
+ )
26
 
27
+ # 儲存轉換後的 OpenVINO 8-bit 模型
28
+ model.save_pretrained(export_path)
29
+ print(f"✅ 轉換完成!OpenVINO 8-bit 模型已儲存至 '{export_path}'")
30
+ else:
31
+ print(f"✅ 發現已轉換的 OpenVINO 8-bit 模型:'{export_path}'")
32
 
33
+ # 載入 OpenVINO 8-bit 模型
34
+ print("🔄 載入 OpenVINO 8-bit 模型...")
35
+ pipe = OVStableDiffusionPipeline.from_pretrained(
36
+ export_path,
37
+ compile=True, # 編譯模型以提高效能
38
+ device="CPU",
39
+ safety_checker=None,
40
+ torch_dtype=torch.uint8
41
+ )
42
+ print("✅ OpenVINO 模型載入完成!")
43
 
44
+ # 設定推論函數
45
+ def infer(prompt):
46
+ print(f"🖼️ 生成圖片: {prompt}")
47
+ image = pipe(
48
+ prompt=f",hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic,",
49
+ negative_prompt="EasyNegative, cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly,",
50
+ width=WIDTH,
51
+ height=HIGH,
52
+ guidance_scale=1.0,
53
+ num_inference_steps=6,
54
+ num_images_per_prompt=1,
55
+ ).images[0]
 
 
56
 
57
+ return image
 
58
 
59
+ # Gradio UI 設定
60
+ css = """
61
+ #col-container {
62
+ margin: 0 auto;
63
+ max-width: 520px;
64
+ }
65
+ """
66
 
67
+ with gr.Blocks(css=css) as demo:
68
+ with gr.Column(elem_id="col-container"):
69
+ gr.Markdown(f"""
70
+ # {model_id.split('/')[1]} {WIDTH}x{HIGH}
71
+ Running on OpenVINO (8-bit).
72
+ """)
 
 
 
 
 
 
 
73
 
74
+ with gr.Row():
75
+ prompt = gr.Textbox(
76
+ label="Prompt",
77
+ show_label=False,
78
+ max_lines=1,
79
+ placeholder="Enter your prompt",
80
+ container=False,
81
+ )
82
+ run_button = gr.Button("Generate", scale=0)
83
+
84
+ result = gr.Image(label="Result", show_label=False)
85
+
86
+ run_button.click(
87
+ fn=infer,
88
+ inputs=[prompt],
89
+ outputs=[result]
90
+ )
91
 
92
+ print("🚀 啟動 Gradio Web UI...")
93
+ demo.queue().launch()