Spaces:
JustinD
/
1
Running on Zero

JustinD commited on
Commit
62d09a9
·
verified ·
1 Parent(s): fe0dd00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1227 -34
app.py CHANGED
@@ -1,36 +1,1229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "1").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", "photo"],
145
+ "prefix": "oil painting, thick impasto brushstrokes, visible canvas texture, rich chiaroscuro, classical figure painting",
146
+ "neg": "photo, flat vector, cel shading",
147
+ },
148
+ }
149
+
150
+ SCENES = [
151
+ "coffee bar counter with espresso machine",
152
+ "office desk with laptop and city view",
153
+ "kitchen counter with morning sunlight",
154
+ "hotel room window with night city skyline",
155
+ "rooftop pool at dusk",
156
+ "library leather couch with dark wood shelves",
157
+ "neon lit rainy alley",
158
+ "steamy outdoor onsen with stone and pine",
159
+ "artist studio with canvases and paint jars",
160
+ "recording studio with mixing desk",
161
+ "velvet daybed in a dim lounge",
162
+ "bedroom with white sheets and linen curtains",
163
+ ]
164
+
165
+ # Every spin makes a pair with the same seed: one clothed, one nude
166
+ CLOTHED_OUTFITS = [
167
+ "black lace lingerie set",
168
+ "unbuttoned oversized white shirt, deep cleavage",
169
+ "silk robe, deep cleavage",
170
+ "black latex corset and sheer stockings",
171
+ "sheer slip dress",
172
+ "white towel wrapped around her",
173
+ "cropped knit sweater and panties",
174
+ "string bikini",
175
+ "black blazer, deep cleavage",
176
+ "tight low cut red dress",
177
+ ]
178
+ NUDE_OUTFITS = [
179
+ "fully nude, bare breasts, nipples",
180
+ "fully nude, gold body chain, bare breasts",
181
+ "topless, bare breasts, denim shorts",
182
+ "completely naked, bare breasts, nipples, nothing covering her",
183
+ "nude except black thigh high stockings, bare breasts",
184
+ "fully nude, wet skin, bare breasts",
185
+ ]
186
+ OUTFITS = CLOTHED_OUTFITS
187
+
188
+ POSES = [
189
+ "caught mid task, glancing at the camera",
190
+ "leaning forward on the counter",
191
+ "kneeling on the bed",
192
+ "sitting on the edge of a desk, legs crossed",
193
+ "stretching arms overhead",
194
+ "lying on her stomach, looking back over her shoulder",
195
+ "standing contrapposto, hand on hip",
196
+ "reclining, propped on one elbow",
197
+ ]
198
+
199
+ LIGHTS = [
200
+ "golden hour window light",
201
+ "pink and blue neon glow",
202
+ "soft overcast window light",
203
+ "warm candlelight",
204
+ "studio softbox with rim light",
205
+ "moonlight through blinds",
206
+ "direct on-camera flash",
207
+ "warm lamp light on her collarbone",
208
+ ]
209
+
210
+ CAMERAS = [
211
+ "full body wide shot",
212
+ "three quarter shot",
213
+ "low angle full body",
214
+ "eye level 50mm",
215
+ "high angle looking down",
216
+ "mirror reflection shot",
217
+ "cowboy shot",
218
+ ]
219
+
220
+ # Face randomizer (body lock never changes)
221
+ ETHNICITIES = ["Japanese", "Korean", "Chinese", "Taiwanese", "Vietnamese", "Thai", "Filipino", "Indonesian", "Malaysian"]
222
+ HAIRS = [
223
+ "long straight black hair", "messy bun", "chin length bob", "high ponytail",
224
+ "long wavy dark brown hair", "twin braids", "wet slicked back hair", "curtain bangs, shoulder length hair",
225
+ ]
226
+ FACES = [
227
+ "soft almond eyes, full lips", "sharp cheekbones, confident smirk", "round face, playful smile",
228
+ "monolid eyes, glossy lips", "heavy lashes, sultry stare", "freckles, bright eyes",
229
+ "beauty mark under one eye", "strong brows, calm gaze",
230
+ ]
231
+ DEFAULT_FACE = "adult Japanese Asian woman late 20s, long straight black hair, soft almond eyes, full lips"
232
+
233
+ # Tease then reveal: frame 1 states
234
+ TEASE_STATES = [
235
+ "shirt pulled halfway up, underboob showing",
236
+ "bra strap slipping off one shoulder",
237
+ "silk robe falling open",
238
+ "towel slipping down",
239
+ ]
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # LoRA slot (every repo id and file name checked on the HF Hub API, Oct 24 2026)
243
+ # ---------------------------------------------------------------------------
244
+ LORA_NONE = "None"
245
+ LORA_CUSTOM = "Custom (repo id + file below)"
246
+ LORAS = {
247
+ "Breast size slider (anime chefs, Illustrious)": {
248
+ "repo": "Muapi/breast-size-slider-lora-illustriousxl",
249
+ "file": "breast-size-slider-lora-illustriousxl.safetensors",
250
+ },
251
+ "Oppai large breasts slim body (anime chefs, Pony/Illustrious)": {
252
+ "repo": "Muapi/oppai-large-breasts-slim-body",
253
+ "file": "oppai-large-breasts-slim-body.safetensors",
254
+ },
255
+ "Skinny to voluptuous slider (photo chefs, SDXL)": {
256
+ "repo": "Muapi/skinny-voluptous-slider-sdxl",
257
+ "file": "skinny-voluptous-slider-sdxl.safetensors",
258
+ },
259
+ "Asian features slider (photo chefs, SDXL)": {
260
+ "repo": "ntc-ai/SDXL-LoRA-slider.asian",
261
+ "file": "asian.safetensors",
262
+ },
263
+ "Add detail XL (photo chefs, SDXL)": {
264
+ "repo": "highscoregames12018/add-detail-xl",
265
+ "file": "add-detail-xl.safetensors",
266
+ },
267
+ }
268
+ LORA_CHOICES = [LORA_NONE] + list(LORAS) + [LORA_CUSTOM]
269
+ DEFAULT_LORA_STRENGTH = 0.8
270
+ LORA_ADAPTER = "roulette_lora"
271
+ REPO_ID_PATTERN = re.compile(r"^[A-Za-z0-9][\w.\-]*/[\w.\-]+$")
272
+
273
+ # ---------------------------------------------------------------------------
274
+ # Samplers (set per spin from the chef's own scheduler config)
275
+ # ---------------------------------------------------------------------------
276
+ SAMPLERS = ["Euler a", "DPM++ 2M Karras", "DPM++ SDE Karras", "UniPC"]
277
+ DEFAULT_SAMPLER = "Euler a"
278
+
279
+ # Nude frame: how frame 2 is made
280
+ NUDE_MODE_SAME = "Fresh render same seed"
281
+ NUDE_MODE_NEW = "Fresh render new seed"
282
+ NUDE_MODE_REVEAL = "Reveal from clothed picture"
283
+ NUDE_MODES = [NUDE_MODE_SAME, NUDE_MODE_NEW, NUDE_MODE_REVEAL]
284
+ DEFAULT_NUDE_MODE = NUDE_MODE_SAME
285
+ # Reveal strength: 0.55 kept the clothes, so start high
286
+ DEFAULT_REVEAL_STRENGTH = 0.72
287
+ REVEAL_MIN, REVEAL_MAX = 0.4, 0.9
288
+
289
+ # Art mode: which styles and chefs a spin may draw
290
+ ART_CARTOON = "Cartoon"
291
+ ART_PHOTO = "Photo"
292
+ ART_MODES = [ART_CARTOON, ART_PHOTO]
293
+ DEFAULT_ART_MODE = ART_CARTOON
294
+ ART_KIND = {ART_CARTOON: "anime", ART_PHOTO: "photo"}
295
+ STYLE_RANDOM = "Roll random"
296
+
297
+ # Reference picture upload
298
+ PIC_OFF = "Off"
299
+ PIC_LOOK = "Copy the look"
300
+ PIC_REDRAW = "Redraw my pic"
301
+ PIC_MODES = [PIC_OFF, PIC_LOOK, PIC_REDRAW]
302
+ DEFAULT_PIC_MODE = PIC_OFF
303
+ DEFAULT_LOOK_STRENGTH = 0.6
304
+ LOOK_MIN, LOOK_MAX = 0.2, 1.0
305
+ DEFAULT_REDRAW_STRENGTH = 0.6
306
+ REDRAW_MIN, REDRAW_MAX = 0.3, 0.9
307
+ # IP-Adapter for SDXL, ViT-H variant (file list checked on the HF Hub API, Oct 24 2026).
308
+ # General look adapter only: the face adapters in that repo are deliberately not used.
309
+ IP_REPO = "h94/IP-Adapter"
310
+ IP_SUBFOLDER = "sdxl_models"
311
+ IP_WEIGHT = "ip-adapter_sdxl_vit-h.safetensors"
312
+ IP_ENCODER_FOLDER = "models/image_encoder" # ViT-H encoder, 2.5 GB (smaller than the bigG one)
313
+ IP_FILES = [
314
+ f"{IP_SUBFOLDER}/{IP_WEIGHT}",
315
+ f"{IP_ENCODER_FOLDER}/config.json",
316
+ f"{IP_ENCODER_FOLDER}/model.safetensors",
317
+ ]
318
+
319
+ FIELDS = ["chef", "style", "scene", "outfit", "nude_look", "pose", "light", "camera", "woman"]
320
+
321
+ # ---------------------------------------------------------------------------
322
+ # Hard locks
323
+ # ---------------------------------------------------------------------------
324
+ ADULT_TAGS = "masterpiece, best quality, 1girl, solo, adult woman over 21, late 20s, fictional character"
325
+ # No "21+" here: in compel a trailing + means "weight up", so plain words only
326
+ FRAME_HEAD = "1girl, solo, adult woman over 21, late 20s, Asian woman"
327
+ ASIAN_LOCK = "beautiful Asian woman, Asian facial features, Asian eyes, dark hair"
328
+ BODY_LOCK = (
329
+ "tall, slim body, small frame, tiny waist, "
330
+ "huge breasts, very large breasts, heavy full round breasts, busty, deep cleavage, slender thighs"
331
+ )
332
+
333
+ # Short versions so the important words fit inside the first 75 tokens
334
+ BODY_LOCK_SHORT = "huge breasts, very large breasts, busty, tall, slim, tiny waist"
335
+ NUDE_FRONT = "(completely nude, naked, bare breasts, nipples)1.4, nsfw, explicit, no clothes"
336
+ # Weighted negatives so each frame pushes away the other frame's state
337
+ CLOTHED_FRAME_NEG = "(nude, naked, topless, nipples, bare breasts)1.3"
338
+ NUDE_FRAME_NEG = (
339
+ "(clothes, clothing, shirt, dress, robe, bra, panties, lingerie, bikini, swimsuit, "
340
+ "towel, corset, blazer, sweater, covered breasts, covered nipples)1.4"
341
+ )
342
+
343
+ BASE_NEGATIVES = (
344
+ "child, loli, underage, teen, young teen, barely legal, "
345
+ "18, eighteen, 19, nineteen, "
346
+ "man, men, male, boy, guy, guys, male focus, masculine, "
347
+ "old, elderly, aged, grandma, wrinkly, "
348
+ "fat, chubby, obese, overweight, belly fat, thick thighs, thick body, "
349
+ "beard, mustache, penis, dick, balls, "
350
+ "bad hands, extra fingers, deformed, "
351
+ "blurry, lowres, watermark, text, censored, ugly, celebrity, real person, "
352
+ "caucasian, white woman, european, blonde hair, small breasts, flat chest"
353
+ )
354
+
355
+ FORBIDDEN_KEYWORDS = []
356
+ if os.path.exists("restricted_words.txt"):
357
+ try:
358
+ with open("restricted_words.txt", "r", encoding="utf-8") as f:
359
+ FORBIDDEN_KEYWORDS = [
360
+ line.strip().lower() for line in f
361
+ if line.strip() and not line.strip().startswith("#")
362
+ ]
363
+ except Exception as e:
364
+ logger.error(f"restricted words load failed: {e}")
365
+
366
+ # 21+: block ages under 21 in prompt text (includes 19 / nineteen)
367
+ AGE_PATTERN = re.compile(
368
+ r"\b(one|two|three|four|five|six|seven|eight|nine|ten|"
369
+ r"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|"
370
+ r"1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19)"
371
+ r"\s*[-\s]?\s*(year|yr|y\/o|yo)\b"
372
+ )
373
+ MINOR_WORDS = re.compile(r"\b(child|kid|loli|teen|teenage|underage|minor|schoolgirl|young girl|little girl)\b")
374
+
375
+
376
+ def check_prompt_safety(prompt: str):
377
+ clean = str(prompt).lower().replace("-", " ").replace("_", " ")
378
+ for word in FORBIDDEN_KEYWORDS:
379
+ if word in clean:
380
+ return False, word
381
+ match = AGE_PATTERN.search(clean) or MINOR_WORDS.search(clean)
382
+ if match:
383
+ return False, match.group(0)
384
+ return True, None
385
+
386
+
387
+ # ---------------------------------------------------------------------------
388
+ # Pure recipe logic (no GPU)
389
+ # ---------------------------------------------------------------------------
390
+ def random_woman(rng=random):
391
+ return (
392
+ f"adult {rng.choice(ETHNICITIES)} Asian woman late 20s, "
393
+ f"{rng.choice(HAIRS)}, {rng.choice(FACES)}"
394
+ )
395
+
396
+
397
+ def styles_for_mode(art_mode):
398
+ """Cartoon: anime styles only (no Photoreal). Photo: styles a photo chef can draw."""
399
+ kind = ART_KIND.get(art_mode, "anime")
400
+ return [name for name, spec in STYLES.items() if kind in spec["kinds"]]
401
+
402
+
403
+ def chefs_for_mode(art_mode):
404
+ kind = ART_KIND.get(art_mode, "anime")
405
+ return [name for name, spec in CHEFS.items() if spec["kind"] == kind]
406
+
407
+
408
+ def chef_pool_for_style(style_name, art_mode=DEFAULT_ART_MODE):
409
+ kinds = STYLES.get(style_name, STYLES["Photoreal"])["kinds"]
410
+ pool = [n for n in chefs_for_mode(art_mode) if CHEFS[n]["kind"] in kinds]
411
+ return pool or chefs_for_mode(art_mode)
412
+
413
+
414
+ def roll_recipe(prev=None, locks=None, new_woman=True, rng=random,
415
+ art_mode=DEFAULT_ART_MODE, style_pick=STYLE_RANDOM):
416
+ """Slot machine roll. Locked fields keep prev values; the rest spin.
417
+
418
+ Art mode decides the style and chef pools. A locked style or chef that does
419
+ not belong to the current art mode is re-rolled inside that mode.
420
+ The Style dropdown (style_pick) forces one style when it is not "Roll random".
421
+ """
422
+ prev = dict(prev or {})
423
+ locks = locks or {}
424
+ if art_mode not in ART_MODES:
425
+ art_mode = DEFAULT_ART_MODE
426
+ style_pool = styles_for_mode(art_mode)
427
+ chef_pool = chefs_for_mode(art_mode)
428
+
429
+ def keep(field):
430
+ return bool(locks.get(field)) and prev.get(field)
431
+
432
+ recipe = {"art": art_mode}
433
+ if style_pick in style_pool:
434
+ recipe["style"] = style_pick
435
+ elif keep("style") and prev["style"] in style_pool:
436
+ recipe["style"] = prev["style"]
437
+ else:
438
+ recipe["style"] = rng.choice(style_pool)
439
+ if keep("chef") and prev["chef"] in chef_pool:
440
+ recipe["chef"] = prev["chef"]
441
+ else:
442
+ recipe["chef"] = rng.choice(chef_pool_for_style(recipe["style"], art_mode))
443
+ recipe["scene"] = prev["scene"] if keep("scene") else rng.choice(SCENES)
444
+ recipe["outfit"] = prev["outfit"] if keep("outfit") else rng.choice(CLOTHED_OUTFITS)
445
+ recipe["nude_look"] = prev["nude_look"] if keep("nude_look") else rng.choice(NUDE_OUTFITS)
446
+ recipe["pose"] = prev["pose"] if keep("pose") else rng.choice(POSES)
447
+ recipe["light"] = prev["light"] if keep("light") else rng.choice(LIGHTS)
448
+ recipe["camera"] = prev["camera"] if keep("camera") else rng.choice(CAMERAS)
449
+ if keep("woman"):
450
+ recipe["woman"] = prev["woman"]
451
+ elif new_woman:
452
+ recipe["woman"] = random_woman(rng)
453
+ else:
454
+ recipe["woman"] = prev.get("woman") or DEFAULT_FACE
455
+ recipe["tease"] = rng.choice(TEASE_STATES)
456
+ return recipe
457
+
458
+
459
+ def _join(*parts):
460
+ return ", ".join(p.strip(" ,") for p in parts if p and str(p).strip(" ,"))
461
+
462
+
463
+ def _outfit_for_negative(outfit):
464
+ """Clothed outfit words for the nude negative, minus words that are fine nude."""
465
+ keep_ok = {"deep cleavage", "sheer stockings"}
466
+ parts = [w.strip() for w in str(outfit or "").split(",")]
467
+ return ", ".join(w for w in parts if w and w not in keep_ok)
468
+
469
+
470
+ def build_frames(recipe, tease_reveal=False, extra=""):
471
+ """Return list of (label, positive, negative).
472
+
473
+ The words that make the two frames different go FIRST and are weighted
474
+ with compel syntax, e.g. (completely nude, naked)1.4. The nude frame also
475
+ carries the clothed frame's outfit in its negative, weighted, so the
476
+ clothes are pushed away instead of copied.
477
+ """
478
+ style = STYLES.get(recipe.get("style"), STYLES["Photoreal"])
479
+ negative = _join(BASE_NEGATIVES, style["neg"])
480
+ woman = recipe.get("woman") or DEFAULT_FACE
481
+ after = _join(woman, BODY_LOCK_SHORT, style["prefix"], recipe.get("pose"), recipe.get("camera"),
482
+ recipe.get("scene"), recipe.get("light"), extra)
483
+ outfit = recipe.get("outfit") or CLOTHED_OUTFITS[0]
484
+ outfit_neg = _outfit_for_negative(outfit)
485
+ nude_neg = _join(negative, NUDE_FRAME_NEG, f"({outfit_neg})1.3" if outfit_neg else "")
486
+
487
+ if not tease_reveal:
488
+ # Pair: frame 1 clothed, frame 2 nude
489
+ clothed = _join(f"(wearing {outfit}, clothed)1.3", FRAME_HEAD, after)
490
+ nude = _join(NUDE_FRONT, recipe.get("nude_look") or NUDE_OUTFITS[0], FRAME_HEAD, after)
491
+ return [
492
+ ("Clothed", clothed, _join(negative, CLOTHED_FRAME_NEG)),
493
+ ("Nude", nude, nude_neg),
494
+ ]
495
+
496
+ frame1 = _join(f"({recipe.get('tease')}, partially covered, teasing)1.2", FRAME_HEAD,
497
+ "full body shot", after)
498
+ frame2 = _join(NUDE_FRONT, FRAME_HEAD, "full body shot", after)
499
+ return [
500
+ ("Tease", frame1, negative),
501
+ ("Reveal", frame2, nude_neg),
502
+ ]
503
+
504
+
505
+ def recipe_card(recipe, seed=None):
506
+ if not recipe:
507
+ return "_No roll yet. Hit **Spin**._"
508
+ lines = ["### Recipe"]
509
+ for field in FIELDS:
510
+ lines.append(f"- **{field.replace('_', ' ').title()}**: {recipe.get(field, '')}")
511
+ if seed is not None:
512
+ lines.append(f"- **Seed**: {seed}")
513
+ return "\n".join(lines)
514
+
515
+
516
+ def history_label(i, entry):
517
+ r = entry["recipe"]
518
+ return f"{i + 1}. {r['style']} | {r['scene']} | {r['outfit']} | seed {entry['seed']}"
519
+
520
+
521
+ def push_history(history, recipe, seed):
522
+ history = list(history or [])
523
+ history.insert(0, {"recipe": dict(recipe), "seed": seed})
524
+ return history[:HISTORY_SIZE]
525
+
526
+
527
+ # ---------------------------------------------------------------------------
528
+ # Spin logging (on by default; set Space variable LOG_VISITOR_UPLOADS=0 to turn off)
529
+ # ---------------------------------------------------------------------------
530
+ _LOG_LOCK = threading.Lock()
531
+
532
+
533
+ def should_log_upload(username) -> bool:
534
+ return bool(LOG_VISITOR_UPLOADS)
535
+
536
+
537
+ def async_log_upload(pil_img, seed, model_name, prompt, username, width, height, steps, cfg_scale):
538
+ if not should_log_upload(username):
539
+ logger.info("visitor log upload skipped (LOG_VISITOR_UPLOADS not enabled)")
540
+ return
541
+ hf_token = os.environ.get("HF_TOKEN")
542
+ if not username or not str(username).strip():
543
+ username = "Unknown_Visitor"
544
+ timestamp = int(time.time())
545
+ clean = str(model_name).replace("/", "_")[:18]
546
+ filename_base = f"gen_{timestamp}_seed_{seed}_{clean}"
547
+ buf = io.BytesIO()
548
+ pil_img.save(buf, format="WEBP", quality=95)
549
+ raw = buf.getvalue()
550
+ if not hf_token:
551
+ logger.error("HF_TOKEN missing - log upload skipped")
552
+ return
553
+ api = HfApi(token=hf_token)
554
+ date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(timestamp))
555
+ log_entry = f"[{date_str}] | User: {username} | Model: {model_name} | Seed: {seed} | Prompt: {prompt[:150]}...\n"
556
+ user_log = f"user_logs/{username}_history.txt"
557
+ with _LOG_LOCK:
558
+ _commit_log(api, hf_token, username, user_log, log_entry, filename_base, raw, timestamp)
559
+
560
+
561
+ def _commit_log(api, hf_token, username, user_log, log_entry, filename_base, raw, timestamp):
562
+ for attempt in range(1, 4):
563
+ try:
564
+ try:
565
+ path = hf_hub_download(BACKUP_DATASET_ID, "traffic_logs.txt", repo_type="dataset", token=hf_token)
566
+ current = open(path, encoding="utf-8").read()
567
+ except Exception:
568
+ current = "=== TRAFFIC LOGS ===\n"
569
+ try:
570
+ upath = hf_hub_download(BACKUP_DATASET_ID, user_log, repo_type="dataset", token=hf_token)
571
+ user_logs = open(upath, encoding="utf-8").read()
572
+ except Exception:
573
+ user_logs = f"=== HISTORY FOR {username} ===\n"
574
+ ops = [
575
+ CommitOperationAdd(path_in_repo="traffic_logs.txt", path_or_fileobj=(current + log_entry).encode()),
576
+ CommitOperationAdd(path_in_repo=user_log, path_or_fileobj=(user_logs + log_entry).encode()),
577
+ CommitOperationAdd(path_in_repo=f"data/{filename_base}.webp", path_or_fileobj=raw),
578
+ ]
579
+ api.create_commit(
580
+ repo_id=BACKUP_DATASET_ID, repo_type="dataset", operations=ops,
581
+ commit_message=f"gen for {username} @ {timestamp}",
582
+ )
583
+ logger.info(f"logged {username} attempt {attempt}")
584
+ return
585
+ except Exception as e:
586
+ logger.error(f"log fail {attempt}: {e}")
587
+ time.sleep(1.5 * attempt)
588
+
589
+
590
+ # ---------------------------------------------------------------------------
591
+ # Pipeline (one chef cached at a time)
592
+ # ---------------------------------------------------------------------------
593
+ _pipe = None
594
+ _pipe_chef = None
595
+ _img2img = None
596
+ _base_sched_config = None
597
+ _ip_loaded = False
598
+
599
+
600
+ def _hf_token():
601
+ return os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
602
+
603
+
604
+ def unload_pipe():
605
+ global _pipe, _pipe_chef, _img2img, _base_sched_config, _ip_loaded
606
+ _pipe = None
607
+ _pipe_chef = None
608
+ _img2img = None
609
+ _base_sched_config = None
610
+ _ip_loaded = False
611
+ gc.collect()
612
+ if torch.cuda.is_available():
613
+ torch.cuda.empty_cache()
614
+
615
+
616
+ def get_pipe(chef_name):
617
+ global _pipe, _pipe_chef, _base_sched_config
618
+ if _pipe is not None and _pipe_chef == chef_name:
619
+ return _pipe
620
+ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
621
+
622
+ unload_pipe()
623
+ spec = CHEFS[chef_name]
624
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
625
+ logger.info(f"Loading chef {chef_name} ({spec['repo']})")
626
+ pipe = StableDiffusionXLPipeline.from_pretrained(
627
+ spec["repo"], torch_dtype=dtype, use_safetensors=True, token=_hf_token(),
628
+ )
629
+ # Keep the chef's own scheduler config so every sampler swap starts clean
630
+ _base_sched_config = dict(pipe.scheduler.config)
631
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(_base_sched_config)
632
+ if torch.cuda.is_available():
633
+ pipe.to("cuda")
634
+ pipe.vae.enable_slicing()
635
+ pipe.vae.enable_tiling()
636
+ _pipe, _pipe_chef = pipe, chef_name
637
+ return pipe
638
+
639
+
640
+ def get_img2img(pipe):
641
+ """Img2img pipe that reuses the SAME unet, vae and text encoders (no extra VRAM)."""
642
+ global _img2img
643
+ if _img2img is not None:
644
+ return _img2img
645
+ from diffusers import StableDiffusionXLImg2ImgPipeline
646
+ try:
647
+ _img2img = StableDiffusionXLImg2ImgPipeline.from_pipe(pipe)
648
+ except Exception as e:
649
+ logger.warning(f"from_pipe failed ({e}), sharing components by hand")
650
+ _img2img = StableDiffusionXLImg2ImgPipeline(**pipe.components)
651
+ return _img2img
652
+
653
+
654
+ def make_scheduler(sampler_name):
655
+ """Fresh scheduler for this spin, built from the chef's original config."""
656
+ from diffusers import (
657
+ EulerAncestralDiscreteScheduler,
658
+ DPMSolverMultistepScheduler,
659
+ UniPCMultistepScheduler,
660
+ )
661
+ config = _base_sched_config or dict(_pipe.scheduler.config)
662
+ if sampler_name == "DPM++ 2M Karras":
663
+ return DPMSolverMultistepScheduler.from_config(
664
+ config, algorithm_type="dpmsolver++", solver_order=2, use_karras_sigmas=True)
665
+ if sampler_name == "DPM++ SDE Karras":
666
+ # sde-dpmsolver++ gives the SDE flavour without needing torchsde
667
+ return DPMSolverMultistepScheduler.from_config(
668
+ config, algorithm_type="sde-dpmsolver++", solver_order=2, use_karras_sigmas=True)
669
+ if sampler_name == "UniPC":
670
+ return UniPCMultistepScheduler.from_config(config)
671
+ return EulerAncestralDiscreteScheduler.from_config(config)
672
+
673
+
674
+ def resolve_lora(lora_choice, custom_repo, custom_file):
675
+ """Return (repo, weight_file) or None."""
676
+ if not lora_choice or lora_choice == LORA_NONE:
677
+ return None
678
+ if lora_choice == LORA_CUSTOM:
679
+ repo = (custom_repo or "").strip()
680
+ if not repo:
681
+ return None
682
+ if not REPO_ID_PATTERN.match(repo):
683
+ logger.warning(f"custom LoRA repo id looks wrong, skipping: {repo!r}")
684
+ return None
685
+ return repo, ((custom_file or "").strip() or None)
686
+ spec = LORAS.get(lora_choice)
687
+ return (spec["repo"], spec["file"]) if spec else None
688
+
689
+
690
+ def clear_lora(pipe):
691
+ """Drop any LoRA left from an earlier spin so they never stack."""
692
+ try:
693
+ pipe.unfuse_lora()
694
+ except Exception:
695
+ pass
696
+ try:
697
+ pipe.unload_lora_weights()
698
+ except Exception as e:
699
+ logger.warning(f"LoRA unload warning: {e}")
700
+
701
+
702
+ def apply_lora(pipe, lora, strength):
703
+ """Load one LoRA by adapter name. A bad LoRA logs a warning and the spin goes on."""
704
+ clear_lora(pipe)
705
+ if not lora or float(strength) <= 0:
706
+ return None
707
+ repo, weight_file = lora
708
+ try:
709
+ kwargs = {"adapter_name": LORA_ADAPTER, "token": _hf_token()}
710
+ if weight_file:
711
+ kwargs["weight_name"] = weight_file
712
+ pipe.load_lora_weights(repo, **kwargs)
713
+ pipe.set_adapters([LORA_ADAPTER], adapter_weights=[float(strength)])
714
+ logger.info(f"LoRA on: {repo} ({weight_file}) at {strength}")
715
+ return f"{repo} @ {float(strength):.2f}"
716
+ except Exception as e:
717
+ logger.warning(f"LoRA {repo} failed, rendering without it: {e}")
718
+ clear_lora(pipe)
719
+ return None
720
+
721
+
722
+ def prefetch_ip_adapter():
723
+ """Download the IP-Adapter files on the CPU side, before the GPU clock starts.
724
+
725
+ Returns None when ready, or an error string.
726
+ """
727
+ try:
728
+ for f in IP_FILES:
729
+ hf_hub_download(IP_REPO, f, token=_hf_token())
730
+ return None
731
+ except Exception as e:
732
+ logger.warning(f"IP-Adapter download failed: {e}")
733
+ return str(e)
734
+
735
+
736
+ def ensure_ip_adapter(pipe, want):
737
+ """Load IP-Adapter once per cached chef, or unload it when not wanted.
738
+
739
+ Returns (ok, error_text). The img2img twin is rebuilt after any change so it
740
+ picks up the new image encoder and attention processors.
741
+ """
742
+ global _ip_loaded, _img2img
743
+ if want and not _ip_loaded:
744
+ try:
745
+ pipe.load_ip_adapter(
746
+ IP_REPO, subfolder=IP_SUBFOLDER, weight_name=IP_WEIGHT,
747
+ image_encoder_folder=IP_ENCODER_FOLDER, token=_hf_token(),
748
+ )
749
+ _ip_loaded = True
750
+ _img2img = None
751
+ logger.info("IP-Adapter loaded")
752
+ except Exception as e:
753
+ logger.warning(f"IP-Adapter load failed, rendering without it: {e}")
754
+ try:
755
+ pipe.unload_ip_adapter()
756
+ except Exception:
757
+ pass
758
+ _ip_loaded = False
759
+ _img2img = None
760
+ return False, str(e)
761
+ elif not want and _ip_loaded:
762
+ try:
763
+ pipe.unload_ip_adapter()
764
+ except Exception as e:
765
+ logger.warning(f"IP-Adapter unload warning: {e}")
766
+ _ip_loaded = False
767
+ _img2img = None
768
+ return (_ip_loaded if want else True), None
769
+
770
+
771
+ def fit_picture(img, width, height):
772
+ """Resize and center crop the upload to the chosen size preset."""
773
+ from PIL import Image, ImageOps
774
+ if img is None:
775
+ return None
776
+ if not isinstance(img, Image.Image):
777
+ img = Image.fromarray(img)
778
+ return ImageOps.fit(img.convert("RGB"), (int(width), int(height)), Image.LANCZOS)
779
+
780
+
781
+ def _gpu_duration(*args, **kwargs):
782
+ # Copy the look may load IP-Adapter onto the GPU, so it gets a little more room
783
+ return 120 if kwargs.get("picture_mode") == PIC_LOOK else 90
784
+
785
+
786
+ def _gpu(fn):
787
+ # 90 s reservation (120 s with Copy the look): ZeroGPU checks this against your remaining daily time
788
+ if not SPACES_AVAILABLE:
789
+ return fn
790
+ try:
791
+ return spaces.GPU(duration=_gpu_duration)(fn)
792
+ except Exception as e:
793
+ logger.warning(f"dynamic GPU duration not supported ({e}), using 120 s")
794
+ return spaces.GPU(duration=120)(fn)
795
+
796
+
797
+ WEIGHT_SYNTAX = re.compile(r"\(([^()]*)\)[0-9.]+")
798
+
799
+
800
+ def strip_weights(text):
801
+ """(words)1.4 becomes words, for the plain fallback without compel."""
802
+ return WEIGHT_SYNTAX.sub(r"\1", str(text))
803
+
804
+
805
+ def _long_prompt_kwargs(pipe, positive, negative):
806
+ """Encode the WHOLE prompt with compel, weights included.
807
+
808
+ Plain diffusers cuts every prompt at 77 tokens and ignores (words)1.4.
809
+ Compel reads past 77 tokens and applies the weights. A NEW encoder runs for
810
+ every frame, so frame 2 never reuses frame 1's embeddings.
811
+ """
812
+ import compel as compel_pkg
813
+ if hasattr(compel_pkg, "CompelForSDXL"):
814
+ enc = compel_pkg.CompelForSDXL(pipe)
815
+ out = enc(positive, negative_prompt=negative)
816
+ return {
817
+ "prompt_embeds": out.embeds,
818
+ "pooled_prompt_embeds": out.pooled_embeds,
819
+ "negative_prompt_embeds": out.negative_embeds,
820
+ "negative_pooled_prompt_embeds": out.negative_pooled_embeds,
821
+ }
822
+ from compel import Compel, ReturnedEmbeddingsType
823
+ enc = Compel(
824
+ tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
825
+ text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
826
+ returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
827
+ requires_pooled=[False, True],
828
+ truncate_long_prompts=False,
829
+ )
830
+ pos_embeds, pos_pooled = enc(positive)
831
+ neg_embeds, neg_pooled = enc(negative)
832
+ pos_embeds, neg_embeds = enc.pad_conditioning_tensors_to_same_length([pos_embeds, neg_embeds])
833
+ return {
834
+ "prompt_embeds": pos_embeds,
835
+ "pooled_prompt_embeds": pos_pooled,
836
+ "negative_prompt_embeds": neg_embeds,
837
+ "negative_pooled_prompt_embeds": neg_pooled,
838
+ }
839
+
840
+
841
+ def _prompt_kwargs(pipe, positive, negative):
842
+ try:
843
+ return _long_prompt_kwargs(pipe, positive, negative), "compel"
844
+ except Exception as e:
845
+ logger.warning(f"compel encode failed, using plain prompt cut at 77 tokens: {e}")
846
+ return {"prompt": strip_weights(positive), "negative_prompt": strip_weights(negative)}, "plain"
847
+
848
+
849
+ @_gpu
850
+ def render_frames(chef_name, frames, seeds, steps, guidance_scale, width, height,
851
+ nude_mode=DEFAULT_NUDE_MODE, reveal_strength=DEFAULT_REVEAL_STRENGTH,
852
+ lora=None, lora_strength=DEFAULT_LORA_STRENGTH, sampler=DEFAULT_SAMPLER,
853
+ ref_image=None, picture_mode=DEFAULT_PIC_MODE,
854
+ look_strength=DEFAULT_LOOK_STRENGTH, redraw_strength=DEFAULT_REDRAW_STRENGTH):
855
+ """frames: list of (label, positive, negative); seeds: one seed per frame.
856
+
857
+ No picture: frame 1 is txt2img; later frames are txt2img (fresh modes) or
858
+ img2img on frame 1 (reveal mode).
859
+ Copy the look: same as above, with IP-Adapter steering every frame.
860
+ Redraw my pic: frame 1 is img2img from the upload; the nude frame is img2img
861
+ from the upload too (strength + 0.1), unless reveal mode is on.
862
+ ref_image arrives already fitted to width x height.
863
+ """
864
+ pipe = get_pipe(chef_name)
865
+ device = "cuda" if torch.cuda.is_available() else "cpu"
866
+ use_look = picture_mode == PIC_LOOK and ref_image is not None
867
+ use_redraw = picture_mode == PIC_REDRAW and ref_image is not None
868
+ ip_ok, ip_error = ensure_ip_adapter(pipe, use_look)
869
+ ip_kwargs = {}
870
+ if use_look and ip_ok:
871
+ try:
872
+ pipe.set_ip_adapter_scale(float(look_strength))
873
+ ip_kwargs = {"ip_adapter_image": ref_image}
874
+ except Exception as e:
875
+ logger.warning(f"IP-Adapter scale failed, rendering without it: {e}")
876
+ ip_error = str(e)
877
+ ensure_ip_adapter(pipe, False)
878
+ ip_ok = False
879
+ if use_look:
880
+ ip_note = (f"on at {float(look_strength):.2f}" if ip_kwargs
881
+ else f"failed, rendered without it ({str(ip_error)[:160]})")
882
+ else:
883
+ ip_note = None
884
+ lora_note = apply_lora(pipe, lora, lora_strength)
885
+ images = []
886
+ encoders = []
887
+ try:
888
+ first_image = None
889
+ for i, (label, positive, negative) in enumerate(frames):
890
+ gen = torch.Generator(device=device).manual_seed(int(seeds[i]))
891
+ prompt_kwargs, enc_name = _prompt_kwargs(pipe, positive, negative)
892
+ encoders.append(enc_name)
893
+ source, strength = None, None
894
+ if nude_mode == NUDE_MODE_REVEAL and i > 0 and first_image is not None:
895
+ source, strength = first_image, float(reveal_strength)
896
+ elif use_redraw:
897
+ bump = 0.0 if i == 0 else 0.1
898
+ source, strength = ref_image, min(REDRAW_MAX, float(redraw_strength) + bump)
899
+ if source is not None:
900
+ i2i = get_img2img(pipe)
901
+ i2i.scheduler = make_scheduler(sampler)
902
+ out = i2i(
903
+ **prompt_kwargs,
904
+ **ip_kwargs,
905
+ image=source.copy(),
906
+ strength=strength,
907
+ num_inference_steps=int(steps),
908
+ guidance_scale=float(guidance_scale),
909
+ generator=gen,
910
+ ).images[0]
911
+ else:
912
+ # fresh scheduler every frame so no state carries over
913
+ try:
914
+ pipe.scheduler = make_scheduler(sampler)
915
+ except Exception as e:
916
+ logger.warning(f"sampler {sampler} failed, keeping current: {e}")
917
+ out = pipe(
918
+ **prompt_kwargs,
919
+ **ip_kwargs,
920
+ num_inference_steps=int(steps),
921
+ guidance_scale=float(guidance_scale),
922
+ width=int(width),
923
+ height=int(height),
924
+ generator=gen,
925
+ ).images[0]
926
+ if i == 0:
927
+ first_image = out
928
+ images.append((label, out))
929
+ finally:
930
+ if lora_note:
931
+ clear_lora(pipe)
932
+ return images, lora_note, encoders, ip_note
933
+
934
+
935
+ # ---------------------------------------------------------------------------
936
+ # UI handlers
937
+ # ---------------------------------------------------------------------------
938
+ def _locks_from_flags(flags):
939
+ return {field: bool(flag) for field, flag in zip(FIELDS, flags)}
940
+
941
+
942
+ def _resolve_seed(seed_value):
943
+ try:
944
+ s = int(float(seed_value))
945
+ except (TypeError, ValueError):
946
+ s = -1
947
+ return random.randint(0, 2**31 - 1) if s < 0 else s
948
+
949
+
950
+ def _cook(recipe, seed, tease_reveal, extra, size_name, steps, guidance_scale,
951
+ nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
952
+ ref_image, picture_mode, look_strength, redraw_strength,
953
+ username, gallery_items, history):
954
+ """Shared render path for Spin and Re-roll. Returns UI outputs."""
955
+ user_key = username or "anonymous"
956
+ now = time.time()
957
+ last = LAST_GEN_TIME.get(user_key)
958
+ if last and now - last < COOLDOWN_SECONDS:
959
+ left = int(COOLDOWN_SECONDS - (now - last))
960
+ raise gr.Error(f"Cooldown {left}s")
961
+
962
+ frames = build_frames(recipe, tease_reveal=bool(tease_reveal), extra=extra or "")
963
+ for _, positive, _ in frames:
964
+ ok, bad = check_prompt_safety(positive)
965
+ if not ok:
966
+ raise gr.Error("Restricted content in prompt")
967
+
968
+ width, height = SIZE_PRESETS.get(size_name, SIZE_PRESETS["Portrait 832x1216"])
969
+ use_steps = int(max(10, min(40, int(steps or DEFAULT_STEPS))))
970
+ use_guidance = float(guidance_scale if guidance_scale is not None else DEFAULT_GUIDANCE)
971
+ use_mode = nude_mode if nude_mode in NUDE_MODES else DEFAULT_NUDE_MODE
972
+ use_reveal_strength = float(max(REVEAL_MIN, min(REVEAL_MAX, float(reveal_strength or DEFAULT_REVEAL_STRENGTH))))
973
+ use_lora_strength = float(max(0.0, min(1.5, float(lora_strength if lora_strength is not None else DEFAULT_LORA_STRENGTH))))
974
+ use_sampler = sampler if sampler in SAMPLERS else DEFAULT_SAMPLER
975
+ lora = resolve_lora(lora_choice, lora_repo, lora_file)
976
+ seed = int(seed)
977
+ if use_mode == NUDE_MODE_NEW:
978
+ seeds = [seed] + [random.randint(0, 2**31 - 1) for _ in frames[1:]]
979
+ else:
980
+ seeds = [seed] * len(frames)
981
+ use_pic_mode = picture_mode if picture_mode in PIC_MODES else DEFAULT_PIC_MODE
982
+ pic_note = None
983
+ if use_pic_mode != PIC_OFF and ref_image is None:
984
+ pic_note = f"Picture mode {use_pic_mode} picked but no picture uploaded, so it ran Off"
985
+ use_pic_mode = PIC_OFF
986
+ use_look_strength = float(max(LOOK_MIN, min(LOOK_MAX, float(look_strength or DEFAULT_LOOK_STRENGTH))))
987
+ use_redraw_strength = float(max(REDRAW_MIN, min(REDRAW_MAX, float(redraw_strength or DEFAULT_REDRAW_STRENGTH))))
988
+ fitted = None
989
+ if use_pic_mode != PIC_OFF:
990
+ try:
991
+ fitted = fit_picture(ref_image, width, height)
992
+ except Exception as e:
993
+ logger.warning(f"could not read the uploaded picture: {e}")
994
+ pic_note = f"Could not read the uploaded picture, so it ran Off ({e})"
995
+ use_pic_mode = PIC_OFF
996
+ if use_pic_mode == PIC_LOOK:
997
+ # download before the GPU clock starts
998
+ err = prefetch_ip_adapter()
999
+ if err:
1000
+ pic_note = f"Copy the look: IP-Adapter download failed, rendered without it ({err[:160]})"
1001
+ use_pic_mode, fitted = PIC_OFF, None
1002
+ LAST_GEN_TIME[user_key] = now
1003
+
1004
+ try:
1005
+ results, lora_note, encoders, ip_note = render_frames(
1006
+ recipe["chef"], frames, seeds, use_steps, use_guidance, width, height,
1007
+ nude_mode=use_mode, reveal_strength=use_reveal_strength,
1008
+ lora=lora, lora_strength=use_lora_strength, sampler=use_sampler,
1009
+ ref_image=fitted, picture_mode=use_pic_mode,
1010
+ look_strength=use_look_strength, redraw_strength=use_redraw_strength,
1011
+ )
1012
+ except Exception as e:
1013
+ logger.exception("render failed")
1014
+ msg = str(e)
1015
+ if "gated" in msg.lower() or "401" in msg or "403" in msg:
1016
+ msg += " (accept the model license and make sure the HF_TOKEN secret can read it)"
1017
+ raise gr.Error(msg)
1018
+
1019
+ new_items = []
1020
+ for (label, img), (_, positive, _), frame_seed in zip(results, frames, seeds):
1021
+ new_items.append((img, f"{label} | {recipe['chef']} | seed {frame_seed}"))
1022
+ threading.Thread(
1023
+ target=async_log_upload,
1024
+ args=(img, frame_seed, f"{label}_{recipe['chef']}", positive, username, width, height, use_steps, use_guidance),
1025
+ daemon=True,
1026
+ ).start()
1027
+
1028
+ gallery_items = (new_items + list(gallery_items or []))[:GALLERY_SIZE]
1029
+ history = push_history(history, recipe, seed)
1030
+ prompt_text = "\n\n".join(f"[{label}]\n{pos}\n[{label} negative]\n{neg}" for label, pos, neg in frames)
1031
+ notes = [
1032
+ f"Art mode: {recipe.get('art', DEFAULT_ART_MODE)}",
1033
+ f"Sampler: {use_sampler}",
1034
+ f"Nude frame mode: {use_mode}",
1035
+ f"Seeds: {', '.join(str(x) for x in seeds)}",
1036
+ f"Prompt encoder per frame: {', '.join(encoders)} (compel = weights on, plain = weights off, cut at 77 tokens)",
1037
+ ]
1038
+ if use_mode == NUDE_MODE_REVEAL:
1039
+ notes.append(f"Reveal strength {use_reveal_strength:.2f}")
1040
+ notes.append(f"Picture mode: {use_pic_mode}")
1041
+ if use_pic_mode == PIC_LOOK:
1042
+ notes.append(f"Copy the look (IP-Adapter {IP_WEIGHT}): {ip_note}")
1043
+ if use_pic_mode == PIC_REDRAW:
1044
+ if use_mode == NUDE_MODE_REVEAL:
1045
+ notes.append(f"Redraw strength {use_redraw_strength:.2f} on the clothed picture, nude picture revealed from it")
1046
+ else:
1047
+ notes.append(f"Redraw strength {use_redraw_strength:.2f} clothed, "
1048
+ f"{min(REDRAW_MAX, use_redraw_strength + 0.1):.2f} nude, both from your picture")
1049
+ if pic_note:
1050
+ notes.append(pic_note)
1051
+ if lora:
1052
+ notes.append(f"LoRA: {lora_note}" if lora_note else f"LoRA {lora[0]} failed to load, rendered without it")
1053
+ prompt_text = prompt_text + "\n\n[Settings]\n" + "\n".join(notes)
1054
+ choices = [history_label(i, h) for i, h in enumerate(history)]
1055
+ return (
1056
+ gallery_items,
1057
+ gallery_items,
1058
+ recipe_card(recipe, seed),
1059
+ prompt_text,
1060
+ recipe,
1061
+ history,
1062
+ gr.update(choices=choices, value=choices[0] if choices else None),
1063
+ )
1064
+
1065
+
1066
+ def on_spin(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps, guidance_scale,
1067
+ seed_value, nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1068
+ ref_image, picture_mode, look_strength, redraw_strength,
1069
+ username, gallery_items, history, *lock_flags):
1070
+ rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),
1071
+ art_mode=art_mode, style_pick=style_pick)
1072
+ return _cook(rolled, _resolve_seed(seed_value), tease_reveal, extra, size_name, steps,
1073
+ guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,
1074
+ lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,
1075
+ redraw_strength, username, gallery_items, history)
1076
+
1077
+
1078
+ def on_reroll_history(choice, tease_reveal, extra, size_name, steps, guidance_scale,
1079
+ nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1080
+ ref_image, picture_mode, look_strength, redraw_strength,
1081
+ username, gallery_items, history):
1082
+ """Re-roll uses whatever picture is in the upload box right now."""
1083
+ history = list(history or [])
1084
+ labels = [history_label(i, h) for i, h in enumerate(history)]
1085
+ if not choice or choice not in labels:
1086
+ raise gr.Error("Pick a recipe from history first")
1087
+ picked = history[labels.index(choice)]["recipe"]
1088
+ return _cook(dict(picked), _resolve_seed(-1), tease_reveal, extra, size_name, steps,
1089
+ guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,
1090
+ lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,
1091
+ redraw_strength, username, gallery_items, history)
1092
+
1093
+
1094
+ def on_load_history(choice, history):
1095
+ history = list(history or [])
1096
+ labels = [history_label(i, h) for i, h in enumerate(history)]
1097
+ if not choice or choice not in labels:
1098
+ return gr.update(), gr.update()
1099
+ entry = history[labels.index(choice)]
1100
+ return dict(entry["recipe"]), recipe_card(entry["recipe"], entry["seed"])
1101
+
1102
+
1103
+ def on_preview(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, *lock_flags):
1104
+ """Spin the card without rendering (free, no GPU)."""
1105
+ rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),
1106
+ art_mode=art_mode, style_pick=style_pick)
1107
+ frames = build_frames(rolled, tease_reveal=bool(tease_reveal), extra=extra or "")
1108
+ return rolled, recipe_card(rolled), "\n\n".join(f"[{l}]\n{p}" for l, p, _ in frames)
1109
+
1110
+
1111
+ def on_picture_upload(picture_mode):
1112
+ """A fresh upload switches Off to Copy the look; any other pick is kept."""
1113
+ return gr.update(value=PIC_LOOK if picture_mode in (None, PIC_OFF) else picture_mode)
1114
+
1115
+
1116
+ def on_picture_clear():
1117
+ return gr.update(value=PIC_OFF)
1118
+
1119
+
1120
+ def on_art_mode(art_mode, style_pick):
1121
+ """Refill the Style dropdown with the styles that suit the art mode."""
1122
+ pool = styles_for_mode(art_mode)
1123
+ value = style_pick if style_pick in pool else STYLE_RANDOM
1124
+ return gr.update(choices=[STYLE_RANDOM] + pool, value=value)
1125
+
1126
+
1127
+ js_visitor = """
1128
+ function() {
1129
+ let id = localStorage.getItem('adult_ai_visitor_id');
1130
+ if (!id) {
1131
+ id = 'Visitor_' + Math.floor(1000 + Math.random() * 9000);
1132
+ localStorage.setItem('adult_ai_visitor_id', id);
1133
+ }
1134
+ return id;
1135
+ }
1136
+ """
1137
+
1138
+
1139
+ def create_ui():
1140
+ with gr.Blocks(title="Roulette Lab") as demo:
1141
+ gr.Markdown(
1142
+ "# Roulette Lab\n"
1143
+ "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. "
1144
+ "Fictional adult women 21+ only. Visitor images are not saved unless the Space secret "
1145
+ "`LOG_VISITOR_UPLOADS=1` is set."
1146
+ )
1147
+ recipe_state = gr.State({})
1148
+ history_state = gr.State([])
1149
+ gallery_state = gr.State([])
1150
+ user_id = gr.Textbox(visible=False)
1151
+
1152
+ with gr.Row():
1153
+ with gr.Column(scale=1):
1154
+ spin_btn = gr.Button("Spin", variant="primary", size="lg")
1155
+ art_mode = gr.Radio(ART_MODES, value=DEFAULT_ART_MODE, label="Art mode")
1156
+ style_pick = gr.Dropdown([STYLE_RANDOM] + styles_for_mode(DEFAULT_ART_MODE), value=STYLE_RANDOM,
1157
+ label="Style (Roll random, or pick one to keep every spin)")
1158
+ preview_btn = gr.Button("Spin card only (no render)")
1159
+ card = gr.Markdown(recipe_card({}))
1160
+ gr.Markdown("**Lock slots** (locked slots survive the next spin)")
1161
+ lock_boxes = [gr.Checkbox(label=f"Lock {f.replace('_', ' ')}", value=False) for f in FIELDS]
1162
+ new_woman = gr.Checkbox(label="New woman each roll", value=True)
1163
+ tease_reveal = gr.Checkbox(label="Tease then reveal instead of clothed and nude (same seed, 2 frames)", value=False)
1164
+ nude_mode = gr.Radio(NUDE_MODES, value=DEFAULT_NUDE_MODE, label="Nude frame mode")
1165
+ reveal_strength = gr.Slider(REVEAL_MIN, REVEAL_MAX, value=DEFAULT_REVEAL_STRENGTH, step=0.05,
1166
+ label="Reveal strength (reveal mode only; low keeps more of the clothed picture)")
1167
+ extra = gr.Textbox(label="Extra tags (optional)", placeholder="e.g. glossy lips, rain on skin")
1168
+ with gr.Accordion("Your picture (optional)", open=False):
1169
+ ref_image = gr.Image(type="pil", label="Reference picture", sources=["upload", "clipboard"])
1170
+ gr.Markdown("Use for pose, outfit, style and mood. Faces come from the random deck, not your pic.")
1171
+ picture_mode = gr.Radio(PIC_MODES, value=DEFAULT_PIC_MODE, label="Picture mode")
1172
+ look_strength = gr.Slider(LOOK_MIN, LOOK_MAX, value=DEFAULT_LOOK_STRENGTH, step=0.05,
1173
+ label="Look strength (Copy the look; high copies more of your pic)")
1174
+ redraw_strength = gr.Slider(REDRAW_MIN, REDRAW_MAX, value=DEFAULT_REDRAW_STRENGTH, step=0.05,
1175
+ label="Redraw strength (Redraw my pic; low stays close to your pic)")
1176
+ with gr.Accordion("LoRA and sampler", open=False):
1177
+ lora_choice = gr.Dropdown(LORA_CHOICES, value=LORA_NONE, label="LoRA")
1178
+ lora_strength = gr.Slider(0.0, 1.5, value=DEFAULT_LORA_STRENGTH, step=0.05, label="LoRA strength")
1179
+ lora_repo = gr.Textbox(label="Custom LoRA repo id (pick Custom above)", placeholder="user/repo")
1180
+ lora_file = gr.Textbox(label="Custom LoRA weight file name", placeholder="name.safetensors")
1181
+ sampler = gr.Dropdown(SAMPLERS, value=DEFAULT_SAMPLER, label="Sampler")
1182
+ with gr.Accordion("Settings", open=False):
1183
+ size_name = gr.Radio(list(SIZE_PRESETS), value="Portrait 832x1216", label="Size")
1184
+ steps = gr.Slider(10, 40, value=DEFAULT_STEPS, step=1, label="Steps")
1185
+ guidance_scale = gr.Slider(1.0, 12.0, value=DEFAULT_GUIDANCE, step=0.5, label="CFG")
1186
+ seed_value = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")
1187
+ with gr.Column(scale=2):
1188
+ gallery = gr.Gallery(label="Output", columns=2, height=720)
1189
+ prompt_box = gr.Textbox(label="Prompt sent", lines=8, interactive=False)
1190
+ gr.Markdown("**History** (last 10 recipes)")
1191
+ history_dd = gr.Dropdown(choices=[], label="Pick a recipe", interactive=True)
1192
+ with gr.Row():
1193
+ reroll_btn = gr.Button("Re-roll this recipe, new seed")
1194
+ load_btn = gr.Button("Load into card (then lock and spin)")
1195
+
1196
+ advanced = [nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,
1197
+ ref_image, picture_mode, look_strength, redraw_strength]
1198
+ outputs = [gallery, gallery_state, card, prompt_box, recipe_state, history_state, history_dd]
1199
+
1200
+ spin_btn.click(
1201
+ on_spin,
1202
+ inputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps,
1203
+ guidance_scale, seed_value] + advanced + [user_id, gallery_state, history_state] + lock_boxes,
1204
+ outputs=outputs,
1205
+ )
1206
+ reroll_btn.click(
1207
+ on_reroll_history,
1208
+ inputs=[history_dd, tease_reveal, extra, size_name, steps, guidance_scale]
1209
+ + advanced + [user_id, gallery_state, history_state],
1210
+ outputs=outputs,
1211
+ )
1212
+ load_btn.click(on_load_history, inputs=[history_dd, history_state], outputs=[recipe_state, card])
1213
+ preview_btn.click(
1214
+ on_preview,
1215
+ inputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra] + lock_boxes,
1216
+ outputs=[recipe_state, card, prompt_box],
1217
+ )
1218
+ ref_image.upload(on_picture_upload, inputs=[picture_mode], outputs=[picture_mode])
1219
+ ref_image.clear(on_picture_clear, inputs=None, outputs=[picture_mode])
1220
+ art_mode.change(on_art_mode, inputs=[art_mode, style_pick], outputs=[style_pick])
1221
+ demo.load(fn=None, inputs=None, outputs=[user_id], js=js_visitor)
1222
+ return demo
1223
+
1224
+
1225
+ if __name__ == "__main__":
1226
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
1227
+ app = create_ui()
1228
+ app.queue(max_size=12)
1229
+ app.launch(ssr_mode=False)