Download app.py from aymce/pinky: direct link, hf CLI and curl.
- Browser
- Download file 6.96 kB
-
https://huggingface.co/spaces/aymce/pinky/resolve/main/app.py
- Command line
-
hf download hf://spaces/aymce/pinky/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aymce/pinky/resolve/main/app.py
6.96 kB
| # app.py — PINKY Maker (Hugging Face Spaces + Replicate, UI couleurs + accessoires) | |
| import os, random, traceback | |
| from io import BytesIO | |
| from PIL import Image | |
| import requests | |
| import gradio as gr | |
| import replicate | |
| # ========= CONFIG ========= | |
| SPACE_ID = os.getenv("SPACE_ID", "") | |
| BASE_IMG_URL = f"https://huggingface.co/spaces/{SPACE_ID}/resolve/main/pinky-monster.png" | |
| # ⚠️ Référence Replicate du modèle img2img (avec :hash exact depuis ton compte) | |
| MODEL = "stability-ai/stable-diffusion-img2img:15a3689ee13b0d2616e98820eca31d4c3abcd36672df6afce5cb6feb1d66087d" | |
| # ========================== | |
| def generate(prompt, strength, guidance, steps, seed, count): | |
| """Appelle Replicate en img2img et renvoie des PIL.Images (ou un placeholder + note).""" | |
| def _fetch_image_from_url(url: str) -> Image.Image: | |
| r = requests.get(url, timeout=120) | |
| r.raise_for_status() | |
| return Image.open(BytesIO(r.content)).convert("RGB") | |
| def _fileoutput_to_image(file_obj) -> Image.Image: | |
| if hasattr(file_obj, "read"): | |
| data = file_obj.read() | |
| return Image.open(BytesIO(data)).convert("RGB") | |
| if hasattr(file_obj, "open"): | |
| with file_obj.open() as f: | |
| data = f.read() | |
| return Image.open(BytesIO(data)).convert("RGB") | |
| if hasattr(file_obj, "path"): | |
| with open(file_obj.path, "rb") as f: | |
| data = f.read() | |
| return Image.open(BytesIO(data)).convert("RGB") | |
| raise RuntimeError(f"Type de sortie Replicate non géré: {type(file_obj)}") | |
| token = os.getenv("REPLICATE_API_TOKEN") | |
| if not token: | |
| note = "❌ Ajoute REPLICATE_API_TOKEN (Settings → Secrets)." | |
| return [Image.new("RGB", (768, 768), (30, 30, 30))], gr.update(value=note) | |
| # Vérifie l’accessibilité de l’image Pinky | |
| try: | |
| test = requests.get(BASE_IMG_URL, timeout=30) | |
| if test.status_code != 200: | |
| note = f"❌ Image introuvable : {BASE_IMG_URL}\nUpload ‘pinky-monster.png’ à la racine du Space." | |
| return [Image.new("RGB", (768, 768), (30, 30, 30))], gr.update(value=note) | |
| except Exception as e: | |
| note = f"❌ Erreur en lisant l'image de base : {e}" | |
| return [Image.new("RGB", (768, 768), (30, 30, 30))], gr.update(value=note) | |
| client = replicate.Client(api_token=token) | |
| # Seed sûr (toujours un int) | |
| try: | |
| s = int(seed) | |
| except Exception: | |
| s = 0 | |
| use_seed_base = s if s != 0 else random.randint(1, 2_000_000_000) | |
| imgs, note = [], "✅ Génération OK" | |
| try: | |
| for i in range(int(count)): | |
| use_seed = use_seed_base + i | |
| out = client.run( | |
| MODEL, | |
| input={ | |
| "prompt": str(prompt), | |
| "image": BASE_IMG_URL, | |
| "prompt_strength": float(strength), # 0.45–0.55 pour garder l’identité | |
| "num_inference_steps": int(steps), # 24–28 | |
| "guidance_scale": float(guidance), # ~6–7.5 | |
| "seed": int(use_seed), | |
| "width": 768, | |
| "height": 768, | |
| }, | |
| ) | |
| # Normalement: list[str] ou list[FileOutput] | |
| if isinstance(out, list) and out: | |
| first = out[0] | |
| if isinstance(first, str): | |
| img = _fetch_image_from_url(first) | |
| else: | |
| img = _fileoutput_to_image(first) | |
| elif isinstance(out, str): | |
| img = _fetch_image_from_url(out) | |
| else: | |
| # petit filet de sécurité | |
| raise RuntimeError(f"Sortie Replicate inattendue: {out}") | |
| imgs.append(img) | |
| except replicate.exceptions.ReplicateError as e: | |
| msg = str(e) | |
| if "Insufficient credit" in msg or "status: 402" in msg: | |
| note = ("❌ Plus de crédits Replicate.\n" | |
| "➡️ Ajoute du crédit sur replicate.com/account/billing puis relance.") | |
| else: | |
| note = f"❌ Erreur Replicate: {msg}\n\nTrace:\n{traceback.format_exc()}" | |
| if not imgs: | |
| imgs = [Image.new("RGB", (768, 768), (30, 30, 30))] | |
| except Exception as e: | |
| note = f"❌ Erreur: {e}\n\nTrace:\n{traceback.format_exc()}" | |
| if not imgs: | |
| imgs = [Image.new("RGB", (768, 768), (30, 30, 30))] | |
| return imgs, gr.update(value=note) | |
| # ========= UI (couleur + accessoires → prompt auto) ========= | |
| def build_prompt(color: str, accessories: list[str]) -> str: | |
| acc = ", ".join(accessories) if accessories else "no accessories" | |
| return ( | |
| 'same monster as the reference image, keep the exact same body shape, proportions, big round eyes, ' | |
| 'necklace with the text "PINKY" unchanged, same pose and background, studio cinematic lighting. ' | |
| f'CHANGE ONLY: fur color to {color}. ADD ACCESSORIES: {acc}. ' | |
| 'do not change the face, do not change the necklace text, no mutations, no extra limbs, ' | |
| 'no text variations, no letter changes, no different background, no different pose.' | |
| ) | |
| with gr.Blocks(title="PINKY Maker") as demo: | |
| gr.Markdown("### 🐲 PINKY Maker — change UNIQUEMENT la couleur + accessoires (identité conservée)") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| color = gr.Dropdown( | |
| label="Couleur de la fourrure", | |
| choices=["rose", "bleu", "vert", "noir", "rouge", "violet", "blanc"], | |
| value="bleu" | |
| ) | |
| accessories = gr.CheckboxGroup( | |
| label="Accessoires", | |
| choices=["chaîne dorée", "lunettes noires", "cornes", "veste en cuir", "bracelet", "visière néon"], | |
| value=["chaîne dorée"] | |
| ) | |
| strength = gr.Slider(0.1, 0.9, value=0.5, step=0.01, label="Force (fidèle ↔ créatif)") | |
| guidance = gr.Slider(1, 15, value=6.5, step=0.5, label="Guidance") | |
| steps = gr.Slider(10, 50, value=26, step=1, label="Pas (qualité/temps)") | |
| seed = gr.Number(value=12345, precision=0, label="Seed (reproductible)") | |
| count = gr.Slider(1, 4, value=1, step=1, label="Nombre d'images") | |
| go = gr.Button("Générer", variant="primary") | |
| status = gr.Markdown(value="Prêt.") | |
| with gr.Column(scale=2): | |
| gallery = gr.Gallery(label="Résultats", height=520) | |
| # on fabrique le prompt avant d'appeler generate | |
| def _run(c, a, st, g, sp, sd, ct): | |
| return generate(build_prompt(c, a), st, g, sp, sd, ct) | |
| go.click( | |
| _run, | |
| inputs=[color, accessories, strength, guidance, steps, seed, count], | |
| outputs=[gallery, status], | |
| api_name="generate", | |
| ) | |
| # 👉 Hugging Face Spaces détecte cette variable | |
| app = demo | |
| # (utile en local, inoffensif sur Spaces) | |
| if __name__ == "__main__": | |
| demo.launch() |