Duskfallcrew commited on
Commit
cc6323b
·
verified ·
1 Parent(s): 54694b3

Update app.py

Browse files

Key Changes:

create_model_repo (Sanitization):

Sanitize model_name: Added model_name = re.sub(r"[^a-zA-Z0-9._-]", "-", model_name) to sanitize the model_name input. This replaces any invalid characters with hyphens.

Sanitize orgs_name: Added orgs_name = re.sub(r"[^a-zA-Z0-9._-]", "-", orgs_name) to sanitize the orgs_name input.

Sanitize in Main: Added sanitization.

main Function (Whitespace Stripping): The code to strip whitespace from all input strings is still present and correct.

Testing (Crucial):

Test with Invalid Characters: Try entering model names and organization names that contain spaces, special symbols (e.g., !@#$%^&*()_+=-[]\{}|;':",./<>?), and other characters that are not allowed in Hugging Face repository IDs. The code should now replace these with hyphens and create a valid repository.

Test with Valid Characters: Also test with valid model and organization names to ensure everything still works correctly.

Test with Empty Fields: Test with and without providing an organization name and model name.

Test with invalid token.

Test with URL, filepath, and repo name.

Files changed (1) hide show
  1. app.py +33 -24
app.py CHANGED
@@ -99,7 +99,7 @@ def download_model(model_path_or_url):
99
 
100
 
101
  def create_model_repo(api, user, orgs_name, model_name, make_private=False):
102
- """Creates a Hugging Face model repository, handling missing inputs and sanitizing the username."""
103
 
104
  print("---- create_model_repo Called ----")
105
  print(f" user: {user}")
@@ -110,18 +110,23 @@ def create_model_repo(api, user, orgs_name, model_name, make_private=False):
110
  model_name = f"converted-model-{datetime.now().strftime('%Y%m%d%H%M%S')}"
111
  print(f" Using default model_name: {model_name}")
112
 
 
 
 
 
 
 
 
 
 
113
  if orgs_name:
114
  repo_id = f"{orgs_name}/{model_name.strip()}"
115
  elif user:
116
- # --- Sanitize the username ---
117
- sanitized_username = re.sub(r"[^a-zA-Z0-9._-]", "-", user['name']) # Replace invalid chars with hyphens
118
- print(f" Original Username: {user['name']}") #Debugging
119
- print(f" Sanitized Username: {sanitized_username}") #Debugging
120
  repo_id = f"{sanitized_username}/{model_name.strip()}"
121
  else:
122
- raise ValueError(
123
- "Must provide either an organization name or be logged in."
124
- )
125
 
126
  print(f" repo_id: {repo_id}")
127
 
@@ -246,13 +251,19 @@ def main(
246
  print(f"---- Main Function Error: {error_message} ----")
247
  return error_message
248
 
249
- # --- Strip Whitespace from Inputs ---
250
  model_to_load = model_to_load.strip()
251
  reference_model = reference_model.strip()
252
  output_path = output_path.strip()
253
- hf_token = hf_token.strip() # Even though it's a password field, good practice
254
- orgs_name = orgs_name.strip() if orgs_name else "" #Handle empty
255
- model_name = model_name.strip() if model_name else "" #Handle empty
 
 
 
 
 
 
256
 
257
  try:
258
  convert_and_save_sdxl_to_diffusers(model_to_load, output_path, reference_model)
@@ -263,11 +274,12 @@ def main(
263
  print(f"Using default model_name: {model_name}")
264
 
265
  if orgs_name:
266
- repo_id = f"{orgs_name}/{model_name.strip()}"
267
  elif user:
268
  # Sanitize username here as well:
269
  sanitized_username = re.sub(r"[^a-zA-Z0-9._-]", "-", user['name'])
270
- repo_id = f"{sanitized_username}/{model_name.strip()}"
 
271
 
272
  else: # Should never happen because of login, but good practice
273
  raise ValueError("Must provide either an organization name or be logged in.")
@@ -317,18 +329,15 @@ with gr.Blocks(css=css) as demo:
317
  - Direct URLs to model files
318
  - Hugging Face model repositories (e.g., 'my-org/my-model' or 'my-org/my-model/file.safetensors')
319
 
320
- ### How To Use
321
- - Insert URL or Repository Information into Field 1 SDXL Checkpoint (Path, URL, or HF Repo)
322
- - Optional: Insert Reference Diffusers Model (Optional)
323
- - Optional: Output Path (Diffusers Format)
324
- - Insert your HF Token WRITE: Get your HF token here: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
325
- - Organization Name (Optional)
326
- - Create a Model Name for Output Purposes
327
-
328
  ### ℹ️ Important Notes:
329
  - This tool runs on **CPU**, conversion might be slower than on GPU.
330
  - For Hugging Face uploads, you need a **WRITE** token (not a read token).
 
 
 
331
  - This space is configured for **FP16** precision to reduce memory usage.
 
 
332
 
333
  ### 💻 Source Code:
334
  - [GitHub Repository](https://github.com/Ktiseos-Nyx/Gradio-SDXL-Diffusers)
@@ -341,11 +350,11 @@ with gr.Blocks(css=css) as demo:
341
  with gr.Row():
342
  with gr.Column():
343
  model_to_load = gr.Textbox(
344
- label="SDXL Checkpoint (Path, URL, or HF Repo)", # Corrected Label
345
  placeholder="Path, URL, or Hugging Face Repo ID (e.g., my-org/my-model or my-org/my-model/file.safetensors)",
346
  )
347
  reference_model = gr.Textbox(
348
- label="Reference Diffusers Model (Optional)", # Corrected Label
349
  placeholder="e.g., stabilityai/stable-diffusion-xl-base-1.0 (Leave blank for default)",
350
  )
351
  output_path = gr.Textbox(label="Output Path (Diffusers Format)", value="output")
 
99
 
100
 
101
  def create_model_repo(api, user, orgs_name, model_name, make_private=False):
102
+ """Creates a Hugging Face model repository, sanitizing inputs."""
103
 
104
  print("---- create_model_repo Called ----")
105
  print(f" user: {user}")
 
110
  model_name = f"converted-model-{datetime.now().strftime('%Y%m%d%H%M%S')}"
111
  print(f" Using default model_name: {model_name}")
112
 
113
+ # --- Sanitize model_name and orgs_name ---
114
+ if orgs_name:
115
+ orgs_name = re.sub(r"[^a-zA-Z0-9._-]", "-", orgs_name)
116
+ print(f" Sanitized orgs_name: {orgs_name}")
117
+ if model_name:
118
+ model_name = re.sub(r"[^a-zA-Z0-9._-]", "-", model_name)
119
+ print(f" Sanitized model_name: {model_name}")
120
+
121
+
122
  if orgs_name:
123
  repo_id = f"{orgs_name}/{model_name.strip()}"
124
  elif user:
125
+ sanitized_username = re.sub(r"[^a-zA-Z0-9._-]", "-", user['name'])
126
+ print(f" Sanitized Username: {sanitized_username}")
 
 
127
  repo_id = f"{sanitized_username}/{model_name.strip()}"
128
  else:
129
+ raise ValueError("Must provide either an organization name or be logged in.")
 
 
130
 
131
  print(f" repo_id: {repo_id}")
132
 
 
251
  print(f"---- Main Function Error: {error_message} ----")
252
  return error_message
253
 
254
+ # --- Strip Whitespace and Sanitize from Inputs ---
255
  model_to_load = model_to_load.strip()
256
  reference_model = reference_model.strip()
257
  output_path = output_path.strip()
258
+ hf_token = hf_token.strip() # Even though it's a password field
259
+ orgs_name = orgs_name.strip() if orgs_name else ""
260
+ model_name = model_name.strip() if model_name else ""
261
+
262
+ # --- Sanitize model_name and orgs_name ---
263
+ if orgs_name:
264
+ orgs_name = re.sub(r"[^a-zA-Z0-9._-]", "-", orgs_name)
265
+ if model_name:
266
+ model_name = re.sub(r"[^a-zA-Z0-9._-]", "-", model_name)
267
 
268
  try:
269
  convert_and_save_sdxl_to_diffusers(model_to_load, output_path, reference_model)
 
274
  print(f"Using default model_name: {model_name}")
275
 
276
  if orgs_name:
277
+ repo_id = f"{orgs_name}/{model_name}"
278
  elif user:
279
  # Sanitize username here as well:
280
  sanitized_username = re.sub(r"[^a-zA-Z0-9._-]", "-", user['name'])
281
+ print(f" Sanitized Username: {sanitized_username}")
282
+ repo_id = f"{sanitized_username}/{model_name}"
283
 
284
  else: # Should never happen because of login, but good practice
285
  raise ValueError("Must provide either an organization name or be logged in.")
 
329
  - Direct URLs to model files
330
  - Hugging Face model repositories (e.g., 'my-org/my-model' or 'my-org/my-model/file.safetensors')
331
 
 
 
 
 
 
 
 
 
332
  ### ℹ️ Important Notes:
333
  - This tool runs on **CPU**, conversion might be slower than on GPU.
334
  - For Hugging Face uploads, you need a **WRITE** token (not a read token).
335
+ - Get your HF token here: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
336
+
337
+ ### 💾 Memory Usage:
338
  - This space is configured for **FP16** precision to reduce memory usage.
339
+ - Close other applications during conversion.
340
+ - For large models, ensure you have at least 16GB of RAM.
341
 
342
  ### 💻 Source Code:
343
  - [GitHub Repository](https://github.com/Ktiseos-Nyx/Gradio-SDXL-Diffusers)
 
350
  with gr.Row():
351
  with gr.Column():
352
  model_to_load = gr.Textbox(
353
+ label="SDXL Checkpoint (Path, URL, or HF Repo)",
354
  placeholder="Path, URL, or Hugging Face Repo ID (e.g., my-org/my-model or my-org/my-model/file.safetensors)",
355
  )
356
  reference_model = gr.Textbox(
357
+ label="Reference Diffusers Model (Optional)",
358
  placeholder="e.g., stabilityai/stable-diffusion-xl-base-1.0 (Leave blank for default)",
359
  )
360
  output_path = gr.Textbox(label="Output Path (Diffusers Format)", value="output")