Spaces:
JustinD
/
1
Running on Zero

JustinD commited on
Commit
e88b91e
·
verified ·
1 Parent(s): 32d67f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -1168
app.py CHANGED
@@ -1,1170 +1,36 @@
1
- # ===== LINE 1: MUST BE SPACES FOR ZEROGPU =====
2
- try:
3
- import spaces
4
- SPACES_AVAILABLE = True
5
- print("ZeroGPU mode enabled")
6
- except ImportError:
7
- SPACES_AVAILABLE = False
8
- print("Running without Spaces (no ZeroGPU)")
9
-
10
- """
11
- Roulette Lab for JustinD/1.
12
-
13
- One button rolls a random recipe (chef, style, scene, outfit, pose, light,
14
- camera, woman). Lock any field and the next roll only spins the rest.
15
- Optional "Tease then reveal" renders the same seed twice.
16
- Art mode: Cartoon (default, anime and illustration chefs only) or Photo.
17
- Nude frame mode: fresh render same seed (default), fresh render new seed,
18
- or reveal from the clothed picture (img2img). LoRA slot and sampler dropdown.
19
- Compel weights the clothed and nude words so the two frames really differ.
20
- Picture upload (optional): "Copy the look" steers style, outfit and mood with
21
- IP-Adapter; "Redraw my pic" repaints your picture with img2img. Faces always
22
- come from the random deck, never from the uploaded picture.
23
- Fiction only. Adult women 21+ (late 20s) only.
24
- """
25
-
26
- import sys
27
- import os
28
- import re
29
- import io
30
- import gc
31
- import time
32
- import random
33
- import logging
34
- import threading
35
-
36
- import torch
37
  import gradio as gr
