ovi054 commited on
Commit
805dc88
·
verified ·
1 Parent(s): bfac8d8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import random
4
+ import spaces
5
+ import torch
6
+ from diffusers import DiffusionPipeline
7
+
8
+ import os
9
+ import requests
10
+ import tempfile
11
+ import shutil
12
+ from urllib.parse import urlparse
13
+
14
+ dtype = torch.bfloat16
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+
18
+ # Load the model pipeline
19
+ pipe = DiffusionPipeline.from_pretrained("meituan-longcat/LongCat-Image", torch_dtype=dtype).to(device)
20
+
21
+ torch.cuda.empty_cache()
22
+
23
+ MAX_SEED = np.iinfo(np.int32).max
24
+ MAX_IMAGE_SIZE = 2048
25
+
26
+ # pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
27
+
28
+ # flymy-ai/qwen-image-realism-lora
29
+
30
+ def load_lora_auto(pipe, lora_input):
31
+ lora_input = lora_input.strip()
32
+ if not lora_input:
33
+ return
34
+
35
+ # If it's just an ID like "author/model"
36
+ if "/" in lora_input and not lora_input.startswith("http"):
37
+ pipe.load_lora_weights(lora_input)
38
+ return
39
+
40
+ if lora_input.startswith("http"):
41
+ url = lora_input
42
+
43
+ # Repo page (no blob/resolve)
44
+ if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
45
+ repo_id = urlparse(url).path.strip("/")
46
+ pipe.load_lora_weights(repo_id)
47
+ return
48
+
49
+ # Blob link → convert to resolve link
50
+ if "/blob/" in url:
51
+ url = url.replace("/blob/", "/resolve/")
52
+
53
+ # Download direct file
54
+ tmp_dir = tempfile.mkdtemp()
55
+ local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
56
+
57
+ try:
58
+ print(f"Downloading LoRA from {url}...")
59
+ resp = requests.get(url, stream=True)
60
+ resp.raise_for_status()
61
+ with open(local_path, "wb") as f:
62
+ for chunk in resp.iter_content(chunk_size=8192):
63
+ f.write(chunk)
64
+ print(f"Saved LoRA to {local_path}")
65
+ pipe.load_lora_weights(local_path)
66
+ finally:
67
+ shutil.rmtree(tmp_dir, ignore_errors=True)
68
+
69
+ @spaces.GPU()
70
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=4, num_inference_steps=28, lora_id=None, lora_scale=0.95, progress=gr.Progress(track_tqdm=True)):
71
+ if randomize_seed:
72
+ seed = random.randint(0, MAX_SEED)
73
+ generator = torch.Generator().manual_seed(seed)
74
+
75
+
76
+ if lora_id and lora_id.strip() != "":
77
+ pipe.unload_lora_weights()
78
+ load_lora_auto(pipe, lora_id)
79
+
80
+ try:
81
+ image = pipe(
82
+ prompt=prompt,
83
+ negative_prompt="",
84
+ width=width,
85
+ height=height,
86
+ num_inference_steps=num_inference_steps,
87
+ generator=generator,
88
+ true_cfg_scale=guidance_scale,
89
+ guidance_scale=1.0 # Use a fixed default for distilled guidance
90
+ ).images[0]
91
+ print("Image Generation Completed for: ", prompt, lora_id)
92
+ return image, seed
93
+ finally:
94
+ # Unload LoRA weights if they were loaded
95
+ if lora_id:
96
+ pipe.unload_lora_weights()
97
+
98
+ examples = [
99
+ "a tiny astronaut hatching from an egg on the moon",
100
+ "a cat holding a sign that says hello world",
101
+ "an anime illustration of a wiener schnitzel",
102
+ ]
103
+
104
+ css = """
105
+ #col-container {
106
+ margin: 0 auto;
107
+ max-width: 960px;
108
+ }
109
+ .generate-btn {
110
+ background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
111
+ border: none !important;
112
+ color: white !important;
113
+ }
114
+ .generate-btn:hover {
115
+ transform: translateY(-2px);
116
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2);
117
+ }
118
+ """
119
+
120
+ with gr.Blocks(css=css) as app:
121
+ gr.HTML("<center><h1>Qwen Image with LoRA support</h1></center>")
122
+ with gr.Column(elem_id="col-container"):
123
+ with gr.Row():
124
+ with gr.Column():
125
+ with gr.Row():
126
+ text_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt here", lines=3, elem_id="prompt-text-input")
127
+ with gr.Row():
128
+ custom_lora = gr.Textbox(label="Custom LoRA (optional)", info="URL or the path to the LoRA weights", placeholder="kudzueye/boreal-qwen-image")
129
+ with gr.Row():
130
+ with gr.Accordion("Advanced Settings", open=False):
131
+ lora_scale = gr.Slider(
132
+ label="LoRA Scale",
133
+ minimum=0,
134
+ maximum=2,
135
+ step=0.01,
136
+ value=1,
137
+ )
138
+ with gr.Row():
139
+ width = gr.Slider(label="Width", value=1024, minimum=64, maximum=2048, step=16)
140
+ height = gr.Slider(label="Height", value=1024, minimum=64, maximum=2048, step=16)
141
+ seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=4294967296, step=1)
142
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
143
+ with gr.Row():
144
+ steps = gr.Slider(label="Inference steps steps", value=28, minimum=1, maximum=100, step=1)
145
+ cfg = gr.Slider(label="Guidance Scale", value=4.5, minimum=1, maximum=20, step=0.5)
146
+ # method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"])
147
+
148
+ with gr.Row():
149
+ # text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
150
+ text_button = gr.Button("✨ Generate Image", variant='primary', elem_classes=["generate-btn"])
151
+ with gr.Column():
152
+ with gr.Row():
153
+ image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
154
+
155
+ # gr.Markdown(article_text)
156
+ with gr.Column():
157
+ gr.Examples(
158
+ examples = examples,
159
+ inputs = [text_prompt],
160
+ )
161
+ gr.on(
162
+ triggers=[text_button.click, text_prompt.submit],
163
+ fn = infer,
164
+ inputs=[text_prompt, seed, randomize_seed, width, height, cfg, steps, custom_lora, lora_scale],
165
+ outputs=[image_output, seed]
166
+ )
167
+
168
+ # text_button.click(query, inputs=[custom_lora, text_prompt, steps, cfg, randomize_seed, seed, width, height], outputs=[image_output,seed_output, seed])
169
+ # text_button.click(infer, inputs=[text_prompt, seed, randomize_seed, width, height, cfg, steps, custom_lora, lora_scale], outputs=[image_output,seed_output, seed])
170
+
171
+ app.launch(share=True)