Mehak-Mazhar commited on
Commit
16f5dea
·
verified ·
1 Parent(s): 24b2907

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -50
app.py CHANGED
@@ -1,64 +1,128 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
  """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
 
 
 
 
 
 
 
 
 
6
  """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
38
 
39
- response += token
40
- yield response
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
61
 
 
62
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
1
  """
2
+ Gradio Space: Text Image using FLUX.1 (Hugging Face Inference API)
3
+ Attractive interface with custom styling and footer label: "designed by Mehak Mazhar"
4
+
5
+ How to use:
6
+ 1. Install dependencies: pip install gradio requests pillow
7
+ 2. Get a Hugging Face API token (if you want to use the hosted FLUX.1 models) and either set it as an env var HF_TOKEN or paste it into the 'HF Token' field in the UI.
8
+ 3. Run: python gradio_flux_text2img.py
9
+
10
+ Notes: this script calls the Hugging Face Inference API for the model 'black-forest-labs/FLUX.1-schnell' by default.
11
+ You can change the MODEL variable to any compatible image generation model hosted on Hugging Face or point to your own inference server.
12
+
13
  """
 
14
 
15
+ import os
16
+ import io
17
+ import base64
18
+ import random
19
+ import requests
20
+ from PIL import Image
21
+ import gradio as gr
22
 
23
+ # --- Configuration ---
24
+ MODEL = os.environ.get("FLUX_MODEL", "black-forest-labs/FLUX.1-schnell")
25
+ HF_API_URL = f"https://api-inference.huggingface.co/models/{MODEL}"
 
 
 
 
 
 
26
 
27
+ # A small helper to call the Hugging Face Inference API (image generation)
28
+ def call_hf_image_api(prompt, token, width, height, guidance_scale, steps, seed, negative_prompt=None):
29
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
30
+ payload = {
31
+ "inputs": prompt,
32
+ "options": {"wait_for_model": True},
33
+ "parameters": {
34
+ "width": int(width),
35
+ "height": int(height),
36
+ "guidance_scale": float(guidance_scale),
37
+ "num_inference_steps": int(steps),
38
+ "seed": None if seed is None else int(seed),
39
+ }
40
+ }
41
+ if negative_prompt:
42
+ payload["parameters"]["negative_prompt"] = negative_prompt
43
 
44
+ # Many HF image models return binary image bytes directly. Some return JSON with base64.
45
+ resp = requests.post(HF_API_URL, headers=headers, json=payload, stream=True, timeout=120)
46
+ resp.raise_for_status()
47
 
48
+ content_type = resp.headers.get("content-type", "")
49
+ if "application/json" in content_type:
50
+ data = resp.json()
51
+ # attempt to find a base64 image in JSON response
52
+ # common key patterns: 'image', 'images', 'generated_images'
53
+ if isinstance(data, dict):
54
+ for k in ("image", "images", "generated_images", "artifacts"):
55
+ if k in data:
56
+ imgs = data[k]
57
+ if isinstance(imgs, list) and len(imgs) > 0:
58
+ b64 = imgs[0].get("data") if isinstance(imgs[0], dict) else imgs[0]
59
+ if isinstance(b64, str):
60
+ return Image.open(io.BytesIO(base64.b64decode(b64)))
61
+ # fallback: try to find base64 strings in the JSON
62
+ for v in data.values():
63
+ if isinstance(v, str) and v.strip().startswith("iVBOR"): # PNG base64 signature
64
+ return Image.open(io.BytesIO(base64.b64decode(v)))
65
+ raise ValueError("Could not parse image from JSON response")
66
+ else:
67
+ # assume raw image bytes
68
+ return Image.open(io.BytesIO(resp.content))
69
 
