HAL1993 commited on
Commit
cd5cb90
·
verified ·
1 Parent(s): f00ffec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -116
app.py CHANGED
@@ -4,55 +4,45 @@ import spaces
4
  import torch
5
  import random
6
  from PIL import Image
7
-
8
  from diffusers import FluxKontextPipeline
9
  from diffusers.utils import load_image
 
10
 
11
  MAX_SEED = np.iinfo(np.int32).max
12
 
13
  pipe = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
14
 
15
  @spaces.GPU
16
- def infer(input_image, prompt, seed=42, randomize_seed=False, guidance_scale=2.5, steps=28, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
  Perform image editing using the FLUX.1 Kontext pipeline.
19
-
20
- This function takes an input image and a text prompt to generate a modified version
21
- of the image based on the provided instructions. It uses the FLUX.1 Kontext model
22
- for contextual image editing tasks.
23
-
24
- Args:
25
- input_image (PIL.Image.Image): The input image to be edited. Will be converted
26
- to RGB format if not already in that format.
27
- prompt (str): Text description of the desired edit to apply to the image.
28
- Examples: "Remove glasses", "Add a hat", "Change background to beach".
29
- seed (int, optional): Random seed for reproducible generation. Defaults to 42.
30
- Must be between 0 and MAX_SEED (2^31 - 1).
31
- randomize_seed (bool, optional): If True, generates a random seed instead of
32
- using the provided seed value. Defaults to False.
33
- guidance_scale (float, optional): Controls how closely the model follows the
34
- prompt. Higher values mean stronger adherence to the prompt but may reduce
35
- image quality. Range: 1.0-10.0. Defaults to 2.5.
36
- steps (int, optional): Controls how many steps to run the diffusion model for.
37
- Range: 1-30. Defaults to 28.
38
- progress (gr.Progress, optional): Gradio progress tracker for monitoring
39
- generation progress. Defaults to gr.Progress(track_tqdm=True).
40
-
41
- Returns:
42
- tuple: A 3-tuple containing:
43
- - PIL.Image.Image: The generated/edited image
44
- - int: The seed value used for generation (useful when randomize_seed=True)
45
- - gr.update: Gradio update object to make the reuse button visible
46
-
47
- Example:
48
- >>> edited_image, used_seed, button_update = infer(
49
- ... input_image=my_image,
50
- ... prompt="Add sunglasses",
51
- ... seed=123,
52
- ... randomize_seed=False,
53
- ... guidance_scale=2.5
54
- ... )
55
  """
 
 
 
 
 
56
  if randomize_seed:
57
  seed = random.randint(0, MAX_SEED)
58
 
@@ -60,17 +50,19 @@ def infer(input_image, prompt, seed=42, randomize_seed=False, guidance_scale=2.5
60
  input_image = input_image.convert("RGB")
61
  image = pipe(
62
  image=input_image,
63
- prompt=prompt,
64
  guidance_scale=guidance_scale,
65
- width = input_image.size[0],
66
- height = input_image.size[1],
67
  num_inference_steps=steps,
68
  generator=torch.Generator().manual_seed(seed),
69
  ).images[0]
70
  else:
71
  image = pipe(
72
- prompt=prompt,
73
  guidance_scale=guidance_scale,
 
 
74
  num_inference_steps=steps,
75
  generator=torch.Generator().manual_seed(seed),
76
  ).images[0]
@@ -81,86 +73,94 @@ def infer_example(input_image, prompt):
81
  image, seed, _ = infer(input_image, prompt)
82
  return image, seed
83
 
84
- css="""
85
- #col-container {
86
- margin: 0 auto;
87
- max-width: 960px;
88
- }
89
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- with gr.Blocks(css=css) as demo:
92
-
93
- with gr.Column(elem_id="col-container"):
94
- gr.Markdown(f"""# FLUX.1 Kontext [dev]
95
- Image editing and manipulation model guidance-distilled from FLUX.1 Kontext [pro], [[blog]](https://bfl.ai/announcements/flux-1-kontext-dev) [[model]](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev)
96
- """)
97
- with gr.Row():
98
- with gr.Column():
99
- input_image = gr.Image(label="Upload the image for editing", type="pil")
100
- with gr.Row():
101
- prompt = gr.Text(
102
- label="Prompt",
103
- show_label=False,
104
- max_lines=1,
105
- placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",
106
- container=False,
107
- )
108
- run_button = gr.Button("Run", scale=0)
109
- with gr.Accordion("Advanced Settings", open=False):
110
-
111
- seed = gr.Slider(
112
- label="Seed",
113
- minimum=0,
114
- maximum=MAX_SEED,
115
- step=1,
116
- value=0,
117
- )
118
-
119
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
120
-
121
- guidance_scale = gr.Slider(
122
- label="Guidance Scale",
123
- minimum=1,
124
- maximum=10,
125
- step=0.1,
126
- value=2.5,
127
- )
128
-
129
- steps = gr.Slider(
130
- label="Steps",
131
- minimum=1,
132
- maximum=30,
133
- value=28,
134
- step=1
135
- )
136
-
137
- with gr.Column():
138
- result = gr.Image(label="Result", show_label=False, interactive=False)
139
- reuse_button = gr.Button("Reuse this image", visible=False)
140
-
141
-
142
- examples = gr.Examples(
143
- examples=[
144
- ["flowers.png", "turn the flowers into sunflowers"],
145
- ["monster.png", "make this monster ride a skateboard on the beach"],
146
- ["cat.png", "make this cat happy"]
147
- ],
148
- inputs=[input_image, prompt],
149
- outputs=[result, seed],
150
- fn=infer_example,
151
- cache_examples="lazy"
152
  )
