artificialguybr commited on
Commit
b46e87b
·
verified ·
1 Parent(s): b505a83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -72
app.py CHANGED
@@ -1,21 +1,21 @@
1
  import gradio as gr
2
- import requests
3
- import io
4
- from PIL import Image
5
  import json
6
- import os
7
  import logging
8
- import math
9
- from tqdm import tqdm
10
- import time
11
-
12
- #logging.basicConfig(level=logging.DEBUG)
13
 
 
14
  with open('loras.json', 'r') as f:
15
  loras = json.load(f)
16
 
 
 
 
 
 
17
  def update_selection(selected_state: gr.SelectData):
18
- logging.debug(f"Inside update_selection, selected_state: {selected_state}")
19
  selected_lora_index = selected_state.index
20
  selected_lora = loras[selected_lora_index]
21
  new_placeholder = f"Type a prompt for {selected_lora['title']}"
@@ -23,64 +23,52 @@ def update_selection(selected_state: gr.SelectData):
23
  updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
24
  return (
25
  gr.update(placeholder=new_placeholder),
26
- updated_text, # Retorna o texto Markdown atualizado
27
  selected_state
28
  )
29
 
30
-
31
- def run_lora(prompt, selected_state, progress=gr.Progress(track_tqdm=True)):
32
- logging.debug(f"Inside run_lora, selected_state: {selected_state}")
33
  if not selected_state:
34
- logging.error("selected_state is None or empty.")
35
- raise gr.Error("You must select a LoRA before proceeding.") # Popup error when no LoRA is selected
36
 
37
- selected_lora_index = selected_state.index # Changed this line
38
  selected_lora = loras[selected_lora_index]
39
- api_url = f"https://api-inference.huggingface.co/models/{selected_lora['repo']}"
40
  trigger_word = selected_lora["trigger_word"]
41
- #token = os.getenv("API_TOKEN")
42
- payload = {
43
- "inputs": f"{prompt} {trigger_word}",
44
- "parameters":{"negative_prompt": "(worst quality, low quality, normal quality, lowres, low details, oversaturated, undersaturated, overexposed, underexposed, grayscale, bw, bad photo, bad photography, bad art:1.4), (watermark, signature, text font, username, error, logo, words, letters, digits, autograph, trademark, name:1.2), (blur, blurry, grainy), morbid, ugly, asymmetrical, mutated malformed, mutilated, poorly lit, bad shadow, draft, cropped, out of frame, cut off, censored, jpeg artifacts, out of focus, glitch, duplicate, (airbrushed, cartoon, anime, semi-realistic, cgi, render, blender, digital art, manga, amateur:1.3), (3D ,3D Game, 3D Game Scene, 3D Character:1.1), (bad hands, bad anatomy, bad body, bad face, bad teeth, bad arms, bad legs, deformities:1.3)", "num_inference_steps": 30, "scheduler":"DPMSolverMultistepScheduler"},
45
- }
46
- #headers = {"Authorization": f"Bearer {token}"}
47
-
48
- # Add a print statement to display the API request
49
- print(f"API Request: {api_url}")
50
- #print(f"API Headers: {headers}")
51
- print(f"API Payload: {payload}")
52
-
53
- error_count = 0
54
- pbar = tqdm(total=None, desc="Loading model")
55
- while(True):
56
- response = requests.post(api_url, json=payload)
57
- if response.status_code == 200:
58
- return Image.open(io.BytesIO(response.content))
59
- elif response.status_code == 503:
60
- #503 is triggered when the model is doing cold boot. It also gives you a time estimate from when the model is loaded but it is not super precise
61
- time.sleep(1)
62
- pbar.update(1)
63
- elif response.status_code == 500 and error_count < 5:
64
- print(response.content)
65
- time.sleep(1)
66
- error_count += 1
67
- continue
68
- else:
69
- logging.error(f"API Error: {response.status_code}")
70
- raise gr.Error("API Error: Unable to fetch the image.") # Raise a Gradio error here
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
 
 
 
 
73
 
74
  with gr.Blocks(css="custom.css") as app:
75
- title = gr.Markdown("# artificialguybr LoRA portfolio")
76
- description = gr.Markdown(
77
- "### This is my portfolio. Follow me on Twitter [@artificialguybr](https://twitter.com/artificialguybr). \n"
78
- "**Note**: The speed and generation quality are for demonstration purposes. "
79
- "For best quality, use Auto or Comfy or Diffusers. \n"
80
- "**Warning**: The API might take some time to deliver the image. \n"
81
- "Special thanks to Hugging Face for their free inference API."
82
  )
 
83
  selected_state = gr.State()
 
84
  with gr.Row():
85
  gallery = gr.Gallery(
86
  [(item["image"], item["title"]) for item in loras],
@@ -88,28 +76,29 @@ with gr.Blocks(css="custom.css") as app:
88
  allow_preview=False,
89
  columns=3
90
  )
 
