Nymbo commited on
Commit
974dc33
·
verified ·
1 Parent(s): dd21ab3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -77
app.py CHANGED
@@ -4,9 +4,9 @@ import io
4
  import random
5
  import os
6
  import time
7
- from typing import Optional
8
  from PIL import Image
9
  import json
 
10
 
11
  # Project by Nymbo
12
 
@@ -15,76 +15,63 @@ API_TOKEN = os.getenv("HF_READ_TOKEN")
15
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
16
  timeout = 100
17
 
18
- def query(
19
- prompt: str,
20
- negative_prompt: str = "",
 
21
  steps: int = 35,
22
- cfg_scale: float = 7,
23
  sampler: str = "DPM++ 2M Karras",
24
  seed: int = -1,
25
  strength: float = 0.7,
26
  width: int = 1024,
27
- height: int = 1024,
28
  ) -> Optional[Image.Image]:
29
- """Generate an image from a text prompt using FLUX.1-Krea via the Hugging Face Inference API.
30
-
31
- This function is exposed as an MCP tool via Gradio. It accepts common text-to-image
32
- parameters and returns a single generated image.
33
-
 
 
34
  Args:
35
- prompt: The main text prompt describing the desired image. Required.
36
- negative_prompt: Text describing what should be avoided in the image.
37
- steps: Number of denoising steps (quality vs speed). Typical range 1–100.
38
- cfg_scale: Classifier-free guidance scale (adherence to prompt). Typical range 1–20.
39
- sampler: Sampling/scheduler method name. If unsupported by the backend, it may be ignored.
40
- seed: Random seed. Use -1 for a random seed on each call.
41
- strength: Image-to-image strength (01). Not used for pure text-to-image but included for compatibility.
42
- width: Output image width in pixels. Usually multiples of 32.
43
- height: Output image height in pixels. Usually multiples of 32.
44
-
45
  Returns:
46
- A PIL.Image if generation succeeds; otherwise None.
47
-
48
- Raises:
49
- gr.Error: If the backend returns a non-200 HTTP status.
50
  """
51
- if not prompt:
52
  return None
53
 
54
  key = random.randint(0, 999)
 
 
 
55
 
56
- api_token = os.getenv("HF_READ_TOKEN")
57
- if not api_token:
58
- raise gr.Error("Missing HF_READ_TOKEN environment variable.")
59
-
60
- headers = {"Authorization": f"Bearer {api_token}"}
61
-
62
- # Slightly augment the prompt for higher quality
63
- prompt_aug = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
64
- print(f'\033[1mGeneration {key}:\033[0m {prompt_aug}')
65
-
66
- # Compute seed value
67
- seed_value = seed if seed != -1 else random.randint(1, 1_000_000_000)
68
-
69
- # Prepare payload aligned with HF Inference API conventions
70
- parameters = {
71
- "num_inference_steps": steps,
72
- "guidance_scale": cfg_scale,
73
- "width": width,
74
- "height": height,
75
- "seed": seed_value,
76
- # Best-effort: some backends accept scheduler/sampler names; safe to send.
77
- "scheduler": sampler,
78
- }
79
- if negative_prompt and negative_prompt.strip():
80
- parameters["negative_prompt"] = negative_prompt
81
- # Include strength only if meaningful
82
- if 0 < strength <= 1:
83
- parameters["strength"] = strength
84
-
85
  payload = {
86
- "inputs": prompt_aug,
87
- "parameters": parameters,
 
 
 
 
 
 
 
 
88
  }
89
 
90
  # Send the request to the API and handle the response