153
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  gr.on(
155
  triggers=[run_button.click, prompt.submit],
156
- fn = infer,
157
- inputs = [input_image, prompt, seed, randomize_seed, guidance_scale, steps],
158
- outputs = [result, seed, reuse_button]
159
  )
160
  reuse_button.click(
161
- fn = lambda image: image,
162
- inputs = [result],
163
- outputs = [input_image]
164
  )
165
 
166
  demo.launch(mcp_server=True)
 
4
  import torch
5
  import random
6
  from PIL import Image
 
7
  from diffusers import FluxKontextPipeline
8
  from diffusers.utils import load_image
9
+ import requests
10
 
11
  MAX_SEED = np.iinfo(np.int32).max
12
 
13
  pipe = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
14
 
15
  @spaces.GPU
16
+ def translate_albanian_to_english(text):
17
+ """Translate Albanian to English using sepioo-facebook-translation API."""
18
+ if not text.strip():
19
+ return ""
20
+ for attempt in range(2):
21
+ try:
22
+ response = requests.post(
23
+ "https://hal1993-mdftranslation1234567890abcdef1234567890-fc073a6.hf.space/v1/translate",
24
+ json={"from_language": "sq", "to_language": "en", "input_text": text},
25
+ headers={"accept": "application/json", "Content-Type": "application/json"},
26
+ timeout=5
27
+ )
28
+ response.raise_for_status()
29
+ translated = response.json().get("translate", "")
30
+ return translated
31
+ except Exception as e:
32
+ if attempt == 1:
33
+ raise gr.Error(f"Përkthimi dështoi: {str(e)}")
34
+ raise gr.Error("Përkthimi dështoi. Ju lutem provoni përsëri.")
35
+
36
+ @spaces.GPU
37
+ def infer(input_image, prompt, seed=42, randomize_seed=False, guidance_scale=2.5, steps=12, progress=gr.Progress(track_tqdm=True)):
38
  """
39
  Perform image editing using the FLUX.1 Kontext pipeline.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  """
41
+ # Translate Albanian prompt to English
42
+ final_prompt = translate_albanian_to_english(prompt.strip()) if prompt.strip() else ""
43
+ if not final_prompt:
44
+ return None, seed, gr.Button(visible=False)
45
+
46
  if randomize_seed:
47
  seed = random.randint(0, MAX_SEED)
48
 
 
50
  input_image = input_image.convert("RGB")