91
  with gr.Column():
92
  prompt_title = gr.Markdown("### Click on a LoRA in the gallery to select it")
93
- selected_info = gr.Markdown("") # Novo componente Markdown para exibir o texto da LoRA selecionada
 
 
 
94
  with gr.Row():
95
- prompt = gr.Textbox(label="Prompt", show_label=False, lines=1, max_lines=1, placeholder="Type a prompt after selecting a LoRA")
96
- button = gr.Button("Run")
97
- result = gr.Image(interactive=False, label="Generated Image")
 
 
 
 
98
 
99
- gallery.select(
100
- update_selection,
101
- outputs=[prompt, selected_info, selected_state] # Adicionado selected_info aqui
102
- )
103
- prompt.submit(
104
- fn=run_lora,
105
- inputs=[prompt, selected_state],
106
- outputs=[result]
107
- )
108
- button.click(
109
  fn=run_lora,
110
- inputs=[prompt, selected_state],
111
  outputs=[result]
112
  )
113
 
114
- app.queue
115
- app.launch()
 
1
  import gradio as gr
 
 
 
2
  import json
 
3
  import logging
4
+ import torch
5
+ from PIL import Image
6
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler, DPMSolverMultistepScheduler
7
+ import spaces
 
8
 
9
+ # Load LoRAs from JSON file
10
  with open('loras.json', 'r') as f:
11
  loras = json.load(f)
12
 
13
+ # Initialize the base model
14
+ base_model = "stabilityai/stable-diffusion-xl-base-1.0"
15
+ pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=torch.float16)
16
+ pipe.to("cuda")
17
+
18
  def update_selection(selected_state: gr.SelectData):
 
19
  selected_lora_index = selected_state.index
20
  selected_lora = loras[selected_lora_index]
21
  new_placeholder = f"Type a prompt for {selected_lora['title']}"
 
23
  updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
24
  return (
25
  gr.update(placeholder=new_placeholder),
26
+ updated_text,
27
  selected_state
28
  )
29
 
30
+ @spaces.GPU
31
+ def run_lora(prompt, negative_prompt, cfg_scale, steps, selected_state, scheduler):
 
32
  if not selected_state:
33
+ raise gr.Error("You must select a LoRA before proceeding.")
 
34
 
35
+ selected_lora_index = selected_state.index
36
  selected_lora = loras[selected_lora_index]
37
+ lora_path = selected_lora["repo"]
38
  trigger_word = selected_lora["trigger_word"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Load LoRA weights
41
+ pipe.load_lora_weights(lora_path)
42
+
43
+ # Set scheduler
44
+ if scheduler == "Euler":
45
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
46
+ elif scheduler == "DPM++ 2M":
47
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
48
+
49
+ # Generate image
50
+ image = pipe(
51
+ prompt=f"{prompt} {trigger_word}",
52
+ negative_prompt=negative_prompt,
53
+ num_inference_steps=steps,
54
+ guidance_scale=cfg_scale,
55
+ ).images[0]
56
 
57
+ # Unload LoRA weights
58
+ pipe.unload_lora_weights()
59
+
60
+ return image
61
 
62
  with gr.Blocks(css="custom.css") as app:
63
+ gr.Markdown("# artificialguybr LoRA portfolio")
64
+ gr.Markdown(
65
+ "### This is my portfolio. Follow me on Twitter [@artificialguybr](https://twitter.com/artificialguybr).\n"
66
+ "**Note**: Generation quality may vary. For best results, adjust the parameters.\n"
67
+ "Special thanks to Hugging Face for their Diffusers library and Spaces platform."
 
 
68
  )
69
+
70
  selected_state = gr.State()
71
+
72
  with gr.Row():
73
  gallery = gr.Gallery(
74
  [(item["image"], item["title"]) for item in loras],
 
76
  allow_preview=False,
77
  columns=3
78
  )
79
+
80
  with gr.Column():
81
  prompt_title = gr.Markdown("### Click on a LoRA in the gallery to select it")
82
+ selected_info = gr.Markdown("")
83
+ prompt = gr.Textbox(label="Prompt", lines=3, placeholder="Type a prompt after selecting a LoRA")
84
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=2, value="low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry")
85
+
86
  with gr.Row():
87
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=7.5)
88
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=30)
89
+
90
+ scheduler = gr.Dropdown(label="Scheduler", choices=["Euler", "DPM++ 2M"], value="Euler")
91
+
92
+ generate_button = gr.Button("Generate")
93
+ result = gr.Image(label="Generated Image")
94
 
95
+ gallery.select(update_selection, outputs=[prompt, selected_info, selected_state])
96
+
97
+ generate_button.click(
 
 
 
 
 
 
 
98
  fn=run_lora,
99
+ inputs=[prompt, negative_prompt, cfg_scale, steps, selected_state, scheduler],
100
  outputs=[result]
101
  )
102
 
103
+ app.queue()
104
+ app.launch()