Update app.py
Browse files
app.py
CHANGED
@@ -8,9 +8,7 @@ from tqdm import tqdm
|
|
8 |
import gradio as gr
|
9 |
import base64
|
10 |
import io
|
11 |
-
from fastapi import Request
|
12 |
-
import secrets
|
13 |
-
from functools import wraps
|
14 |
|
15 |
from safetensors.torch import save_file
|
16 |
from src.pipeline import FluxPipeline
|
@@ -24,9 +22,6 @@ lora_base_path = "./models"
|
|
24 |
# Environment variable for API token (set this in your Hugging Face space settings)
|
25 |
API_TOKEN = os.environ.get("HF_TOKEN")
|
26 |
|
27 |
-
# Generate a secure random session token for UI access (regenerates on restart)
|
28 |
-
UI_SESSION_TOKEN = secrets.token_urlsafe(32)
|
29 |
-
|
30 |
# Initialize the pipeline
|
31 |
pipe = FluxPipeline.from_pretrained(base_path, torch_dtype=torch.bfloat16)
|
32 |
transformer = FluxTransformer2DModel.from_pretrained(base_path, subfolder="transformer", torch_dtype=torch.bfloat16)
|
@@ -37,60 +32,29 @@ def clear_cache(transformer):
|
|
37 |
for name, attn_processor in transformer.attn_processors.items():
|
38 |
attn_processor.bank_kv.clear()
|
39 |
|
40 |
-
# Token verification
|
41 |
-
def verify_token(
|
42 |
-
"""Verify the token
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
auth_header = request.headers.get("Authorization")
|
45 |
if not auth_header or not auth_header.startswith("Bearer "):
|
46 |
-
return
|
47 |
|
48 |
token = auth_header.replace("Bearer ", "")
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
except Exception as e:
|
56 |
-
print(f"Token verification error: {e}")
|
57 |
-
return False
|
58 |
-
|
59 |
-
# Auth decorator for Gradio functions
|
60 |
-
def require_auth(func):
|
61 |
-
@wraps(func)
|
62 |
-
def wrapper(*args, **kwargs):
|
63 |
-
# Extract the request object
|
64 |
-
request = kwargs.get('request')
|
65 |
-
|
66 |
-
if not request:
|
67 |
-
return {"error": "Authentication required"}
|
68 |
-
|
69 |
-
# Check for API token in header for programmatic access
|
70 |
-
auth_header = request.headers.get("Authorization")
|
71 |
-
if auth_header and auth_header.startswith("Bearer "):
|
72 |
-
token = auth_header.replace("Bearer ", "")
|
73 |
-
if API_TOKEN and token == API_TOKEN:
|
74 |
-
return func(*args, **kwargs)
|
75 |
-
|
76 |
-
# Check for UI session token in cookies for UI access
|
77 |
-
auth_cookie = request.cookies.get("hf_ui_auth")
|
78 |
-
if auth_cookie == UI_SESSION_TOKEN:
|
79 |
-
return func(*args, **kwargs)
|
80 |
-
|
81 |
-
# If no valid auth found, return error
|
82 |
-
if request.is_from_ui:
|
83 |
-
return "Unauthorized: Valid authentication required"
|
84 |
-
else:
|
85 |
-
return {"error": "Unauthorized access. Invalid or missing token."}
|
86 |
|
87 |
-
return wrapper
|
88 |
-
|
89 |
-
# Define the Gradio interface with token verification
|
90 |
-
@spaces.GPU()
|
91 |
-
@require_auth
|
92 |
-
def single_condition_generate_image(prompt, spatial_img, height, width, seed, control_type, request: gr.Request = None):
|
93 |
-
|
94 |
try:
|
95 |
# Set the control type
|
96 |
if control_type == "Ghibli":
|
@@ -134,22 +98,26 @@ control_types = ["Ghibli"]
|
|
134 |
|
135 |
# Example data
|
136 |
single_examples = [
|
137 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/00.png"), 680, 1024, 5, "Ghibli"],
|
138 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/02.png"), 560, 1024, 42, "Ghibli"],
|
139 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/03.png"), 568, 1024, 1, "Ghibli"],
|
140 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/04.png"), 768, 672, 1, "Ghibli"],
|
141 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/06.png"), 896, 1024, 1, "Ghibli"],
|
142 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/07.png"), 528, 800, 1, "Ghibli"],
|
143 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/08.png"), 696, 1024, 1, "Ghibli"],
|
144 |
-
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/09.png"), 896, 1024, 1, "Ghibli"],
|
145 |
]
|
146 |
|
147 |
# Create the Gradio Blocks interface
|
148 |
with gr.Blocks() as demo:
|
149 |
gr.Markdown("# Ghibli Studio Control Image Generation with EasyControl")
|
|
|
150 |
gr.Markdown("The model is trained on **only 100 real Asian faces** paired with **GPT-4o-generated Ghibli-style counterparts**, and it preserves facial features while applying the iconic anime aesthetic.")
|
151 |
gr.Markdown("Generate images using EasyControl with Ghibli control LoRAs.(Due to hardware constraints, only low-resolution images can be generated. For high-resolution (1024+), please set up your own environment.)")
|
152 |
|
|
|
|
|
|
|
153 |
gr.Markdown("**[Attention!!]**:The recommended prompts for using Ghibli Control LoRA should include the trigger words: `Ghibli Studio style, Charming hand-drawn anime-style illustration`")
|
154 |
gr.Markdown("😊😊If you like this demo, please give us a star (github: [EasyControl](https://github.com/Xiaojiu-z/EasyControl))")
|
155 |
|
@@ -166,95 +134,22 @@ with gr.Blocks() as demo:
|
|
166 |
with gr.Column():
|
167 |
single_output_image = gr.Image(label="Generated Image")
|
168 |
|
169 |
-
# Add examples for Single Condition Generation
|
170 |
gr.Examples(
|
171 |
examples=single_examples,
|
172 |
-
inputs=[prompt, spatial_img, height, width, seed, control_type],
|
173 |
outputs=single_output_image,
|
174 |
fn=single_condition_generate_image,
|
175 |
cache_examples=False,
|
176 |
label="Single Condition Examples"
|
177 |
)
|
178 |
|
179 |
-
# Link the buttons to the functions
|
180 |
single_generate_btn.click(
|
181 |
single_condition_generate_image,
|
182 |
-
inputs=[prompt, spatial_img, height, width, seed, control_type],
|
183 |
outputs=single_output_image
|
184 |
)
|
185 |
|
186 |
-
#
|
187 |
-
|
188 |
-
def check_auth(username, password):
|
189 |
-
# You could use a more sophisticated verification here
|
190 |
-
if API_TOKEN and password == API_TOKEN:
|
191 |
-
# Set the UI session token as a cookie
|
192 |
-
gr.Info("Authentication successful")
|
193 |
-
return {"hf_ui_auth": UI_SESSION_TOKEN}, True
|
194 |
-
else:
|
195 |
-
gr.Warning("Authentication failed")
|
196 |
-
return {}, False
|
197 |
-
|
198 |
-
with gr.Blocks() as auth_block:
|
199 |
-
gr.Markdown("# Authentication Required")
|
200 |
-
gr.Markdown("This Hugging Face space requires authentication.")
|
201 |
-
|
202 |
-
username = gr.Textbox(label="Username (any value)")
|
203 |
-
password = gr.Textbox(label="API Token", type="password")
|
204 |
-
submit_btn = gr.Button("Login")
|
205 |
-
|
206 |
-
submit_btn.click(
|
207 |
-
fn=check_auth,
|
208 |
-
inputs=[username, password],
|
209 |
-
outputs=[gr.JSON(visible=False), gr.Checkbox(visible=False)],
|
210 |
-
_js="""
|
211 |
-
function(auth_result, success) {
|
212 |
-
if (success) {
|
213 |
-
// Set the auth cookie
|
214 |
-
const cookies = auth_result;
|
215 |
-
for (const [key, value] of Object.entries(cookies)) {
|
216 |
-
document.cookie = `${key}=${value}; path=/; max-age=86400; SameSite=Strict`;
|
217 |
-
}
|
218 |
-
// Refresh the page to load the actual UI
|
219 |
-
window.location.reload();
|
220 |
-
}
|
221 |
-
return [auth_result, success];
|
222 |
-
}
|
223 |
-
"""
|
224 |
-
)
|
225 |
-
|
226 |
-
return auth_block
|
227 |
-
|
228 |
-
# Launch the Gradio app with custom auth
|
229 |
-
if API_TOKEN:
|
230 |
-
# Define middleware to check cookie-based auth before showing UI
|
231 |
-
def auth_middleware(app):
|
232 |
-
@app.middleware("http")
|
233 |
-
async def auth_middleware(request, call_next):
|
234 |
-
# Check for UI auth cookie
|
235 |
-
cookies = request.cookies
|
236 |
-
has_valid_auth = cookies.get("hf_ui_auth") == UI_SESSION_TOKEN
|
237 |
-
|
238 |
-
# Check for API token in header
|
239 |
-
auth_header = request.headers.get("Authorization")
|
240 |
-
if auth_header and auth_header.startswith("Bearer "):
|
241 |
-
token = auth_header.replace("Bearer ", "")
|
242 |
-
has_valid_auth = has_valid_auth or (token == API_TOKEN)
|
243 |
-
|
244 |
-
# If accessing the main UI without auth, redirect to auth UI
|
245 |
-
if not has_valid_auth and request.url.path == "/" and "text/html" in request.headers.get("accept", ""):
|
246 |
-
# Show auth UI instead of main UI
|
247 |
-
auth_ui = auth_interface(demo)
|
248 |
-
auth_response = await auth_ui.process_api(request)
|
249 |
-
return auth_response
|
250 |
-
|
251 |
-
# Otherwise proceed normally (API validation happens in the endpoint function)
|
252 |
-
return await call_next(request)
|
253 |
-
|
254 |
-
return app
|
255 |
-
|
256 |
-
# Launch with auth middleware
|
257 |
-
demo.queue().launch(middleware=auth_middleware)
|
258 |
-
else:
|
259 |
-
print("WARNING: No API_TOKEN set. Running without authentication!")
|
260 |
-
demo.queue().launch()
|
|
|
8 |
import gradio as gr
|
9 |
import base64
|
10 |
import io
|
11 |
+
from fastapi import Request
|
|
|
|
|
12 |
|
13 |
from safetensors.torch import save_file
|
14 |
from src.pipeline import FluxPipeline
|
|
|
22 |
# Environment variable for API token (set this in your Hugging Face space settings)
|
23 |
API_TOKEN = os.environ.get("HF_TOKEN")
|
24 |
|
|
|
|
|
|
|
25 |
# Initialize the pipeline
|
26 |
pipe = FluxPipeline.from_pretrained(base_path, torch_dtype=torch.bfloat16)
|
27 |
transformer = FluxTransformer2DModel.from_pretrained(base_path, subfolder="transformer", torch_dtype=torch.bfloat16)
|
|
|
32 |
for name, attn_processor in transformer.attn_processors.items():
|
33 |
attn_processor.bank_kv.clear()
|
34 |
|
35 |
+
# Token verification function
|
36 |
+
def verify_token(token):
|
37 |
+
"""Verify if the provided token matches the API token"""
|
38 |
+
return API_TOKEN and token == API_TOKEN
|
39 |
+
|
40 |
+
# Define the Gradio interface with token verification
|
41 |
+
@spaces.GPU()
|
42 |
+
def single_condition_generate_image(prompt, spatial_img, height, width, seed, control_type, api_token="", request: gr.Request = None):
|
43 |
+
# Check authentication for API requests
|
44 |
+
if not request.is_from_ui:
|
45 |
+
# For API requests, check Authorization header
|
46 |
auth_header = request.headers.get("Authorization")
|
47 |
if not auth_header or not auth_header.startswith("Bearer "):
|
48 |
+
return {"error": "Unauthorized access. Invalid or missing token in Authorization header."}
|
49 |
|
50 |
token = auth_header.replace("Bearer ", "")
|
51 |
+
if not verify_token(token):
|
52 |
+
return {"error": "Unauthorized access. Invalid token."}
|
53 |
+
else:
|
54 |
+
# For UI requests, check the token input
|
55 |
+
if not verify_token(api_token):
|
56 |
+
return "Unauthorized: Please enter a valid API token"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
try:
|
59 |
# Set the control type
|
60 |
if control_type == "Ghibli":
|
|
|
98 |
|
99 |
# Example data
|
100 |
single_examples = [
|
101 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/00.png"), 680, 1024, 5, "Ghibli", API_TOKEN],
|
102 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/02.png"), 560, 1024, 42, "Ghibli", API_TOKEN],
|
103 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/03.png"), 568, 1024, 1, "Ghibli", API_TOKEN],
|
104 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/04.png"), 768, 672, 1, "Ghibli", API_TOKEN],
|
105 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/06.png"), 896, 1024, 1, "Ghibli", API_TOKEN],
|
106 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/07.png"), 528, 800, 1, "Ghibli", API_TOKEN],
|
107 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/08.png"), 696, 1024, 1, "Ghibli", API_TOKEN],
|
108 |
+
["Ghibli Studio style, Charming hand-drawn anime-style illustration", Image.open("./test_imgs/09.png"), 896, 1024, 1, "Ghibli", API_TOKEN],
|
109 |
]
|
110 |
|
111 |
# Create the Gradio Blocks interface
|
112 |
with gr.Blocks() as demo:
|
113 |
gr.Markdown("# Ghibli Studio Control Image Generation with EasyControl")
|
114 |
+
gr.Markdown("⚠️ **AUTHENTICATION REQUIRED**: You must enter a valid API token to use this interface.")
|
115 |
gr.Markdown("The model is trained on **only 100 real Asian faces** paired with **GPT-4o-generated Ghibli-style counterparts**, and it preserves facial features while applying the iconic anime aesthetic.")
|
116 |
gr.Markdown("Generate images using EasyControl with Ghibli control LoRAs.(Due to hardware constraints, only low-resolution images can be generated. For high-resolution (1024+), please set up your own environment.)")
|
117 |
|
118 |
+
# Authentication input - visible at the top of the interface
|
119 |
+
api_token = gr.Textbox(label="API Token (Required)", type="password", value="")
|
120 |
+
|
121 |
gr.Markdown("**[Attention!!]**:The recommended prompts for using Ghibli Control LoRA should include the trigger words: `Ghibli Studio style, Charming hand-drawn anime-style illustration`")
|
122 |
gr.Markdown("😊😊If you like this demo, please give us a star (github: [EasyControl](https://github.com/Xiaojiu-z/EasyControl))")
|
123 |
|
|
|
134 |
with gr.Column():
|
135 |
single_output_image = gr.Image(label="Generated Image")
|
136 |
|
137 |
+
# Add examples for Single Condition Generation (including the token)
|
138 |
gr.Examples(
|
139 |
examples=single_examples,
|
140 |
+
inputs=[prompt, spatial_img, height, width, seed, control_type, api_token],
|
141 |
outputs=single_output_image,
|
142 |
fn=single_condition_generate_image,
|
143 |
cache_examples=False,
|
144 |
label="Single Condition Examples"
|
145 |
)
|
146 |
|
147 |
+
# Link the buttons to the functions, including the token
|
148 |
single_generate_btn.click(
|
149 |
single_condition_generate_image,
|
150 |
+
inputs=[prompt, spatial_img, height, width, seed, control_type, api_token],
|
151 |
outputs=single_output_image
|
152 |
)
|
153 |
|
154 |
+
# Launch the Gradio app
|
155 |
+
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|