import base64, io, random, torch, gradio as gr from diffusers import DiffusionPipeline from PIL import Image MODEL_ID = "JingyeChen22/textdiffuser2-full-ft" device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float16 if device == "cuda" else torch.float32 pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=dtype).to(device) def gen_image(prompt, main_text, sub_text, negative_prompt, width, height, steps, guidance, seed): # seed if seed is None or str(seed).strip() == "": seed = random.randint(1, 2**31 - 1) g = torch.Generator(device=device).manual_seed(int(seed)) # prompt structuré pour TextDiffuser-2 full_prompt = f"{prompt}\ntext: '{main_text}'\nsubtext: '{sub_text}'" img = pipe( prompt=full_prompt, negative_prompt=negative_prompt if negative_prompt else None, num_inference_steps=int(steps), guidance_scale=float(guidance), width=int(width), height=int(height), generator=g ).images[0] # retour base64 pour un usage direct via API buf = io.BytesIO() img.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode("utf-8") return img, str(seed), b64 with gr.Blocks() as demo: gr.Markdown("### TextDiffuser-2 — API pour visuels LinkedIn (HF Space)") with gr.Row(): with gr.Column(): prompt = gr.Textbox(label="Background prompt", value="Professional LinkedIn poster background, deep blue gradient, Quebec map in connected nodes, innovation & cybersecurity icons, clean corporate layout, high contrast") main_text = gr.Textbox(label="Main title", value="SOUVERAINETÉ NUMÉRIQUE AU QUÉBEC") sub_text = gr.Textbox(label="Subtitle", value="Un avantage compétitif réel ?") negative_prompt = gr.Textbox(label="Negative prompt (optional)", value="blurry, misspelled text, distorted letters, artifacts, cluttered layout") width = gr.Number(label="Width", value=1200, precision=0) height = gr.Number(label="Height", value=627, precision=0) steps = gr.Slider(10, 60, value=40, step=1, label="Steps") guidance = gr.Slider(3.0, 12.0, value=7.5, step=0.5, label="Guidance") seed = gr.Textbox(label="Seed (optional)") btn = gr.Button("Generate") with gr.Column(): out_img = gr.Image(label="Result", type="pil") out_seed = gr.Textbox(label="Used seed") out_b64 = gr.Textbox(label="Base64 PNG (for API)") btn.click(gen_image, inputs=[prompt, main_text, sub_text, negative_prompt, width, height, steps, guidance, seed], outputs=[out_img, out_seed, out_b64]) demo.launch()