38
- from huggingface_hub import hf_hub_download, HfApi, CommitOperationAdd
39
-
40
- logging.basicConfig(
41
- level=logging.INFO,
42
- format="%(asctime)s - %(levelname)s - %(message)s",
43
- handlers=[logging.StreamHandler(sys.stdout)],
44
- )
45
- logger = logging.getLogger("RouletteLab")
46
- logger.info("Roulette Lab boot (21+ adult women only, fiction only)")
47
-
48
- # ---------------------------------------------------------------------------
49
- # Settings
50
- # ---------------------------------------------------------------------------
51
- BACKUP_DATASET_ID = "JustinD/generation-images"
52
- LOG_VISITOR_UPLOADS = os.environ.get("LOG_VISITOR_UPLOADS", "0").strip().lower() in {"1", "true", "yes"}
53
- COOLDOWN_SECONDS = 12
54
- LAST_GEN_TIME = {}
55
- HISTORY_SIZE = 10
56
- GALLERY_SIZE = 12
57
-
58
- DEFAULT_STEPS = 28
59
- DEFAULT_GUIDANCE = 6.0
60
-
61
- SIZE_PRESETS = {
62
- "Portrait 832x1216": (832, 1216),
63
- "Landscape 1344x768": (1344, 768),
64
- "Square 1024x1024": (1024, 1024),
65
- }
66
-
67
- # ---------------------------------------------------------------------------
68
- # Chefs: diffusers SDXL repos, tagged by what they draw best
69
- # ---------------------------------------------------------------------------
70
- CHEFS = {
71
- # photoreal
72
- "Lustify GGWP v7": {"repo": "John6666/lustify-sdxl-nsfw-checkpoint-ggwp-v7-sdxl", "kind": "photo"},
73
- "Lustify Endgame": {"repo": "John6666/lustify-sdxl-nsfwsfw-endgame-sdxl", "kind": "photo"},
74
- "URPM XL v6": {"repo": "John6666/uber-realistic-porn-merge-xl-urpmxl-v6final-sdxl", "kind": "photo"},
75
- "PornWorks Sexy Beauty v04": {"repo": "John6666/pornworks-sexy-beauty-v04-sdxl", "kind": "photo"},
76
- "OhMySister Asian Woman": {"repo": "John6666/oms-oh-my-sister-beautiful-asian-woman-v10-sdxl", "kind": "photo"},
77
- # anime / illustration
78
- "WAI NSFW Illustrious v150": {"repo": "John6666/wai-nsfw-illustrious-sdxl-v150-sdxl", "kind": "anime"},
79
- "PornMaster Anime Illustrious": {"repo": "John6666/pornmaster-anime-illustrious-v2-sdxl", "kind": "anime"},
80
- "Perfection Asian Illustrious": {"repo": "John6666/perfection-asian-ilxl-illustrious-xl-nsfw-sfw-checkpoint-v10-sdxl", "kind": "anime"},
81
- "Janku v5 Illustrious": {"repo": "John6666/janku-v5-nsfw-trained-noobai-rou-wei-illustrious-xl-v50-sdxl", "kind": "anime"},
82
- "Unearthly NSFW Illustrious": {"repo": "John6666/unearthly-nsfw-illustrious-sdxl-20250610b-sdxl", "kind": "anime"},
83
- }
84
-
85
- # ---------------------------------------------------------------------------
86
- # Decks
87
- # ---------------------------------------------------------------------------
88
- # Each style says which chef kinds suit it, so an unlocked chef is drawn from a matching pool.
89
- STYLES = {
90
- # Justin's favourite, listed first so it is easy to pick in the Style dropdown
91
- "Glossy mono anime": {
92
- "kinds": ["anime"],
93
- "prefix": "monochrome, grayscale, glossy anime illustration, oily shiny skin, wet skin, water droplets, "
94
- "soft studio light, long wavy dark hair, sultry half lidded eyes, slim tall body, tiny waist, "
95
- "toned stomach, long legs, standing pose, minimal plain room background",
96
- "neg": "color, photo, realistic, 3d render",
97
- },
98
- "Modern anime key visual": {
99
- "kinds": ["anime"],
100
- "prefix": "modern anime key visual, crisp clean lineart, vibrant cel shading, detailed glossy eyes, bloom lighting, high contrast",
101
- "neg": "photo, realistic, 3d render, sketch",
102
- },
103
- "Hentai doujin cel": {
104
- "kinds": ["anime"],
105
- "prefix": "hentai doujin style, bold ink lineart, flat cel shading, blush stickers, glossy skin highlights, manga panel energy",
106
- "neg": "photo, realistic, 3d render, painterly",
107
- },
108
- "Western cartoon pin up": {
109
- "kinds": ["anime"],
110
- "prefix": "western cartoon pin up, bold outlines, exaggerated curves, saturated flat colors, retro 1950s pin up poster",
111
- "neg": "photo, realistic, anime eyes, 3d render",
112
- },
113
- "Manhwa webtoon glossy": {
114
- "kinds": ["anime"],
115
- "prefix": "korean manhwa webtoon art, glossy digital painting, soft gradient shading, sharp elegant lineart, shiny highlights on skin",
116
- "neg": "photo, realistic, 3d render, rough sketch",
117
- },
118
- "Photoreal": {
119
- "kinds": ["photo"],
120
- "prefix": "photorealistic photo, RAW photo, 85mm lens, natural skin texture, sharp focus",
121
- "neg": "anime, cartoon, illustration, drawing, painting, 3d render",
122
- },
123
- "90s anime cel": {
124
- "kinds": ["anime"],
125
- "prefix": "retro 90s anime cel shading, vintage anime key visual, airbrushed highlights, film grain, glossy reflective surfaces",
126
- "neg": "photo, realistic, 3d render",
127
- },
128
- "Painted PVC figure": {
129
- "kinds": ["anime"],
130
- "prefix": "anime figurine, painted PVC 1/7 scale statue, smooth matte skin finish, round display base, product photography, soft studio light",
131
- "neg": "flat illustration, sketch, real skin pores",
132
- },
133
- "Pop art engraving": {
134
- "kinds": ["anime", "photo"],
135
- "prefix": "pop art, Victorian engraving linework, crosshatching, halftone dots, neon pink outline, flat magenta cyan and orange colors",
136
- "neg": "photo, soft gradient, 3d render",
137
- },
138
- "Flat vector pin up": {
139
- "kinds": ["anime"],
140
- "prefix": "flat vector illustration, modern pin up, clean linework, flat color blocks with one soft shade, muted dark background",
141
- "neg": "photo, realistic, 3d render, heavy texture",
142
- },
143
- "Oil painting impasto": {
144
- "kinds": ["anime"],
145
- "prefix": "oil painting, thick impasto brushstrokes, visible canvas texture, rich chiaroscuro, classical figure painting, nice tits",
146
- "neg": "photo, flat vector, cel shading",
147
- },
148
- }
149
-
150
- SCENES = [
151
- "",
152
- ]
153
-
154
- # Every spin makes a pair with the same seed: one clothed, one nude
155
- CLOTHED_OUTFITS = [
156
- "",
157
- ]
158
- NUDE_OUTFITS = [
159
- "",
160
- ]
161
- OUTFITS = CLOTHED_OUTFITS
162
-
163
- POSES = [
164
- "",
165
- ]
166
-
167
- LIGHTS = [
168
- "",
169
- ]
170
-
171
- CAMERAS = [
172
- "",
173
- ]
174
-
175
- # Face randomizer (body lock never changes)
176
- ETHNICITIES = ["Japanese", "Korean", "Chinese", "Taiwanese", "Vietnamese", "Thai", "Filipino", "Indonesian", "Malaysian"]
177
- HAIRS = [
178
- "",
179
- ]
180
- FACES = [
181
- "",
182
- ]
183
- DEFAULT_FACE = ""
184
-
185
- # Tease then reveal: frame 1 states
186
- TEASE_STATES = [
187
- "",
188
- ]
189
-
190
- # ---------------------------------------------------------------------------
191
- # LoRA slot (every repo id and file name checked on the HF Hub API, Oct 24 2026)
192
- # ---------------------------------------------------------------------------
193
- LORA_NONE = "None"
194
- LORA_CUSTOM = "Custom (repo id + file below)"
195
- LORAS = {
196
- "Breast size slider (anime chefs, Illustrious)": {
197
- "repo": "Muapi/breast-size-slider-lora-illustriousxl",
198
- "file": "breast-size-slider-lora-illustriousxl.safetensors",
199
- },
200
- "Oppai large breasts slim body (anime chefs, Pony/Illustrious)": {
201
- "repo": "Muapi/oppai-large-breasts-slim-body",
202
- "file": "oppai-large-breasts-slim-body.safetensors",
203
- },
204
- "Skinny to voluptuous slider (photo chefs, SDXL)": {
205
- "repo": "Muapi/skinny-voluptous-slider-sdxl",
206
- "file": "skinny-voluptous-slider-sdxl.safetensors",
207
- },
208
- "Asian features slider (photo chefs, SDXL)": {
209
- "repo": "ntc-ai/SDXL-LoRA-slider.asian",
210
- "file": "asian.safetensors",
211
- },
212
- "Add detail XL (photo chefs, SDXL)": {
213
- "repo": "highscoregames12018/add-detail-xl",
214
- "file": "add-detail-xl.safetensors",
215
- },
216
- }
217
- LORA_CHOICES = [LORA_NONE] + list(LORAS) + [LORA_CUSTOM]
218
- DEFAULT_LORA_STRENGTH = 0.8
219
- LORA_ADAPTER = "roulette_lora"
220
- REPO_ID_PATTERN = re.compile(r"^[A-Za-z0-9][\w.\-]*/[\w.\-]+$")
221
-
222
- # ---------------------------------------------------------------------------
223
- # Samplers (set per spin from the chef's own scheduler config)
224
- # ---------------------------------------------------------------------------
225
- SAMPLERS = ["Euler a", "DPM++ 2M Karras", "DPM++ SDE Karras", "UniPC"]
226
- DEFAULT_SAMPLER = "Euler a"
227
-
228
- # Nude frame: how frame 2 is made
229
- NUDE_MODE_SAME = "Fresh render same seed"
230
- NUDE_MODE_NEW = "Fresh render new seed"
231
- NUDE_MODE_REVEAL = "Reveal from clothed picture"
232
- NUDE_MODES = [NUDE_MODE_SAME, NUDE_MODE_NEW, NUDE_MODE_REVEAL]
233
- DEFAULT_NUDE_MODE = NUDE_MODE_SAME
234
- # Reveal strength: 0.55 kept the clothes, so start high
235
- DEFAULT_REVEAL_STRENGTH = 0.72
236
- REVEAL_MIN, REVEAL_MAX = 0.4, 0.9
237
-
238
- # Art mode: which styles and chefs a spin may draw
239
- ART_CARTOON = "Cartoon"
240
- ART_PHOTO = "Photo"
241
- ART_MODES = [ART_CARTOON, ART_PHOTO]
242
- DEFAULT_ART_MODE = ART_CARTOON
243
- ART_KIND = {ART_CARTOON: "anime", ART_PHOTO: "photo"}
244
- STYLE_RANDOM = "Roll random"
245
-
246
- # Reference picture upload
247
- PIC_OFF = "Off"
248
- PIC_LOOK = "Copy the look"
249
- PIC_REDRAW = "Redraw my pic"
250
- PIC_MODES = [PIC_OFF, PIC_LOOK, PIC_REDRAW]
251
- DEFAULT_PIC_MODE = PIC_OFF
252
- DEFAULT_LOOK_STRENGTH = 0.6
253
- LOOK_MIN, LOOK_MAX = 0.2, 1.0
254
- DEFAULT_REDRAW_STRENGTH = 0.6
255
- REDRAW_MIN, REDRAW_MAX = 0.3, 0.9
256
- # IP-Adapter for SDXL, ViT-H variant (file list checked on the HF Hub API, Oct 24 2026).
257
- # General look adapter only: the face adapters in that repo are deliberately not used.
258
- IP_REPO = "h94/IP-Adapter"
259
- IP_SUBFOLDER = "sdxl_models"
260
- IP_WEIGHT = "ip-adapter_sdxl_vit-h.safetensors"
261
- IP_ENCODER_FOLDER = "models/image_encoder" # ViT-H encoder, 2.5 GB (smaller than the bigG one)
262
- IP_FILES = [
263
- f"{IP_SUBFOLDER}/{IP_WEIGHT}",
264
- f"{IP_ENCODER_FOLDER}/config.json",
265
- f"{IP_ENCODER_FOLDER}/model.safetensors",
266
- ]
267
-
268
- FIELDS = ["chef", "style", "scene", "outfit", "nude_look", "pose", "light", "camera", "woman"]
269
-
270
- # ---------------------------------------------------------------------------
271
- # Hard locks
272
- # ---------------------------------------------------------------------------
273
- ADULT_TAGS = "masterpiece, best quality, 1girl, solo, adult woman over 21, late 20s, fictional character"
274
- # No "21+" here: in compel a trailing + means "weight up", so plain words only
275
- FRAME_HEAD = "1girl, solo, adult woman over 21, late 20s, Asian woman"
276
- ASIAN_LOCK = "beautiful Asian woman, Asian facial features, Asian eyes, dark hair"
277
- BODY_LOCK = (
278
- "tall, slim body, small frame, tiny waist, "
279
- "huge breasts, very large breasts, heavy full round breasts, busty, deep cleavage, slender thighs"
280
- )
281
-
282
- # Short versions so the important words fit inside the first 75 tokens
283
- BODY_LOCK_SHORT = "huge breasts, very large breasts, busty, tall, slim, tiny waist"
284
- NUDE_FRONT = "(completely nude, naked, bare breasts, nipples)1.4, nsfw, explicit, no clothes"
285
- # Weighted negatives so each frame pushes away the other frame's state
286
- CLOTHED_FRAME_NEG = "(nude, naked, topless, nipples, bare breasts)1.3"
287
- NUDE_FRAME_NEG = (
288
- "(clothes, clothing, shirt, dress, robe, bra, panties, lingerie, bikini, swimsuit, "
289
- "towel, corset, blazer, sweater, covered breasts, covered nipples)1.4"
290
- )
291
-
292
- BASE_NEGATIVES = (
293
- "child, loli, underage, teen, young teen, barely legal, "
294
- "18, eighteen, 19, nineteen, "
295
- "man, men, male, boy, guy, guys, male focus, masculine, "
296
- "old, elderly, aged, grandma, wrinkly, "
297
- "fat, chubby, obese, overweight, belly fat, thick thighs, thick body, "
298
- "beard, mustache, penis, dick, balls, "
299
- "bad hands, extra fingers, deformed, "
300
- "blurry, lowres, watermark, text, censored, ugly, celebrity, real person, "
301
- "caucasian, white woman, european, blonde hair, small breasts, flat chest"
302
- )
303
-
304
- FORBIDDEN_KEYWORDS = []
305
- if os.path.exists("restricted_words.txt"):
306
- try:
307
- with open("restricted_words.txt", "r", encoding="utf-8") as f:
308
- FORBIDDEN_KEYWORDS = [
309
- line.strip().lower() for line in f
310
- if line.strip() and not line.strip().startswith("#")
311
- ]
312
- except Exception as e:
313
- logger.error(f"restricted words load failed: {e}")
314
-
315
- # 21+: block ages under 21 in prompt text (includes 19 / nineteen)
316
- AGE_PATTERN = re.compile(
317
- r"\b(one|two|three|four|five|six|seven|eight|nine|ten|"
318
- r"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|"
319
- r"1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19)"
320
- r"\s*[-\s]?\s*(year|yr|y\/o|yo)\b"
321
- )
322
- MINOR_WORDS = re.compile(r"\b(child|kid|loli|teen|teenage|underage|minor|schoolgirl|young girl|little girl)\b")
323
-
324
-
325
- def check_prompt_safety(prompt: str):
326
- clean = str(prompt).lower().replace("-", " ").replace("_", " ")
327
- for word in FORBIDDEN_KEYWORDS:
328
- if word in clean:
329
- return False, word
330
- match = AGE_PATTERN.search(clean) or MINOR_WORDS.search(clean)
331
- if match:
332
- return False, match.group(0)
333
- return True, None
334
-
335
-
336
- # ---------------------------------------------------------------------------
337
- # Pure recipe logic (no GPU)
338
- # ---------------------------------------------------------------------------
339
- def random_woman(rng=random):
340
- return (
341
- f"adult {rng.choice(ETHNICITIES)} Asian woman late 20s, "
342
- f"{rng.choice(HAIRS)}, {rng.choice(FACES)}"
343
- )
344
-
345
-
346
- def styles_for_mode(art_mode):
347
- """Cartoon: anime styles only (no Photoreal). Photo: styles a photo chef can draw."""
348
- kind = ART_KIND.get(art_mode, "anime")
349
- return [name for name, spec in STYLES.items() if kind in spec["kinds"]]
350
-
351
-
352
- def chefs_for_mode(art_mode):
353
- kind = ART_KIND.get(art_mode, "anime")
354
- return [name for name, spec in CHEFS.items() if spec["kind"] == kind]
355
-
356
-
357
- def chef_pool_for_style(style_name, art_mode=DEFAULT_ART_MODE):
358
- kinds = STYLES.get(style_name, STYLES["Photoreal"])["kinds"]
359
- pool = [n for n in chefs_for_mode(art_mode) if CHEFS[n]["kind"] in kinds]
360
- return pool or chefs_for_mode(art_mode)
361
-
362
-
363
- def roll_recipe(prev=None, locks=None, new_woman=True, rng=random,
364
- art_mode=DEFAULT_ART_MODE, style_pick=STYLE_RANDOM):
365
- """Slot machine roll. Locked fields keep prev values; the rest spin.
366
-
367
- Art mode decides the style and chef pools. A locked style or chef that does
368
- not belong to the current art mode is re-rolled inside that mode.
369
- The Style dropdown (style_pick) forces one style when it is not "Roll random".
370
- """
371
- prev = dict(prev or {})
372
- locks = locks or {}
373
- if art_mode not in ART_MODES:
374
- art_mode = DEFAULT_ART_MODE
375
- style_pool = styles_for_mode(art_mode)
376
- chef_pool = chefs_for_mode(art_mode)
377
-
378
- def keep(field):
379
- return bool(locks.get(field)) and prev.get(field)
380
-
381
- recipe = {"art": art_mode}
382
- if style_pick in style_pool:
383
- recipe["style"] = style_pick
384
- elif keep("style") and prev["style"] in style_pool:
385
- recipe["style"] = prev["style"]
386
- else:
387
- recipe["style"] = rng.choice(style_pool)
388
- if keep("chef") and prev["chef"] in chef_pool:
389
- recipe["chef"] = prev["chef"]
390
- else:
391
- recipe["chef"] = rng.choice(chef_pool_for_style(recipe["style"], art_mode))
392
- recipe["scene"] = prev["scene"] if keep("scene") else rng.choice(SCENES)
393
- recipe["outfit"] = prev["outfit"] if keep("outfit") else rng.choice(CLOTHED_OUTFITS)
394
- recipe["nude_look"] = prev["nude_look"] if keep("nude_look") else rng.choice(NUDE_OUTFITS)
395
- recipe["pose"] = prev["pose"] if keep("pose") else rng.choice(POSES)
396
- recipe["light"] = prev["light"] if keep("light") else rng.choice(LIGHTS)
397
- recipe["camera"] = prev["camera"] if keep("camera") else rng.choice(CAMERAS)
398
- if keep("woman"):
399
- recipe["woman"] = prev["woman"]
400
- elif new_woman:
401
- recipe["woman"] = random_woman(rng)
402
- else:
403
- recipe["woman"] = prev.get("woman") or DEFAULT_FACE
404
- recipe["tease"] = rng.choice(TEASE_STATES)
405
- return recipe
406
-
407
-
408
- def _join(*parts):
409
- return ", ".join(p.strip(" ,") for p in parts if p and str(p).strip(" ,"))
410
-
411
-
412
- def _outfit_for_negative(outfit):
413
- """Clothed outfit words for the nude negative, minus words that are fine nude."""
414
- keep_ok = {"deep cleavage", "NUDE"}
415
- parts = [w.strip() for w in str(outfit or "").split(",")]
416
- return ", ".join(w for w in parts if w and w not in keep_ok)
417
-
418
-
419
- def build_frames(recipe, tease_reveal=False, extra=""):
420
- """Return list of (label, positive, negative).
421
-
422
- The words that make the two frames different go FIRST and are weighted
423
- with compel syntax, e.g. (completely nude, naked)1.4. The nude frame also
424
- carries the clothed frame's outfit in its negative, weighted, so the
425
- clothes are pushed away instead of copied.
426
- """
427
- style = STYLES.get(recipe.get("style"), STYLES["Photoreal"])
428
- negative = _join(BASE_NEGATIVES, style["neg"])
429
- woman = recipe.get("woman") or DEFAULT_FACE
430
- after = _join(woman, BODY_LOCK_SHORT, style["prefix"], recipe.get("pose"), recipe.get("camera"),
431
- recipe.get("scene"), recipe.get("light"), extra)
432
- outfit = recipe.get("outfit") or CLOTHED_OUTFITS[0]
433
- outfit_neg = _outfit_for_negative(outfit)
434
- nude_neg = _join(negative, NUDE_FRAME_NEG, f"({outfit_neg})1.3" if outfit_neg else "")
435
-
436
- if not tease_reveal:
437
- # Pair: frame 1 clothed, frame 2 nude
438
- clothed = _join(f"(wearing {outfit}, clothed)1.3", FRAME_HEAD, after)
439
- nude = _join(NUDE_FRONT, recipe.get("nude_look") or NUDE_OUTFITS[1], FRAME_HEAD, after)
440
- return [
441
- ("Clothed", clothed, _join(negative, CLOTHED_FRAME_NEG)),
442
- ("Nude", nude, nude_neg),
443
- ]
444
-
445
- frame1 = _join(f"({recipe.get('tease')}, partially covered, teasing)1.2", FRAME_HEAD,
446
- "full body shot", after)
447
- frame2 = _join(NUDE_FRONT, FRAME_HEAD, "full body shot", after)
448
- return [
449
- ("Tease", frame1, negative),
450
- ("Reveal", frame2, nude_neg),
451
- ]
452
-
453
-
454
- def recipe_card(recipe, seed=None):
455
- if not recipe:
456
- return "_No roll yet. Hit **Spin**._"
457
- lines = ["### Recipe"]
458
- for field in FIELDS:
459
- lines.append(f"- **{field.replace('_', ' ').title()}**: {recipe.get(field, '')}")
460
- if seed is not None:
461
- lines.append(f"- **Seed**: {seed}")
462
- return "\n".join(lines)
463
-
464
-
465
- def history_label(i, entry):
466
- r = entry["recipe"]
467
- return f"{i + 1}. {r['style']} | {r['scene']} | {r['outfit']} | seed {entry['seed']}"
468
-
469
-
470
- def push_history(history, recipe, seed):
471
- history = list(history or [])
472
- history.insert(0, {"recipe": dict(recipe), "seed": seed})
473
- return history[:HISTORY_SIZE]
474
-
475
-
476
- # ---------------------------------------------------------------------------
477
- # Visitor logging (off by default)
478
- # ---------------------------------------------------------------------------
479
- def should_log_upload(username) -> bool:
480
- return bool(LOG_VISITOR_UPLOADS)
481
-
482
-
483
- def async_log_upload(pil_img, seed, model_name, prompt, username, width, height, steps, cfg_scale):
484
- if not should_log_upload(username):
485
- logger.info("visitor log upload skipped (LOG_VISITOR_UPLOADS not enabled)")
486
- return
487
- hf_token = os.environ.get("HF_TOKEN")
488
- if not username or not str(username).strip():
489
- username = "Unknown_Visitor"
490
- timestamp = int(time.time())
491
- clean = str(model_name).replace("/", "_")[:18]
492
- filename_base = f"gen_{timestamp}_seed_{seed}_{clean}"
493
- buf = io.BytesIO()
494
- pil_img.save(buf, format="WEBP", quality=95)
495
- raw = buf.getvalue()
496
- if not hf_token:
497
- logger.error("HF_TOKEN missing - log upload skipped")
498
- return
499
- api = HfApi(token=hf_token)
500
- date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(timestamp))
501
- log_entry = f"[{date_str}] | User: {username} | Model: {model_name} | Seed: {seed} | Prompt: {prompt[:150]}...\n"
502
- user_log = f"user_logs/{username}_history.txt"
503
- for attempt in range(1, 4):
504
- try:
505
- try:
506
- path = hf_hub_download(BACKUP_DATASET_ID, "traffic_logs.txt", repo_type="dataset", token=hf_token)
507
- current = open(path, encoding="utf-8").read()
508
- except Exception:
509
- current = "=== TRAFFIC LOGS ===\n"
510
- try:
511
- upath = hf_hub_download(BACKUP_DATASET_ID, user_log, repo_type="dataset", token=hf_token)
512
- user_logs = open(upath, encoding="utf-8").read()
513
- except Exception:
514
- user_logs = f"=== HISTORY FOR {username} ===\n"
515
- ops = [
516
- CommitOperationAdd(path_in_repo="traffic_logs.txt", path_or_fileobj=(current + log_entry).encode()),
517
- CommitOperationAdd(path_in_repo=user_log, path_or_fileobj=(user_logs + log_entry).encode()),
518
- CommitOperationAdd(path_in_repo=f"data/{filename_base}.webp", path_or_fileobj=raw),
519
- ]
520
- api.create_commit(
521
- repo_id=BACKUP_DATASET_ID, repo_type="dataset", operations=ops,
522
- commit_message=f"gen for {username} @ {timestamp}",
523
- )
524
- logger.info(f"logged {username} attempt {attempt}")
525
- return
526
- except Exception as e:
527
- logger.error(f"log fail {attempt}: {e}")
528
- time.sleep(1.5 * attempt)
529
-
530
-
531
- # ---------------------------------------------------------------------------
532
- # Pipeline (one chef cached at a time)
533
- # ---------------------------------------------------------------------------
534
- _pipe = None
535
- _pipe_chef = None
536
- _img2img = None
537
- _base_sched_config = None
538
- _ip_loaded = False
539
-
540
-
541
- def _hf_token():
542
- return os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
543
-
544
-
545
- def unload_pipe():
546
- global _pipe, _pipe_chef, _img2img, _base_sched_config, _ip_loaded
547
- _pipe = None
548
- _pipe_chef = None
549
- _img2img = None
550
- _base_sched_config = None
551
- _ip_loaded = False
552
- gc.collect()
553
- if torch.cuda.is_available():
554
- torch.cuda.empty_cache()
555
-
556
 
