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|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
|
| 5 |
+
# -------------------------
|
| 6 |
+
# 1) Secrets (from environment variables)
|
| 7 |
+
# -------------------------
|
| 8 |
+
# Make sure you set these in your environment or a .env file
|
| 9 |
+
# Example in Linux/macOS:
|
| 10 |
+
# export GROQ_API_KEY="your_key"
|
| 11 |
+
# export HUGGINGFACEHUB_API_TOKEN="your_token"
|
| 12 |
+
|
| 13 |
+
os.environ["HF_TOKEN"] = os.environ.get("HUGGINGFACEHUB_API_TOKEN", "")
|
| 14 |
+
|
| 15 |
+
if not os.environ.get("GROQ_API_KEY"):
|
| 16 |
+
raise ValueError("β Missing GROQ_API_KEY in environment variables")
|
| 17 |
+
|
| 18 |
+
if not os.environ.get("HUGGINGFACEHUB_API_TOKEN"):
|
| 19 |
+
print("β οΈ HUGGINGFACEHUB_API_TOKEN missing. If a model is gated, it may fail to download.")
|
| 20 |
+
|
| 21 |
+
# -------------------------
|
| 22 |
+
# 2) Device config
|
| 23 |
+
# -------------------------
|
| 24 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 25 |
+
dtype = torch.float16 if device == "cuda" else torch.float32
|
| 26 |
+
print("Device:", device)
|
| 27 |
+
|
| 28 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 29 |
+
|
| 30 |
+
# -------------------------
|
| 31 |
+
# 3) LangChain (Groq)
|
| 32 |
+
# -------------------------
|
| 33 |
+
from langchain_groq import ChatGroq
|
| 34 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 35 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 36 |
+
|
| 37 |
+
llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0.7)
|
| 38 |
+
|
| 39 |
+
prompt_refiner = ChatPromptTemplate.from_template("""
|
| 40 |
+
You are an expert AI prompt engineer for SDXL text-to-image generation.
|
| 41 |
+
Convert the user's idea into a high-quality image prompt.
|
| 42 |
+
|
| 43 |
+
Rules:
|
| 44 |
+
- concise (max 60 words)
|
| 45 |
+
- include subject, environment, lighting, composition, style
|
| 46 |
+
- avoid brand names, watermarks, copyrighted characters
|
| 47 |
+
- keep any style the user mentions (anime/realistic/etc.)
|
| 48 |
+
|
| 49 |
+
User idea: {text}
|
| 50 |
+
|
| 51 |
+
Final image prompt:
|
| 52 |
+
""")
|
| 53 |
+
|
| 54 |
+
caption_refiner = ChatPromptTemplate.from_template("""
|
| 55 |
+
You are an expert image caption editor.
|
| 56 |
+
Rewrite the caption in clear, neutral English (1β2 sentences). No identity guessing.
|
| 57 |
+
|
| 58 |
+
Raw caption: {caption}
|
| 59 |
+
|
| 60 |
+
Final caption:
|
| 61 |
+
""")
|
| 62 |
+
|
| 63 |
+
prompt_chain = prompt_refiner | llm | StrOutputParser()
|
| 64 |
+
caption_chain = caption_refiner | llm | StrOutputParser()
|
| 65 |
+
|
| 66 |
+
NEG_DEFAULT = "lowres, blurry, bad anatomy, extra fingers, watermark, text, logo, jpeg artifacts, deformed"
|
| 67 |
+
|
| 68 |
+
# -------------------------
|
| 69 |
+
# 4) SDXL pipeline
|
| 70 |
+
# -------------------------
|
| 71 |
+
from diffusers import StableDiffusionXLPipeline
|
| 72 |
+
|
| 73 |
+
MODEL_ID = "playgroundai/playground-v2.5-1024px-aesthetic"
|
| 74 |
+
|
| 75 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 76 |
+
MODEL_ID,
|
| 77 |
+
torch_dtype=dtype,
|
| 78 |
+
use_safetensors=True,
|
| 79 |
+
token=os.environ.get("HUGGINGFACEHUB_API_TOKEN") or None
|
| 80 |
+
).to(device)
|
| 81 |
+
|
| 82 |
+
pipe.enable_attention_slicing()
|
| 83 |
+
try:
|
| 84 |
+
pipe.enable_vae_tiling()
|
| 85 |
+
except Exception:
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
pipe.safety_checker = None
|
| 89 |
+
|
| 90 |
+
def _gen(seed: int):
|
| 91 |
+
seed = int(seed)
|
| 92 |
+
return torch.Generator(device="cuda").manual_seed(seed) if device == "cuda" else torch.Generator().manual_seed(seed)
|
| 93 |
+
|
| 94 |
+
@torch.inference_mode()
|
| 95 |
+
def text_to_image(user_text, steps=30, guidance=6.5, seed=123, size=1024, negative_prompt=NEG_DEFAULT):
|
| 96 |
+
if not user_text or not str(user_text).strip():
|
| 97 |
+
raise ValueError("Please enter a non-empty prompt.")
|
| 98 |
+
|
| 99 |
+
enhanced = prompt_chain.invoke({"text": user_text}).strip()
|
| 100 |
+
|
| 101 |
+
g = _gen(seed)
|
| 102 |
+
img = pipe(
|
| 103 |
+
prompt=enhanced,
|
| 104 |
+
negative_prompt=negative_prompt,
|
| 105 |
+
num_inference_steps=int(steps),
|
| 106 |
+
guidance_scale=float(guidance),
|
| 107 |
+
height=int(size),
|
| 108 |
+
width=int(size),
|
| 109 |
+
generator=g
|
| 110 |
+
).images[0]
|
| 111 |
+
return enhanced, img
|
| 112 |
+
|
| 113 |
+
# -------------------------
|
| 114 |
+
# 5) Image β Text (BLIP)
|
| 115 |
+
# -------------------------
|
| 116 |
+
from transformers import pipeline as hf_pipeline
|
| 117 |
+
|
| 118 |
+
caption_model = hf_pipeline(
|
| 119 |
+
"image-to-text",
|
| 120 |
+
model="Salesforce/blip-image-captioning-base",
|
| 121 |
+
device=0 if device == "cuda" else -1
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def image_to_text(img):
|
| 125 |
+
if img is None:
|
| 126 |
+
raise ValueError("Please upload an image.")
|
| 127 |
+
raw = caption_model(img)[0]["generated_text"].strip()
|
| 128 |
+
refined = caption_chain.invoke({"caption": raw}).strip()
|
| 129 |
+
return raw, refined
|
| 130 |
+
|
| 131 |
+
# -------------------------
|
| 132 |
+
# 6) Gradio App
|
| 133 |
+
# -------------------------
|
| 134 |
+
import gradio as gr
|
| 135 |
+
|
| 136 |
+
with gr.Blocks(title="LangChain Text β Image (SDXL, Secure)") as app:
|
| 137 |
+
gr.Markdown("## π LangChain Text β Image (SDXL, Secret Key Based) β Better Quality on T4")
|
| 138 |
+
|
| 139 |
+
with gr.Tab("Text β Image (SDXL)"):
|
| 140 |
+
txt = gr.Textbox(label="Enter text prompt", placeholder="e.g., A futuristic hospital lab with AI robots, cinematic lighting, ultra-detailed")
|
| 141 |
+
with gr.Row():
|
| 142 |
+
size = gr.Radio([512, 1024], value=1024, label="Resolution (Use 512 if OOM)")
|
| 143 |
+
seed = gr.Number(value=123, label="Seed")
|
| 144 |
+
with gr.Row():
|
| 145 |
+
steps = gr.Slider(10, 50, value=30, step=1, label="Steps (Quality β with steps)")
|
| 146 |
+
guidance = gr.Slider(1.0, 10.0, value=6.5, step=0.1, label="Guidance (5β8 best)")
|
| 147 |
+
negative = gr.Textbox(value=NEG_DEFAULT, label="Negative prompt (quality control)")
|
| 148 |
+
btn1 = gr.Button("Generate Image")
|
| 149 |
+
|
| 150 |
+
refined_prompt = gr.Textbox(label="Enhanced Prompt (LangChain)", interactive=False)
|
| 151 |
+
img = gr.Image(label="Generated Image")
|
| 152 |
+
|
| 153 |
+
btn1.click(text_to_image, [txt, steps, guidance, seed, size, negative], [refined_prompt, img])
|
| 154 |
+
|
| 155 |
+
with gr.Tab("Image β Text"):
|
| 156 |
+
img_in = gr.Image(type="pil", label="Upload image")
|
| 157 |
+
btn2 = gr.Button("Generate Caption")
|
| 158 |
+
raw = gr.Textbox(label="Raw Caption (BLIP)", interactive=False)
|
| 159 |
+
clean = gr.Textbox(label="Refined Caption (LangChain)", interactive=False)
|
| 160 |
+
|
| 161 |
+
btn2.click(image_to_text, img_in, [raw, clean])
|
| 162 |
+
|
| 163 |
+
app.launch(share=True)
|