@@ -95,12 +82,12 @@ def query(
95
  if response.status_code == 503:
96
  raise gr.Error(f"{response.status_code} : The model is being loaded")
97
  raise gr.Error(f"{response.status_code}")
98
-
99
  try:
100
  # Convert the response content into an image
101
  image_bytes = response.content
102
  image = Image.open(io.BytesIO(image_bytes))
103
- print(f'\033[1mGeneration {key} completed!\033[0m ({prompt_aug})')
104
  return image
105
  except Exception as e:
106
  print(f"Error when trying to open the image: {e}")
@@ -118,7 +105,8 @@ css = """
118
  # Build the Gradio UI with Blocks
119
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
120
  # Add a title to the app
121
- gr.HTML("<center><h1>FLUX.1-Krea-dev</h1></center>")
 
122
 
123
  # Container for all the UI elements
124
  with gr.Column(elem_id="app-container"):
@@ -149,22 +137,8 @@ with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
149
  with gr.Row():
150
  image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
151
 
152
- # Bind the button to the query function with the added width and height inputs
153
- text_button.click(
154
- query,
155
- inputs=[
156
- text_prompt,
157
- negative_prompt,
158
- steps,
159
- cfg,
160
- method,
161
- seed,
162
- strength,
163
- width,
164
- height,
165
- ],
166
- outputs=image_output,
167
- )
168
 
169
- # Launch the Gradio app
170
  app.launch(show_api=True, share=False, mcp_server=True)
 
4
  import random
5
  import os
6
  import time
 
7
  from PIL import Image
8
  import json
9
+ from typing import Optional
10
 
11
  # Project by Nymbo
12
 
 
15
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
16
  timeout = 100
17
 
18
+ # Function to query the API and return the generated image
19
+ def flux_krea_generate(
20
+ prompt: str,
21
+ negative_prompt: str = "(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos",
22
  steps: int = 35,
23
+ cfg_scale: float = 7.0,
24
  sampler: str = "DPM++ 2M Karras",
25
  seed: int = -1,
26
  strength: float = 0.7,
27
  width: int = 1024,
28
+ height: int = 1024
29
  ) -> Optional[Image.Image]:
30
+ """
31
+ Generate high-quality images using the FLUX.1-Krea-dev model from Hugging Face.
32
+
33
+ This function creates detailed, ultra-high-quality images based on text prompts using
34
+ the advanced FLUX.1-Krea-dev diffusion model. The generated images feature ultra detail,
35
+ ultra elaboration, and perfect quality.
36
+
37
  Args:
38
+ prompt: Text description of the image to generate. Be detailed and descriptive for best results.
39
+ negative_prompt: Text describing what should NOT appear in the image. Helps avoid unwanted elements.
40
+ steps: Number of denoising steps (1-100). Higher values generally produce better quality but take longer.
41
+ cfg_scale: Classifier-free guidance scale (1-20). Higher values follow the prompt more closely.
42
+ sampler: Sampling method to use. Options: "DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM".
43
+ seed: Random seed for reproducible results. Use -1 for random seed.
44
+ strength: Strength of the generation process (0-1). Higher values give more creative freedom.
45
+ width: Width of generated image in pixels (64-1216, must be multiple of 32).
46
+ height: Height of generated image in pixels (64-1216, must be multiple of 32).
47
+
48
  Returns:
49
+ PIL Image object of the generated image, or None if generation failed.
 
 
 
50
  """
51
+ if prompt == "" or prompt is None:
52
  return None
53
 
54
  key = random.randint(0, 999)
55
+
56
+ API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
57
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
58
 
59
+ # Add some extra flair to the prompt
60
+ enhanced_prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
61
+ print(f'\033[1mGeneration {key}:\033[0m {enhanced_prompt}')
62
+
63
+ # Prepare the payload for the API call, including width and height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  payload = {
65
+ "inputs": enhanced_prompt,
66
+ "is_negative": False,
67
+ "steps": steps,
68
+ "cfg_scale": cfg_scale,
69
+ "seed": seed if seed != -1 else random.randint(1, 1000000000),
70
+ "strength": strength,
71
+ "parameters": {
72
+ "width": width, # Pass the width to the API
73
+ "height": height # Pass the height to the API
74
+ }
75
  }
76
 
77
  # Send the request to the API and handle the response
 
82
  if response.status_code == 503:
83
  raise gr.Error(f"{response.status_code} : The model is being loaded")
84
  raise gr.Error(f"{response.status_code}")
85
+
86
  try:
87
  # Convert the response content into an image
88
  image_bytes = response.content
89
  image = Image.open(io.BytesIO(image_bytes))
90
+ print(f'\033[1mGeneration {key} completed!\033[0m ({enhanced_prompt})')
91
  return image
92
  except Exception as e:
93
  print(f"Error when trying to open the image: {e}")
 
105
  # Build the Gradio UI with Blocks
106
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
107
  # Add a title to the app
108
+ gr.HTML("<center><h1>FLUX.1-Krea-dev MCP Server</h1></center>")
109
+ gr.HTML("<center><p>High-quality image generation via Model Context Protocol</p></center>")
110
 
111
  # Container for all the UI elements
112
  with gr.Column(elem_id="app-container"):
 
137
  with gr.Row():
138
  image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
139
 
140
+ # Bind the button to the flux_krea_generate function with the added width and height inputs
141
+ text_button.click(flux_krea_generate, inputs=[text_prompt, negative_prompt, steps, cfg, method, seed, strength, width, height], outputs=image_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
+ # Launch the Gradio app with MCP server enabled
144
  app.launch(show_api=True, share=False, mcp_server=True)