557
- def get_pipe(chef_name):
558
- global _pipe, _pipe_chef, _base_sched_config
559
- if _pipe is not None and _pipe_chef == chef_name:
560
- return _pipe
561
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
562
-
563
- unload_pipe()
564
- spec = CHEFS[chef_name]
565
- dtype = torch.float16 if torch.cuda.is_available() else torch.float32
566
- logger.info(f"Loading chef {chef_name} ({spec['repo']})")
567
- pipe = StableDiffusionXLPipeline.from_pretrained(
568
- spec["repo"], torch_dtype=dtype, use_safetensors=True, token=_hf_token(),
569
- )
570
- # Keep the chef's own scheduler config so every sampler swap starts clean
571
- _base_sched_config = dict(pipe.scheduler.config)
572
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(_base_sched_config)
573
- if torch.cuda.is_available():
574
- pipe.to("cuda")
575
- pipe.vae.enable_slicing()
576
- pipe.vae.enable_tiling()
577
- _pipe, _pipe_chef = pipe, chef_name
578
- return pipe
579
-
580
-
581
- def get_img2img(pipe):
582
- """Img2img pipe that reuses the SAME unet, vae and text encoders (no extra VRAM)."""
583
- global _img2img
584
- if _img2img is not None:
585
- return _img2img
586
- from diffusers import StableDiffusionXLImg2ImgPipeline
587
- try:
588
- _img2img = StableDiffusionXLImg2ImgPipeline.from_pipe(pipe)
589
- except Exception as e:
590
- logger.warning(f"from_pipe failed ({e}), sharing components by hand")
591
- _img2img = StableDiffusionXLImg2ImgPipeline(**pipe.components)
592
- return _img2img
593
-
594
-
595
- def make_scheduler(sampler_name):
596
- """Fresh scheduler for this spin, built from the chef's original config."""
597
- from diffusers import (
598
- EulerAncestralDiscreteScheduler,
599
- DPMSolverMultistepScheduler,
600
- UniPCMultistepScheduler,
601
- )
602
- config = _base_sched_config or dict(_pipe.scheduler.config)
603
- if sampler_name == "DPM++ 2M Karras":
604
- return DPMSolverMultistepScheduler.from_config(
605
- config, algorithm_type="dpmsolver++", solver_order=2, use_karras_sigmas=True)
606
- if sampler_name == "DPM++ SDE Karras":
607
- # sde-dpmsolver++ gives the SDE flavour without needing torchsde
608
- return DPMSolverMultistepScheduler.from_config(
609
- config, algorithm_type="sde-dpmsolver++", solver_order=2, use_karras_sigmas=True)
610
- if sampler_name == "UniPC":
611
- return UniPCMultistepScheduler.from_config(config)
612
- return EulerAncestralDiscreteScheduler.from_config(config)
613
-
614
-
615
- def resolve_lora(lora_choice, custom_repo, custom_file):
616
- """Return (repo, weight_file) or None."""
617
- if not lora_choice or lora_choice == LORA_NONE:
618
- return None
619
- if lora_choice == LORA_CUSTOM:
620
- repo = (custom_repo or "").strip()
621
- if not repo:
622
- return None
623
- if not REPO_ID_PATTERN.match(repo):
624
- logger.warning(f"custom LoRA repo id looks wrong, skipping: {repo!r}")
625
- return None
626
- return repo, ((custom_file or "").strip() or None)
627
- spec = LORAS.get(lora_choice)
628
- return (spec["repo"], spec["file"]) if spec else None
629
-
630
-
631
- def clear_lora(pipe):
632
- """Drop any LoRA left from an earlier spin so they never stack."""
633
- try:
634
- pipe.unfuse_lora()
635
- except Exception:
636
- pass
637
- try:
638
- pipe.unload_lora_weights()
639
- except Exception as e:
640
- logger.warning(f"LoRA unload warning: {e}")
641
-
642
-
643
- def apply_lora(pipe, lora, strength):
644
- """Load one LoRA by adapter name. A bad LoRA logs a warning and the spin goes on."""
645
- clear_lora(pipe)
646
- if not lora or float(strength) <= 0:
647
- return None
648
- repo, weight_file = lora
649
- try:
650
- kwargs = {"adapter_name": LORA_ADAPTER, "token": _hf_token()}
651
- if weight_file:
652
- kwargs["weight_name"] = weight_file
653
- pipe.load_lora_weights(repo, **kwargs)
654
- pipe.set_adapters([LORA_ADAPTER], adapter_weights=[float(strength)])
655
- logger.info(f"LoRA on: {repo} ({weight_file}) at {strength}")
656
- return f"{repo} @ {float(strength):.2f}"
657
- except Exception as e:
658
- logger.warning(f"LoRA {repo} failed, rendering without it: {e}")
659
- clear_lora(pipe)
660
- return None
661
-
662
-
663
- def prefetch_ip_adapter():
664
- """Download the IP-Adapter files on the CPU side, before the GPU clock starts.
665
-
666
- Returns None when ready, or an error string.
667
- """
668
- try:
669
- for f in IP_FILES:
670
- hf_hub_download(IP_REPO, f, token=_hf_token())
671
- return None
672
- except Exception as e:
673
- logger.warning(f"IP-Adapter download failed: {e}")
674
- return str(e)
675
-
676
-
677
- def ensure_ip_adapter(pipe, want):
678
- """Load IP-Adapter once per cached chef, or unload it when not wanted.
679
-
680
- Returns (ok, error_text). The img2img twin is rebuilt after any change so it
681
- picks up the new image encoder and attention processors.
682
- """
683
- global _ip_loaded, _img2img
684
- if want and not _ip_loaded:
685
- try:
686
- pipe.load_ip_adapter(
687
- IP_REPO, subfolder=IP_SUBFOLDER, weight_name=IP_WEIGHT,
688
- image_encoder_folder=IP_ENCODER_FOLDER, token=_hf_token(),
689
- )
690
- _ip_loaded = True
691
- _img2img = None
692
- logger.info("IP-Adapter loaded")
693
- except Exception as e:
694
- logger.warning(f"IP-Adapter load failed, rendering without it: {e}")
695
- try:
696
- pipe.unload_ip_adapter()
697
- except Exception:
698
- pass
699
- _ip_loaded = False
700
- _img2img = None
701
- return False, str(e)
702
- elif not want and _ip_loaded:
703
- try:
704
- pipe.unload_ip_adapter()
705
- except Exception as e:
706
- logger.warning(f"IP-Adapter unload warning: {e}")
707
- _ip_loaded = False
708
- _img2img = None
709
- return (_ip_loaded if want else True), None
710
-
711
-
712
- def fit_picture(img, width, height):
713
- """Resize and center crop the upload to the chosen size preset."""
714
- from PIL import Image, ImageOps
715
- if img is None:
716
- return None
717
- if not isinstance(img, Image.Image):
718
- img = Image.fromarray(img)
719
- return ImageOps.fit(img.convert("RGB"), (int(width), int(height)), Image.LANCZOS)
720
-
721
-
722
- def _gpu_duration(*args, **kwargs):
723
- # Copy the look may load IP-Adapter onto the GPU, so it gets a little more room
724
- return 120 if kwargs.get("picture_mode") == PIC_LOOK else 90
725
-
726
-
727
- def _gpu(fn):
728
- # 90 s reservation (120 s with Copy the look): ZeroGPU checks this against your remaining daily time
729
- if not SPACES_AVAILABLE:
730
- return fn
731
- try:
732
- return spaces.GPU(duration=_gpu_duration)(fn)
733
- except Exception as e:
734
- logger.warning(f"dynamic GPU duration not supported ({e}), using 120 s")
735
- return spaces.GPU(duration=120)(fn)
736
-
737
-
738
- WEIGHT_SYNTAX = re.compile(r"\(([^()]*)\)[0-9.]+")
739
-
740
-
741
- def strip_weights(text):
742
- """(words)1.4 becomes words, for the plain fallback without compel."""
743
- return WEIGHT_SYNTAX.sub(r"\1", str(text))
744
-
745
-
746
- def _long_prompt_kwargs(pipe, positive, negative):
747
- """Encode the WHOLE prompt with compel, weights included.
748
-
749
- Plain diffusers cuts every prompt at 77 tokens and ignores (words)1.4.
750
- Compel reads past 77 tokens and applies the weights. A NEW encoder runs for
751
- every frame, so frame 2 never reuses frame 1's embeddings.
752
- """
753
- import compel as compel_pkg
754
- if hasattr(compel_pkg, "CompelForSDXL"):
755
- enc = compel_pkg.CompelForSDXL(pipe)
756
- out = enc(positive, negative_prompt=negative)
757
- return {
758
- "prompt_embeds": out.embeds,
759
- "pooled_prompt_embeds": out.pooled_embeds,
760
- "negative_prompt_embeds": out.negative_embeds,
761
- "negative_pooled_prompt_embeds": out.negative_pooled_embeds,
762
- }
763
- from compel import Compel, ReturnedEmbeddingsType
764
- enc = Compel(
765
- tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
766
- text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
767
- returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
768
- requires_pooled=[False, True],
769
- truncate_long_prompts=False,
770
- )
771
- pos_embeds, pos_pooled = enc(positive)
772
- neg_embeds, neg_pooled = enc(negative)
773
- pos_embeds, neg_embeds = enc.pad_conditioning_tensors_to_same_length([pos_embeds, neg_embeds])
774
- return {
775
- "prompt_embeds": pos_embeds,
776
- "pooled_prompt_embeds": pos_pooled,
777
- "negative_prompt_embeds": neg_embeds,
778
- "negative_pooled_prompt_embeds": neg_pooled,
779
- }
780
-
781
-
782
- def _prompt_kwargs(pipe, positive, negative):
783
- try:
784
- return _long_prompt_kwargs(pipe, positive, negative), "compel"
785
- except Exception as e:
786
- logger.warning(f"compel encode failed, using plain prompt cut at 77 tokens: {e}")
787
- return {"prompt": strip_weights(positive), "negative_prompt": strip_weights(negative)}, "plain"
788
-
789
-
790
- @_gpu
791
- def render_frames(chef_name, frames, seeds, steps, guidance_scale, width, height,
792
- nude_mode=DEFAULT_NUDE_MODE, reveal_strength=DEFAULT_REVEAL_STRENGTH,
793
- lora=None, lora_strength=DEFAULT_LORA_STRENGTH, sampler=DEFAULT_SAMPLER,
794
- ref_image=None, picture_mode=DEFAULT_PIC_MODE,
795
- look_strength=DEFAULT_LOOK_STRENGTH, redraw_strength=DEFAULT_REDRAW_STRENGTH):
796
- """frames: list of (label, positive, negative); seeds: one seed per frame.
797
-
798
- No picture: frame 1 is txt2img; later frames are txt2img (fresh modes) or
799
- img2img on frame 1 (reveal mode).
800
- Copy the look: same as above, with IP-Adapter steering every frame.
801
- Redraw my pic: frame 1 is img2img from the upload; the nude frame is img2img
802
- from the upload too (strength + 0.1), unless reveal mode is on.
803
- ref_image arrives already fitted to width x height.
804
- """
805
- pipe = get_pipe(chef_name)
806
- device = "cuda" if torch.cuda.is_available() else "cpu"
807
- use_look = picture_mode == PIC_LOOK and ref_image is not None
808
- use_redraw = picture_mode == PIC_REDRAW and ref_image is not None
809
- ip_ok, ip_error = ensure_ip_adapter(pipe, use_look)
810
- ip_kwargs = {}
811
- if use_look and ip_ok:
812
- try:
813
- pipe.set_ip_adapter_scale(float(look_strength))
814
- ip_kwargs = {"ip_adapter_image": ref_image}
815
- except Exception as e:
816
- logger.warning(f"IP-Adapter scale failed, rendering without it: {e}")
817
- ip_error = str(e)
818
- ensure_ip_adapter(pipe, False)
819
- ip_ok = False
820
- if use_look:
821
- ip_note = (f"on at {float(look_strength):.2f}" if ip_kwargs
822
- else f"failed, rendered without it ({str(ip_error)[:160]})")
823
- else:
824
- ip_note = None
825
- lora_note = apply_lora(pipe, lora, lora_strength)
826
- images = []
827
- encoders = []
828
- try:
829
- first_image = None
830
- for i, (label, positive, negative) in enumerate(frames):
831
- gen = torch.Generator(device=device).manual_seed(int(seeds[i]))
832
- prompt_kwargs, enc_name = _prompt_kwargs(pipe, positive, negative)
833
- encoders.append(enc_name)
834
- source, strength = None, None
835
- if nude_mode == NUDE_MODE_REVEAL and i > 0 and first_image is not None:
836
- source, strength = first_image, float(reveal_strength)
837
- elif use_redraw:
838
- bump = 0.0 if i == 0 else 0.1
839
- source, strength = ref_image, min(REDRAW_MAX, float(redraw_strength) + bump)
840
- if source is not None:
841
- i2i = get_img2img(pipe)
842
- i2i.scheduler = make_scheduler(sampler)
843
- out = i2i(
844
- **prompt_kwargs,
845
- **ip_kwargs,
846
- image=source.copy(),
847
- strength=strength,
848
- num_inference_steps=int(steps),
849
- guidance_scale=float(guidance_scale),
850
- generator=gen,
851
- ).images[0]
852
- else:
853
- # fresh scheduler every frame so no state carries over
854
- try:
855
- pipe.scheduler = make_scheduler(sampler)
856
- except Exception as e:
857
- logger.warning(f"sampler {sampler} failed, keeping current: {e}")
858
- out = pipe(
859
- **prompt_kwargs,
860
- **ip_kwargs,
861
- num_inference_steps=int(steps),
862
- guidance_scale=float(guidance_scale),
863
- width=int(width),
864
- height=int(height),
865
- generator=gen,
866
- ).images[0]
867
- if i == 0:
868
- first_image = out
869
- images.append((label, out))
870
- finally:
871
- if lora_note:
872
- clear_lora(pipe)
873
- return images, lora_note, encoders, ip_note
874
-
875
-
876
- # ---------------------------------------------------------------------------
877
- # UI handlers
878
- # ---------------------------------------------------------------------------
879
- def _locks_from_flags(flags):
880
- return {field: bool(flag) for field, flag in zip(FIELDS, flags)}
881
-
882
-
883
- def _resolve_seed(seed_value):
884
- try:
885
- s = int(float(seed_value))
886
- except (TypeError, ValueError):
887
- s = -1
888
- return random.randint(0, 2**31 - 1) if s < 0 else s
889
-
890
-
891
- def _cook(recipe, seed, tease_reveal, extra, size_name, steps, guidance_scale,
892
- nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
893
- ref_image, picture_mode, look_strength, redraw_strength,
894
- username, gallery_items, history):
895
- """Shared render path for Spin and Re-roll. Returns UI outputs."""
896
- user_key = username or "anonymous"
897
- now = time.time()
898
- last = LAST_GEN_TIME.get(user_key)
899
- if last and now - last < COOLDOWN_SECONDS:
900
- left = int(COOLDOWN_SECONDS - (now - last))
901
- raise gr.Error(f"Cooldown {left}s")
902
-
903
- frames = build_frames(recipe, tease_reveal=bool(tease_reveal), extra=extra or "")
904
- for _, positive, _ in frames:
905
- ok, bad = check_prompt_safety(positive)
906
- if not ok:
907
- raise gr.Error("Restricted content in prompt")
908
-
909
- width, height = SIZE_PRESETS.get(size_name, SIZE_PRESETS["Portrait 832x1216"])
910
- use_steps = int(max(10, min(40, int(steps or DEFAULT_STEPS))))
911
- use_guidance = float(guidance_scale if guidance_scale is not None else DEFAULT_GUIDANCE)
912
- use_mode = nude_mode if nude_mode in NUDE_MODES else DEFAULT_NUDE_MODE
913
- use_reveal_strength = float(max(REVEAL_MIN, min(REVEAL_MAX, float(reveal_strength or DEFAULT_REVEAL_STRENGTH))))
914
- use_lora_strength = float(max(0.0, min(1.5, float(lora_strength if lora_strength is not None else DEFAULT_LORA_STRENGTH))))
915
- use_sampler = sampler if sampler in SAMPLERS else DEFAULT_SAMPLER
916
- lora = resolve_lora(lora_choice, lora_repo, lora_file)
917
- seed = int(seed)
918
- if use_mode == NUDE_MODE_NEW:
919
- seeds = [seed] + [random.randint(0, 2**31 - 1) for _ in frames[1:]]
920
- else:
921
- seeds = [seed] * len(frames)
922
- use_pic_mode = picture_mode if picture_mode in PIC_MODES else DEFAULT_PIC_MODE
923
- pic_note = None
924
- if use_pic_mode != PIC_OFF and ref_image is None:
925
- pic_note = f"Picture mode {use_pic_mode} picked but no picture uploaded, so it ran Off"
926
- use_pic_mode = PIC_OFF
927
- use_look_strength = float(max(LOOK_MIN, min(LOOK_MAX, float(look_strength or DEFAULT_LOOK_STRENGTH))))
928
- use_redraw_strength = float(max(REDRAW_MIN, min(REDRAW_MAX, float(redraw_strength or DEFAULT_REDRAW_STRENGTH))))
929
- fitted = None
930
- if use_pic_mode != PIC_OFF:
931
- try:
932
- fitted = fit_picture(ref_image, width, height)
933
- except Exception as e:
934
- logger.warning(f"could not read the uploaded picture: {e}")
935
- pic_note = f"Could not read the uploaded picture, so it ran Off ({e})"
936
- use_pic_mode = PIC_OFF
937
- if use_pic_mode == PIC_LOOK:
938
- # download before the GPU clock starts
939
- err = prefetch_ip_adapter()
940
- if err:
941
- pic_note = f"Copy the look: IP-Adapter download failed, rendered without it ({err[:160]})"
942
- use_pic_mode, fitted = PIC_OFF, None
943
- LAST_GEN_TIME[user_key] = now
944
-
945
- try:
946
- results, lora_note, encoders, ip_note = render_frames(
947
- recipe["chef"], frames, seeds, use_steps, use_guidance, width, height,
948
- nude_mode=use_mode, reveal_strength=use_reveal_strength,
949
- lora=lora, lora_strength=use_lora_strength, sampler=use_sampler,
950
- ref_image=fitted, picture_mode=use_pic_mode,
951
- look_strength=use_look_strength, redraw_strength=use_redraw_strength,
952
- )
953
- except Exception as e:
954
- logger.exception("render failed")
955
- msg = str(e)
956
- if "gated" in msg.lower() or "401" in msg or "403" in msg:
957
- msg += " (accept the model license and make sure the HF_TOKEN secret can read it)"
958
- raise gr.Error(msg)
959
-
960
- new_items = []
961
- for (label, img), (_, positive, _), frame_seed in zip(results, frames, seeds):
962
- new_items.append((img, f"{label} | {recipe['chef']} | seed {frame_seed}"))
963
- threading.Thread(
964
- target=async_log_upload,
965
- args=(img, frame_seed, recipe["chef"], positive, username, width, height, use_steps, use_guidance),
966
- daemon=True,
967
- ).start()
968
-
969
- gallery_items = (new_items + list(gallery_items or []))[:GALLERY_SIZE]
970
- history = push_history(history, recipe, seed)
971
- prompt_text = "\n\n".join(f"[{label}]\n{pos}\n[{label} negative]\n{neg}" for label, pos, neg in frames)
972
- notes = [
973
- f"Art mode: {recipe.get('art', DEFAULT_ART_MODE)}",
974
- f"Sampler: {use_sampler}",
975
- f"Nude frame mode: {use_mode}",
976
- f"Seeds: {', '.join(str(x) for x in seeds)}",
977
- f"Prompt encoder per frame: {', '.join(encoders)} (compel = weights on, plain = weights off, cut at 77 tokens)",
978
- ]
979
- if use_mode == NUDE_MODE_REVEAL:
980
- notes.append(f"Reveal strength {use_reveal_strength:.2f}")
981
- notes.append(f"Picture mode: {use_pic_mode}")
982
- if use_pic_mode == PIC_LOOK:
983
- notes.append(f"Copy the look (IP-Adapter {IP_WEIGHT}): {ip_note}")
984
- if use_pic_mode == PIC_REDRAW:
985
- if use_mode == NUDE_MODE_REVEAL:
986
- notes.append(f"Redraw strength {use_redraw_strength:.2f} on the clothed picture, nude picture revealed from it")
987
- else:
988
- notes.append(f"Redraw strength {use_redraw_strength:.2f} clothed, "
989
- f"{min(REDRAW_MAX, use_redraw_strength + 0.1):.2f} nude, both from your picture")
990
- if pic_note:
991
- notes.append(pic_note)
992
- if lora:
993
- notes.append(f"LoRA: {lora_note}" if lora_note else f"LoRA {lora[0]} failed to load, rendered without it")
994
- prompt_text = prompt_text + "\n\n[Settings]\n" + "\n".join(notes)
995
- choices = [history_label(i, h) for i, h in enumerate(history)]
996
- return (
997
- gallery_items,
998
- gallery_items,
999
- recipe_card(recipe, seed),
1000
- prompt_text,
1001
- recipe,
1002
- history,
1003
- gr.update(choices=choices, value=choices[0] if choices else None),
1004
- )
1005
-
1006
-
1007
- def on_spin(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps, guidance_scale,
1008
- seed_value, nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1009
- ref_image, picture_mode, look_strength, redraw_strength,
1010
- username, gallery_items, history, *lock_flags):
1011
- rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),
1012
- art_mode=art_mode, style_pick=style_pick)
1013
- return _cook(rolled, _resolve_seed(seed_value), tease_reveal, extra, size_name, steps,
1014
- guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,
1015
- lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,
1016
- redraw_strength, username, gallery_items, history)
1017
-
1018
-
1019
- def on_reroll_history(choice, tease_reveal, extra, size_name, steps, guidance_scale,
1020
- nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1021
- ref_image, picture_mode, look_strength, redraw_strength,
1022
- username, gallery_items, history):
1023
- """Re-roll uses whatever picture is in the upload box right now."""
1024
- history = list(history or [])
1025
- labels = [history_label(i, h) for i, h in enumerate(history)]
1026
- if not choice or choice not in labels:
1027
- raise gr.Error("Pick a recipe from history first")
1028
- picked = history[labels.index(choice)]["recipe"]
1029
- return _cook(dict(picked), _resolve_seed(-1), tease_reveal, extra, size_name, steps,
1030
- guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,
1031
- lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,
1032
- redraw_strength, username, gallery_items, history)
1033
-
1034
-
1035
- def on_load_history(choice, history):
1036
- history = list(history or [])
1037
- labels = [history_label(i, h) for i, h in enumerate(history)]
1038
- if not choice or choice not in labels:
1039
- return gr.update(), gr.update()
1040
- entry = history[labels.index(choice)]
1041
- return dict(entry["recipe"]), recipe_card(entry["recipe"], entry["seed"])
1042
-
1043
-
1044
- def on_preview(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, *lock_flags):
1045
- """Spin the card without rendering (free, no GPU)."""
1046
- rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),
1047
- art_mode=art_mode, style_pick=style_pick)
1048
- frames = build_frames(rolled, tease_reveal=bool(tease_reveal), extra=extra or "")
1049
- return rolled, recipe_card(rolled), "\n\n".join(f"[{l}]\n{p}" for l, p, _ in frames)
1050
-
1051
-
1052
- def on_picture_upload(picture_mode):
1053
- """A fresh upload switches Off to Copy the look; any other pick is kept."""
1054
- return gr.update(value=PIC_LOOK if picture_mode in (None, PIC_OFF) else picture_mode)
1055
-
1056
-
1057
- def on_picture_clear():
1058
- return gr.update(value=PIC_OFF)
1059
-
1060
-
1061
- def on_art_mode(art_mode, style_pick):
1062
- """Refill the Style dropdown with the styles that suit the art mode."""
1063
- pool = styles_for_mode(art_mode)
1064
- value = style_pick if style_pick in pool else STYLE_RANDOM
1065
- return gr.update(choices=[STYLE_RANDOM] + pool, value=value)
1066
-
1067
-
1068
- js_visitor = """
1069
- function() {
1070
- let id = localStorage.getItem('adult_ai_visitor_id');
1071
- if (!id) {
1072
- id = 'Visitor_' + Math.floor(1000 + Math.random() * 9000);
1073
- localStorage.setItem('adult_ai_visitor_id', id);
1074
- }
1075
- return id;
1076
- }
1077
- """
1078
-
1079
-
1080
- def create_ui():
1081
- with gr.Blocks(title="Roulette Lab") as demo:
1082
- gr.Markdown(
1083
- "# Roulette Lab\n"
1084
- "Spin a random recipe. Every spin makes two pictures: one clothed, one nude. Cartoon art is the default; switch Art mode to Photo for real looking pictures. Lock what you like, spin again, and only the unlocked slots change. "
1085
- "Fictional adult women 21+ only. Visitor images are not saved unless the Space secret "
1086
- "`LOG_VISITOR_UPLOADS=1` is set."
1087
- )
1088
- recipe_state = gr.State({})
1089
- history_state = gr.State([])
1090
- gallery_state = gr.State([])
1091
- user_id = gr.Textbox(visible=False)
1092
-
1093
- with gr.Row():
1094
- with gr.Column(scale=1):
1095
- spin_btn = gr.Button("Spin", variant="primary", size="lg")
1096
- art_mode = gr.Radio(ART_MODES, value=DEFAULT_ART_MODE, label="Art mode")
1097
- style_pick = gr.Dropdown([STYLE_RANDOM] + styles_for_mode(DEFAULT_ART_MODE), value=STYLE_RANDOM,
1098
- label="Style (Roll random, or pick one to keep every spin)")
1099
- preview_btn = gr.Button("Spin card only (no render)")
1100
- card = gr.Markdown(recipe_card({}))
1101
- gr.Markdown("**Lock slots** (locked slots survive the next spin)")
1102
- lock_boxes = [gr.Checkbox(label=f"Lock {f.replace('_', ' ')}", value=False) for f in FIELDS]
1103
- new_woman = gr.Checkbox(label="New woman each roll", value=True)
1104
- tease_reveal = gr.Checkbox(label="Tease then reveal instead of clothed and nude (same seed, 2 frames)", value=False)
1105
- nude_mode = gr.Radio(NUDE_MODES, value=DEFAULT_NUDE_MODE, label="Nude frame mode")
1106
- reveal_strength = gr.Slider(REVEAL_MIN, REVEAL_MAX, value=DEFAULT_REVEAL_STRENGTH, step=0.05,
1107
- label="Reveal strength (reveal mode only; low keeps more of the clothed picture)")
1108
- extra = gr.Textbox(label="Extra tags (optional)", placeholder="e.g. glossy lips, rain on skin")
1109
- with gr.Accordion("Your picture (optional)", open=False):
1110
- ref_image = gr.Image(type="pil", label="Reference picture", sources=["upload", "clipboard"])
1111
- gr.Markdown("Use for pose, outfit, style and mood. Faces come from the random deck, not your pic.")
1112
- picture_mode = gr.Radio(PIC_MODES, value=DEFAULT_PIC_MODE, label="Picture mode")
1113
- look_strength = gr.Slider(LOOK_MIN, LOOK_MAX, value=DEFAULT_LOOK_STRENGTH, step=0.05,
1114
- label="Look strength (Copy the look; high copies more of your pic)")
1115
- redraw_strength = gr.Slider(REDRAW_MIN, REDRAW_MAX, value=DEFAULT_REDRAW_STRENGTH, step=0.05,
1116
- label="Redraw strength (Redraw my pic; low stays close to your pic)")
1117
- with gr.Accordion("LoRA and sampler", open=False):
1118
- lora_choice = gr.Dropdown(LORA_CHOICES, value=LORA_NONE, label="LoRA")
1119
- lora_strength = gr.Slider(0.0, 1.5, value=DEFAULT_LORA_STRENGTH, step=0.05, label="LoRA strength")
1120
- lora_repo = gr.Textbox(label="Custom LoRA repo id (pick Custom above)", placeholder="user/repo")
1121
- lora_file = gr.Textbox(label="Custom LoRA weight file name", placeholder="name.safetensors")
1122
- sampler = gr.Dropdown(SAMPLERS, value=DEFAULT_SAMPLER, label="Sampler")
1123
- with gr.Accordion("Settings", open=False):
1124
- size_name = gr.Radio(list(SIZE_PRESETS), value="Portrait 832x1216", label="Size")
1125
- steps = gr.Slider(10, 40, value=DEFAULT_STEPS, step=1, label="Steps")
1126
- guidance_scale = gr.Slider(1.0, 12.0, value=DEFAULT_GUIDANCE, step=0.5, label="CFG")
1127
- seed_value = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")
1128
- with gr.Column(scale=2):
1129
- gallery = gr.Gallery(label="Output", columns=2, height=720)
1130
- prompt_box = gr.Textbox(label="Prompt sent", lines=8, interactive=False)
1131
- gr.Markdown("**History** (last 10 recipes)")
1132
- history_dd = gr.Dropdown(choices=[], label="Pick a recipe", interactive=True)
1133
- with gr.Row():
1134
- reroll_btn = gr.Button("Re-roll this recipe, new seed")
1135
- load_btn = gr.Button("Load into card (then lock and spin)")
1136
-
1137
- advanced = [nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1138
- ref_image, picture_mode, look_strength, redraw_strength]
1139
- outputs = [gallery, gallery_state, card, prompt_box, recipe_state, history_state, history_dd]
1140
-
1141
- spin_btn.click(
1142
- on_spin,
1143
- inputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps,
1144
- guidance_scale, seed_value] + advanced + [user_id, gallery_state, history_state] + lock_boxes,
1145
- outputs=outputs,
1146
- )
1147
- reroll_btn.click(
1148
- on_reroll_history,
1149
- inputs=[history_dd, tease_reveal, extra, size_name, steps, guidance_scale]
1150
- + advanced + [user_id, gallery_state, history_state],
1151
- outputs=outputs,
1152
- )
1153
- load_btn.click(on_load_history, inputs=[history_dd, history_state], outputs=[recipe_state, card])
1154
- preview_btn.click(
1155
- on_preview,
1156
- inputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra] + lock_boxes,
1157
- outputs=[recipe_state, card, prompt_box],
1158
- )
1159
- ref_image.upload(on_picture_upload, inputs=[picture_mode], outputs=[picture_mode])
1160
- ref_image.clear(on_picture_clear, inputs=None, outputs=[picture_mode])
1161
- art_mode.change(on_art_mode, inputs=[art_mode, style_pick], outputs=[style_pick])
1162
- demo.load(fn=None, inputs=None, outputs=[user_id], js=js_visitor)
1163
- return demo
1164
-
1165
-
1166
- if __name__ == "__main__":
1167
- os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
1168
- app = create_ui()
1169
- app.queue(max_size=12)
1170
- app.launch(ssr_mode=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ # Your original app, renamed to image_app.py, stays as is.
5
+ try:
6
+ from image_app import demo as image_demo
7
+ except Exception as e:
8
+ image_demo = None
9
+ image_err = str(e)
10
+
11
+ ideas = pd.read_csv("lacuna_ideas.csv")
12
+
13
+ def filter_ideas(text, kind):
14
+ df = ideas
15
+ if kind != "all":
16
+ df = df[df["kind"] == kind]
17
+ if text:
18
+ t = text.lower()
19
+ df = df[df.apply(lambda r: t in " ".join(map(str, r.values)).lower(), axis=1)]
20
+ return df
21
+
22
+ with gr.Blocks() as lacuna_demo:
23
+ gr.Markdown("## Lacuna ideas\nCoherent but unlikely combos from the idea map. Ideas are model guesses; backing papers are real items from the map.")
24
+ with gr.Row():
25
+ q = gr.Textbox(label="Search")
26
+ k = gr.Dropdown(["all", "pair", "triple"], value="all", label="Kind")
27
+ table = gr.Dataframe(ideas, wrap=True, interactive=False)
28
+ q.change(filter_ideas, [q, k], table)
29
+ k.change(filter_ideas, [q, k], table)
30
+
31
+ if image_demo is not None:
32
+ demo = gr.TabbedInterface([image_demo, lacuna_demo], ["Image", "Lacuna ideas"])
33
+ else:
34
+ demo = lacuna_demo
35
+
36
+ demo.launch()