Vivarium-Greenscreen-Characters-FLUX-9B / tools /plan_character_production.py
ChristophSchuhmann's picture
Document 500 planned people, ten reference expressions and WebDataset inference
9bc4c0e verified
Raw History Blame
12.7 kB
"""500 fully clothed fictional identities, eleven age groups, ten expressions."""
from collections import Counter
import hashlib
import json
from pathlib import Path
import random
from vivarium_prompt_templates import CHARACTER_STYLE, CHARACTER_PROMPT_TEMPLATE
ROOT=Path(__file__).resolve().parents[1]
STATE=ROOT/'experiments/character-production'
AGES=[('baby',0,2),('preschool',3,5),('younger_schoolchild',6,8),('older_schoolchild',9,12),
('younger_teen',13,15),('older_teen',16,18),('young_adult',19,29),('middle_adult',30,49),
('older_adult',50,64),('younger_senior',65,79),('older_senior',80,95)]
EMOTIONS=[('neutral','a relaxed neutral expression with a slight friendly smile'),
('joyful','natural joy: an open smiling mouth, raised cheeks and bright happy eyes'),
('grateful','warm gratitude: a gentle closed-mouth appreciative smile and softly relaxed eyelids'),
('playful','gentle playfulness: a small lopsided mischievous grin and one eyebrow slightly raised'),
('angry','mild controlled anger: eyebrows drawn inward and lowered, lips firmly pressed together'),
('afraid','mild apprehension: raised inner eyebrows, slightly widened eyes and gently parted lips'),
('sad','quiet mild sadness: raised inner eyebrows, softly sad eyes and downturned mouth corners'),
('annoyed','mild annoyance: partly lowered eyelids, one brow lowered and a faint flat line of the lips'),
('pain','brief mild discomfort: a slight wince, gently narrowed eyes and compressed lips, with no visible injury'),
('disgust','mild distaste: a slight nose wrinkle, subtly raised upper lip and asymmetric downturned mouth')]
ETHNICITIES=[('white_caucasian','white European-ancestry', ['fair','light warm','light olive']),
('african_american','African-American',['medium brown','deep brown','dark brown']),
('arab','Arab',['light olive','warm tan','medium brown']),
('latino','Latino',['light tan','warm medium brown','olive']),
('indian','Indian',['warm brown','medium brown','deep brown']),
('japanese','Japanese',['light warm','medium light','light tan']),
('southeast_asian','Southeast Asian',['warm tan','medium brown','light golden brown']),
('indigenous_american','Indigenous American',['warm tan','medium brown','light brown'])]
HAIR_M=['neatly cropped straight hair','short naturally curly hair','soft wavy hair swept to one side',
'close-cropped textured hair','short tousled hair','a tidy side-part hairstyle']
HAIR_F=['a short practical bob','shoulder-length naturally wavy hair','a neatly tied ponytail',
'short naturally curly hair','a loose braid over one shoulder','a cropped textured hairstyle']
COLORS=['navy','burgundy','rust red','ochre','cream','plum','brown','charcoal','royal blue','soft lavender']
def seed(text):return int.from_bytes(hashlib.sha256(('vivarium-people-2026-10-06:'+text).encode()).digest()[:4],'big')
def write(path,value):
path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value,indent=2,ensure_ascii=False)+'\n')
def outfit(age,gender,rng,serial):
color=rng.choice(COLORS)
if age<=2:
options=[('baby_everyday',f'a fully covering {color} cotton romper with long sleeves and soft booties'),
('baby_layers',f'a {color} knitted cardigan over a cream long-sleeved top, soft trousers and booties'),
('baby_sporty',f'a {color} long-sleeved sweatshirt, loose cotton trousers and soft socks')]
elif age<=12:
options=[('child_sporty',f'a {color} sweatshirt, loose navy joggers and closed sneakers'),
('child_everyday',f'a {color} cardigan over a cream T-shirt, comfortable brown trousers and closed shoes'),
('child_outdoors',f'a {color} zip jacket, full-length charcoal trousers and sturdy closed shoes'),
('child_school',f'a {color} cardigan over a white collared shirt, navy school trousers and closed shoes'),
('child_creative',f'a {color} long-sleeved shirt, brown cotton dungarees and closed canvas shoes'),
('child_formal',f'a {color} buttoned cardigan, cream collared shirt, full-length navy trousers and neat closed shoes')]
else:
options=[('sporty',f'a {color} sweatshirt, loose navy athletic trousers and closed sneakers'),
('casual_layers',f'a {color} cardigan over a cream crew-neck top, brown trousers and closed shoes'),
('outdoors',f'a {color} practical jacket, charcoal hiking trousers and closed walking shoes'),
('smart_casual',f'a {color} collared shirt under a cream cardigan, navy trousers and neat closed shoes'),
('formal',f'a {color} tailored jacket over a cream buttoned shirt, matching full-length trousers and closed dress shoes'),
('workwear',f'a {color} long-sleeved work shirt, practical brown carpenter trousers and closed work boots'),
('rock_inspired',f'a dark {color} denim jacket over a cream crew-neck T-shirt, loose dark trousers and closed boots'),
('crafts',f'a {color} cotton overshirt over a cream top, navy canvas trousers and closed shoes'),
('simple_everyday',f'a {color} knitted pullover, full-length brown trousers and plain closed shoes')]
if gender=='female':
options+=[('everyday_dress',f'a {color} long-sleeved knee-length day dress over opaque dark leggings with closed shoes'),
('formal_skirt',f'a {color} buttoned jacket, a cream high-neck blouse, a knee-length skirt over opaque leggings and closed shoes')]
kind,clothes=options[serial%len(options)]
return kind,clothes
def description(person):
age=person['age_years'];gender=person['gender'];eth=person['ethnicity_prompt_label'];skin=person['skin_tone']
if person['age_group']=='baby':
subject=f"one fictional {person['age_months']}-month-old baby {'boy' if gender=='male' else 'girl'}"
anatomy='natural infant proportions, a softly rounded face and gentle proportionate eyes'
elif age<13:
subject=f"one fictional {age}-year-old {'boy' if gender=='male' else 'girl'}"
anatomy='natural school-child proportions, modest almond-shaped eyes, a proportionate head and restrained facial features' if age>=6 else 'natural preschool-child proportions and restrained facial features'
elif age<16:
subject=f"one fictional {age}-year-old {'boy' if gender=='male' else 'girl'}, an early adolescent"
anatomy='natural adolescent proportions, modest almond-shaped eyes and a proportionate head'
elif age<=18:
subject=f"one fictional mature-looking {age}-year-old {'young man' if gender=='male' else 'young woman'}, a late adolescent"
anatomy='a near-adult elongated oval face, modest almond-shaped eyes, a subtly defined jaw, a proportionate head and long adolescent limbs'
else:
subject=f"one fictional {age}-year-old {'man' if gender=='male' else 'woman'}"
anatomy='natural adult proportions and a proportionate face'
if age>=50:anatomy+=', age-appropriate facial lines'
if age>=65:anatomy+=', clearly visible natural wrinkles'
return f"{subject}, {eth} heritage, {skin} skin, {person['hair']}, {person['build']}, wearing {person['outfit']}, fully clothed and age-appropriate. {anatomy}"
def prompt(person,emotion,reference=False):
expression=dict(EMOTIONS)[emotion]
text=CHARACTER_PROMPT_TEMPLATE.format(description=description(person),style=CHARACTER_STYLE)
text=text.replace('Calm friendly expression, facing the viewer.',f'{expression.capitalize()}, facing the viewer.')
if person['age_group']=='baby':
text=text.replace('Standing three-quarter portrait, head to thighs, hands and shoulders inside the frame, margin around the silhouette.',
'Sitting upright in a safe natural infant posture, entire clothed body inside the frame with a margin around the silhouette.')
if reference:
age=f"{person['age_months']}-month-old baby" if person['age_group']=='baby' else f"{person['age_years']}-year-old person"
text=(f'vvar_char, edit the reference portrait. Make this exact same fictional {age} show {expression}. '
'Change the mouth, eyebrows and eyelids so this mild natural emotion is clearly visible. '
'Preserve exact identity, face shape, skin tone, hair, clothing, pose and framing. '
f'{CHARACTER_STYLE} Fully clothed, age-appropriate. Perfectly uniform solid bright chroma green background. '
'No scenery, no text, no logo, no watermark.')
return text
def main():
other_index=0;persons=[]
# Eight cells get24people; the other14cells get22: total500.
priority={'older_schoolchild','younger_teen','older_teen','young_adult'}
for group,low,high in AGES:
for gender in ['male','female']:
count=24 if group in priority else 22
for j in range(count):
ident=f'person-{len(persons)+1:04d}';rng=random.Random(seed(ident))
if j%2==0:eth=ETHNICITIES[0]
else:eth=ETHNICITIES[1+other_index%7];other_index+=1
age=rng.randint(max(low,1),high)
months=rng.choice([9,12,15,18,21,24]) if group=='baby' else 0
if group=='baby':age=months//12
hair_color=rng.choice(['dark brown','black','medium brown','chestnut'])
if eth[0]=='white_caucasian':hair_color=rng.choice(['dark brown','light brown','blond','auburn','black'])
if age>=65:hair_color=rng.choice(['silver','white','gray'])
elif age>=50:hair_color+=' with natural gray strands'
style=rng.choice(HAIR_M if gender=='male' else HAIR_F)
hair=f'{hair_color} {style}'
if group=='baby':hair=f'soft sparse {hair_color} baby hair'
body=rng.choice(['a slim build','an average build','a sturdy build','a compact build']) if age>=16 else 'a natural age-appropriate build'
style_id,clothes=outfit(age,gender,rng,j)
p=dict(personality_id=ident,character_id=ident,age_group=group,age_years=age,age_months=months,
gender=gender,ethnicity=eth[0],ethnicity_prompt_label=eth[1],skin_tone=rng.choice(eth[2]),hair=hair,
build=body,outfit_id='outfit-01',outfit_style=style_id,outfit=clothes,seed=seed(ident),default_emotion='neutral')
p['description']=description(p);persons.append(p)
assert len(persons)==500
assert Counter(p['gender'] for p in persons)==dict(male=250,female=250)
assert sum(p['ethnicity']=='white_caucasian' for p in persons)==250
jobs=[]
for p in persons:
negative='extra people, changed clothing, different hairstyle, exaggerated expression, text, logo, watermark, background scenery'
if p['age_years']>=6:negative+=', oversized doll eyes, chibi proportions'
expressions=[dict(id=p['personality_id']+'-'+e,emotion=e,prompt=prompt(p,e,e!='neutral'),negative_prompt=negative if e=='neutral' else negative.replace('exaggerated expression, ',''),
seed=p['seed'],reference_id='' if e=='neutral' else p['personality_id']+'-neutral') for e,cue in EMOTIONS]
jobs.append(dict(**p,expressions=expressions))
assert len({j['id'] for p in jobs for j in p['expressions']})==5000
write(STATE/'person-plan.json',jobs)
write(STATE/'planning/allocation.json',dict(persons=500,images=5000,emotions_per_person=10,
by_age_and_gender={f'{a}/{g}':sum(p['age_group']==a and p['gender']==g for p in persons) for a,l,h in AGES for g in ['male','female']},
ethnicity_counts=dict(Counter(p['ethnicity'] for p in persons)),gender_counts=dict(Counter(p['gender'] for p in persons)),
race_labels_are_prompt_attributes=True,ethnicity_not_inferred_from_appearance=True,
default_emotion='neutral',reference_policy='Neutral image reused for9 expression edits; same seeded noise per identity',
reference_width=416,reference_height=624,output_width=832,output_height=1248,steps=50,cfg=4.0))
write(STATE/'planning/taxonomy.json',dict(age_groups=[dict(id=a,min_age=l,max_age=h) for a,l,h in AGES],
emotions=[dict(id=e,expression=v) for e,v in EMOTIONS],ethnicity_groups=[dict(id=e,prompt_label=v) for e,v,s in ETHNICITIES],
default_emotion='neutral',minor_policy='Fully clothed,age-appropriate everyday outfits; mild platonic expressions',
baby_pose='Safely seated upright,full body visible; actual sampled infant ages9–24months',
school_child_pose='Standing head-to-thigh portrait; modest natural facial proportions'))
print(json.dumps(json.loads((STATE/'planning/allocation.json').read_text()),indent=2))
if __name__=='__main__':main()