51
  image = pipe(
52
  image=input_image,
53
+ prompt=final_prompt,
54
  guidance_scale=guidance_scale,
55
+ width=input_image.size[0],
56
+ height=input_image.size[1],
57
  num_inference_steps=steps,
58
  generator=torch.Generator().manual_seed(seed),
59
  ).images[0]
60
  else:
61
  image = pipe(
62
+ prompt=final_prompt,
63
  guidance_scale=guidance_scale,
64
+ width=1024,
65
+ height=1024,
66
  num_inference_steps=steps,
67
  generator=torch.Generator().manual_seed(seed),
68
  ).images[0]
 
73
  image, seed, _ = infer(input_image, prompt)
74
  return image, seed
75
 
76
+ with gr.Blocks() as demo:
77
+ gr.HTML("""
78
+ <style>
79
+ body::before {
80
+ content: "";
81
+ display: block;
82
+ height: 320px;
83
+ background-color: var(--body-background-fill);
84
+ }
85
+ button[aria-label="Fullscreen"], button[aria-label="Fullscreen"]:hover {
86
+ display: none !important;
87
+ visibility: hidden !important;
88
+ opacity: 0 !important;
89
+ pointer-events: none !important;
90
+ }
91
+ button[aria-label="Share"], button[aria-label="Share"]:hover {
92
+ display: none !important;
93
+ }
94
+ button[aria-label="Download"] {
95
+ transform: scale(3);
96
+ transform-origin: top right;
97
+ margin: 0 !important;
98
+ padding: 6px !important;
99
+ }
100
+ </style>
101
+ """)
102
 
103
+ gr.Markdown("# Krijo Imazhe")
104
+ gr.Markdown("Gjenero imazhe të reja nga përshkrimin yt me fuqinë e inteligjencës artificiale.")
105
+
106
+ with gr.Column():
107
+ input_image = gr.Image(label="Ngarko Imazhin për Editim", type="pil")
108
+ prompt = gr.Textbox(
109
+ label="Përshkrimi",
110
+ placeholder="Shkruani përshkrimin këtu",
111
+ lines=3
112
+ )
113
+ run_button = gr.Button(value="Gjenero")
114
+ reuse_button = gr.Button("Rivendos këtë imazh", visible=False)
115
+ # Hidden advanced settings
116
+ seed = gr.Slider(
117
+ minimum=0,
118
+ maximum=MAX_SEED,
119
+ step=1,
120
+ value=0,
121
+ visible=False
122
+ )
123
+ randomize_seed = gr.Checkbox(value=True, visible=False)
124
+ guidance_scale = gr.Slider(
125
+ minimum=1,
126
+ maximum=10,
127
+ step=0.1,
128
+ value=2.5,
129
+ visible=False
130
+ )
131
+ steps = gr.Slider(
132
+ minimum=1,
133
+ maximum=30,
134
+ value=12,
135
+ step=1,
136
+ visible=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  )
138
+
139
+ with gr.Row():
140
+ result = gr.Image(label="Imazhi i Gjeneruar", interactive=False)
141
+
142
+ gr.Examples(
143
+ examples=[
144
+ ["flowers.png", "ktheji lulet në luledielli"],
145
+ ["monster.png", "bëje këtë përbindësh të hipë në një skateboard në plazh"],
146
+ ["cat.png", "bëje këtë mace të lumtur"]
147
+ ],
148
+ inputs=[input_image, prompt],
149
+ outputs=[result, seed],
150
+ fn=infer_example,
151
+ cache_examples="lazy"
152
+ )
153
+
154
  gr.on(
155
  triggers=[run_button.click, prompt.submit],
156
+ fn=infer,
157
+ inputs=[input_image, prompt, seed, randomize_seed, guidance_scale, steps],
158
+ outputs=[result, seed, reuse_button]
159
  )
160
  reuse_button.click(
161
+ fn=lambda image: image,
162
+ inputs=[result],
163
+ outputs=[input_image]
164
  )
165
 
166
  demo.launch(mcp_server=True)