70
+ # --- Gradio UI ---
71
+ css = r'''
72
+ body { background: linear-gradient(135deg, #fff7e6 0%, #fffaf0 50%, #fff7fd 100%); }
73
+ .gradio-container { font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial; }
74
+ .header { display:flex; align-items:center; gap:16px; }
75
+ .logo { width:64px; height:64px; border-radius:14px; box-shadow: 0 6px 18px rgba(0,0,0,0.08); }
76
+ .card { background: rgba(255,255,255,0.9); border-radius:16px; padding:18px; box-shadow: 0 12px 30px rgba(0,0,0,0.06); }
77
+ .footer { text-align:center; font-size:12px; color:#555; margin-top:12px; }
78
+ .footer strong { color:#333; }
79
+ .generator-btn { border-radius: 12px; padding:10px 18px; }
80
+ '''
81
 
82
+ with gr.Blocks(css=css, title="Flux Text→Image — designed by Mehak Mazhar") as demo:
83
+ with gr.Row(elem_id="top-row"):
84
+ with gr.Column(scale=1):
85
+ gr.HTML("<div class='header'><img class='logo' src='https://raw.githubusercontent.com/black-forest-labs/flux/main/logo.png' alt='Flux logo' onerror='this.style.display=\'none\'' + "> <div><h2 style='margin:0'>FLUX.1 Text → Image</h2><p style='margin:0;color:#555;'>Generate high-quality images from text (Hugging Face inference API)</p></div></div>")
86
 
87
+ with gr.Row():
88
+ with gr.Column(scale=1, min_width=360):
89
+ prompt = gr.Textbox(label="Prompt", placeholder="A serene mountain lake at sunset, digital painting, ultra-detailed", rows=4)
90
+ negative = gr.Textbox(label="Negative prompt (optional)", placeholder="blurry, lowres, text, watermark", rows=2)
91
+ hf_token = gr.Textbox(label="Hugging Face API Token (optional)", placeholder="Paste your HF token here or set HF_TOKEN env var", type="password")
92
+ with gr.Row():
93
+ width = gr.Dropdown(choices=[256,384,512,768,1024], value=512, label="Width")
94
+ height = gr.Dropdown(choices=[256,384,512,768,1024], value=512, label="Height")
95
+ with gr.Row():
96
+ steps = gr.Slider(10, 150, value=28, step=1, label="Steps")
97
+ guidance = gr.Slider(1.0, 30.0, value=7.5, step=0.1, label="Guidance scale")
98
+ with gr.Row():
99
+ seed = gr.Number(value=None, precision=0, label="Seed (leave blank for random)")
100
+ gen_btn = gr.Button("Generate", elem_classes="generator-btn")
101
+ info = gr.Markdown("**Tip:** Use vivid, descriptive prompts. Try styles like `cinematic lighting`, `digital oil painting`, or `ultra-detailed`.")
102
 
103
+ with gr.Column(scale=1, min_width=360):
104
+ gallery = gr.Gallery(label="Generated images", show_label=True, elem_id="gallery").style(grid=[2], height="640px")
105
+ out_log = gr.Textbox(label="Status / Debug log", lines=4, interactive=False)
106
+
107
+ # Footer with the requested label
108
+ gr.HTML("<div class='footer'>\n<p><strong>designed by Mehak Mazhar</strong></p>\n</div>")
109
+
110
+ def generate_image(prompt_text, negative_text, hf_token_text, width_v, height_v, steps_v, guidance_v, seed_v):
111
+ token = hf_token_text.strip() or os.environ.get("HF_TOKEN")
112
+ if not token:
113
+ return None, "ERROR: No Hugging Face token provided. Set HF_TOKEN or paste it into the UI."
114
+ try:
115
+ if seed_v in (None, "", 0):
116
+ seed_val = random.randint(0, 2**31 - 1)
117
+ else:
118
+ seed_val = int(seed_v)
119
+ img = call_hf_image_api(prompt_text, token, width_v, height_v, guidance_v, steps_v, seed_val, negative_prompt=negative_text)
120
+ return [img], f"OK — seed={seed_val}, model={MODEL}"
121
+ except Exception as e:
122
+ return None, f"API error: {e}"
123
 
124
+ gen_btn.click(fn=generate_image, inputs=[prompt, negative, hf_token, width, height, steps, guidance, seed], outputs=[gallery, out_log])
125
 
126
+ # Run the app when executed directly
127
  if __name__ == "__main__":
128
+ demo.launch(server_name="0.0.0.0", share=False)