"""Keep new phase plans/configs present when earlier publishers update cards.""" import json from pathlib import Path import shutil import sqlite3 from datasets import Value from webdataset_card_schema import attach_schema ROOT=Path(__file__).resolve().parents[1] def gate_public_base_paths(card): safety=ROOT/'experiments/minor-safety' if not (safety/'request.json').exists():return from minor_safety_gate import approved_shard c=sqlite3.connect(ROOT/'experiments/character-production/queue.sqlite');c.row_factory=sqlite3.Row fully_uploaded=c.execute("SELECT COALESCE(SUM(count),0) FROM shards WHERE status='uploaded'").fetchone()[0]==5000 if (safety/'completion.json').exists() and fully_uploaded: from background_production import dump,utc dump(safety/'public-stream-filter.json',dict(status='restored_after_completed_recheck_and_all_replacement_uploads',utc=utc(),included_base_images=5000,withheld_base_images=0)) c.close();return shards=list(c.execute("SELECT name,count,sha256 FROM shards WHERE status='uploaded' ORDER BY name")) accepted=[r for r in shards if approved_shard(c,r['name'])];c.close() paths=['data/'+r['name'] for r in accepted];assert paths,'No checked base TARs are available' for config in card['configs']: for split in config['data_files']: prior=split['path'];prior=[prior] if isinstance(prior,str) else prior if 'data/*.tar' in prior:split['path']=[p for p in prior if p!='data/*.tar']+paths from background_production import dump,utc dump(safety/'public-stream-filter.json',dict(status='active_while_repairing',utc=utc(), included_shards=len(accepted),included_base_images=sum(r['count'] for r in accepted), withheld_shards=len(shards)-len(accepted),withheld_base_images=sum(r['count'] for r in shards)-sum(r['count'] for r in accepted), included=[dict(r) for r in accepted],policy_sha256=json.loads((safety/'policy.json').read_text())['policy_sha256'])) def uploaded(phase): path=ROOT/f'experiments/{phase}/queue.sqlite' if not path.exists():return 0 c=sqlite3.connect(path);n=c.execute("SELECT COALESCE(SUM(count),0) FROM shards WHERE status='uploaded'").fetchone()[0];c.close();return n def extend(kind,card,body,base_shard): phase='job-outfits' if kind=='characters' else 'background-drama-extension' plan='image-plan.json' if kind=='characters' else 'prompt-plan.json' if not (ROOT/f'experiments/{phase}/{plan}').exists():return body name,prefix=('jobs','job-data') if kind=='characters' else ('drama','drama-data') amount=uploaded(phase) if amount: pattern=prefix+'/*.tar' card['configs']=[c for c in card['configs'] if c['config_name']!=name] default=next(c for c in card['configs'] if c['config_name']=='default') paths=default['data_files'][0]['path'];paths=[paths] if isinstance(paths,str) else list(paths) if pattern not in paths:paths.append(pattern) default['data_files'][0]['path']=paths card['configs'].append(dict(config_name=name,data_files=[dict(split='train',path=pattern)])) if kind=='characters': if not any(c['config_name']=='base' for c in card['configs']): card['configs'].append(dict(config_name='base',data_files=[dict(split='train',path='data/*.tar')])) gate_public_base_paths(card) fields=dict(record_type='string',production_phase='string',lora_scale='float64',special_class='string',special_variant='string',composition='string', job_id='string',job_key='string',profession_family='string',job_title_de='string',job_title_en='string',job_outfit='string',job_outfit_index='int64', base_outfit_id='string',base_outfit_style='string',base_outfit='string',base_description='string',reference_source_phase='string', reference_source_repo_path='string',reference_source_shard='string',reference_source_member='string',reference_source_generated_utc='string', safety_regeneration_attempt='int64',safety_regeneration_policy_sha256='string',seed_strategy='string',safety_reference_strategy='string',**{'runtime.gpu_shared_with_character_production':'bool'}) fields['safety_check']={ 'max_score':Value('float64'),'attempt':Value('int64'),'recipe_variant':Value('int64'),'utc':Value('string'),'id':Value('string'),'passed':Value('bool'), 'image_sha256':Value('string'),'policy_sha256':Value('string'),'original_screening_policy_sha256':Value('string'),'generation_seconds':Value('float64'),'screening_seconds':Value('float64'),'positive_text_encoding_seconds':Value('float64'),'retained_original':Value('bool'), 'views':{view:{'clip_nsfw':Value('float64'),'efficientnet_nsfw':Value('float64'), 'efficientnet_classes':{label:Value('float64') for label in ['drawing','hentai','neutral','porn','sexy']}} for view in ['original','foreground']}} intro=f'''\n# Complete character collection and professional outfit plan **Planned total: 840 identities, 12,140 images.** The expression/special collection contains 7,500 planned images. A further **464 adult humans × 10 professional outfits = 4,640 sprites** reuse those identities and their neutral references; they do not add new personality IDs. See [all 100 jobs and the exact outfit allocation](JOB_OUTFITS.md). Job sprites uploaded so far: **{amount:,}/4,640**. The `jobs` streaming configuration becomes available when its first TAR is uploaded. The [teen/child detector recheck](SAFETY_RECHECK.md) reports actual image checksums, both LAION classifier scores, operational thresholds and any replacements. Intended ages, professions and demographic attributes describe prompting, not inferred real-world classifications. ''' else: fields=dict(view_type='string',business_pair_id='string',narrative_genres=[Value('string')],atmosphere='string',daylight='string') intro=f'''\n# Complete environment collection and cinematic extension plan **Planned total: 1,693 backgrounds.** In addition to the original 1,093 scenes and the 400 home/city variants, a further **200 empty contemporary cinematic locations** cover shelters, mobile-home communities, under-bridge tent camps, factories/warehouses, nightclubs, parks, forests, campgrounds, beaches, hotels and liminal urban settings. See [the cinematic taxonomy and exact plan](DRAMA_LOCATIONS.md). Cinematic extension uploaded so far: **{amount}/200**. The `drama` configuration becomes available with its first TAR. ''' attach_schema(card,base_shard,fields) return intro+body def safety_documents(release): source=ROOT/'experiments/minor-safety' if not (source/'request.json').exists():return target=Path(release)/'metadata/minor-safety';target.mkdir(parents=True,exist_ok=True) for name in ['policy.json','baseline-policy.json','policy-transition.json','detector-provenance.json','progress.json','current-validation.json','completion.json','scores.jsonl','flagged.json','baseline-validation.json','baseline-scores.jsonl','baseline-classification-summary.json','replacement-audit.json','repair-quality-gate-passed.json','lora-gallery-recheck.json','lora-gallery-completion.json','public-stream-filter.json','scorer-equivalence.json','replacement-transaction-validation.json','regeneration-plan-validation.json','regeneration-variant-validation.json','candidate-checkpoint-validation.json','replacement-remote-snapshot.json','public-reference-index-validation.json','public-quarantine.json','public-quarantine-validation.json','public-replacement-stream-validation.json','difficult-case-visual-review.json','profile-recipe-overrides.json']: if (source/name).exists():shutil.copy2(source/name,target/name) snapshot=json.loads((source/'current-validation.json').read_text()) if (source/'current-validation.json').exists() else {} if (source/'policy-boundary-validation.json').exists():shutil.copy2(source/'policy-boundary-validation.json',target/'policy-boundary-validation.json') for extra in ['age19-scores.jsonl','age19-validation.json','future-teen-screening-validation.json','release-summary.json']: if (source/extra).exists():shutil.copy2(source/extra,target/extra) policy=json.loads((source/'policy.json').read_text());clip_limit=policy.get('clip_elevated_threshold',policy['elevated_threshold']);efficientnet_limit=policy.get('efficientnet_elevated_threshold',policy['elevated_threshold']) current_gate=source/f'repair-quality-gate-{policy["policy_sha256"]}.json' if current_gate.exists():shutil.copy2(current_gate,target/'current-policy-repair-quality-gate.json') audit=json.loads((source/'replacement-audit.json').read_text()) if (source/'replacement-audit.json').exists() else [] changed={ident for entry in audit for ident,digest in entry['new_image_sha256'].items() if digest!=entry['old_image_sha256'][ident]} age19=json.loads((source/'age19-validation.json').read_text()) if (source/'age19-validation.json').exists() else {} (Path(release)/'SAFETY_RECHECK.md').write_text(f'''# Teen and child classifier recheck Actually changed dataset PNGs: **{len(changed)}**, across **{len({entry['personality_id'] for entry in audit})} profiles**, including earlier stricter-filter replacements and the final seven-profile round. The [replacement audit](metadata/minor-safety/replacement-audit.json) distinguishes regenerated images from byte-identical retained expressions. A changed neutral requires a new coherent ten-expression series. The [supplemental age19 report](metadata/minor-safety/age19-validation.json) additionally covers **{age19.get('images_checked',0)} existing19-year-old sprites**:40 original-base expressions and one previously public job-outfit pilot. Status: `{age19.get('status','pending')}`; flags: **{age19.get('images_flagged',0)}**. These young-adult-labelled profiles are outside the2760-category count but inside the literal under-20 check. Future human expression and professional-outfit generations with a numerical age below20 are screened inline with both models and both views before becoming uploadable. Raised candidates automatically retry with recorded actual seeds; failed searches cannot be uploaded. The [control-flow validation](metadata/minor-safety/future-teen-screening-validation.json) tests retry exhaustion, checksum binding, thresholds and concurrent plan updates; it is separate from actual model-output measurements. Requested dataset scope: **276 identities × 10 expressions = 2,760 images**, covering babies, preschoolers, both school-age groups and both teen groups, including 18-year-olds in the older-teen category. **Six previously published child/teen model-gallery examples** are checked separately; their scores and any replacement commit are in the gallery reports. The published snapshot has checked **{snapshot.get('current_images_checked',0):,} current dataset images**; **{snapshot.get('current_images_passed',0):,} pass the operational criteria** and **{snapshot.get('current_images_flagged',0):,} require further processing**. This is an ongoing snapshot unless the linked completion report explicitly says complete. The exact [policy](metadata/minor-safety/policy.json), [detector provenance](metadata/minor-safety/detector-provenance.json), [per-image scores](metadata/minor-safety/scores.jsonl) and [current validation](metadata/minor-safety/current-validation.json) are checksum-specific. They identify the actual PNG bytes, not only filenames. Already-public TAR contents are matched to their remote SHA256 and byte size before scoring the identical local images. Two official LAION image models are used: the [CLIP ViT-L/14 binary classifier](https://github.com/LAION-AI/CLIP-based-NSFW-Detector) and the [LAION-SAFETY EfficientNetV2 B2 classifier](https://github.com/LAION-AI/LAION-SAFETY). The latter's drawing/neutral classes are SFW; its hentai/porn/sexy softmax scores are summed for the NSFW score. Each model sees the original portrait and a foreground crop fitted into a neutral square. CLIP uses L2-normalized projected OpenAI ViT-L/14 image embeddings; EfficientNet uses RGB0–1 and its documented260-pixel image input. The active additional operational thresholds are **CLIP ≥{clip_limit:.2f} or EfficientNet NSFW sum ≥{efficientnet_limit:.2f} in either view**. Ordinary positive classifier outputs are included by these conservative cutoffs; outputs at least0.50 are also recorded separately as positive. These additional thresholds are project criteria, not documented guarantees or a calibration for this illustrated domain. A flagged score does not establish that an image depicts sexual content. Model scores can produce false positives and false negatives. The [baseline class-output analysis](metadata/minor-safety/baseline-classification-summary.json) separates these additional project flags from the models' ordinary classifications. Across all2,760 original images and both views, EfficientNet's highest-scoring class is always SFW:5,406 drawing views and114 neutral views, with no hentai/porn/sexy top labels. The maximum CLIP NSFW output is0.0545109. Thus all original top-label/binary classifications are SFW; the1,662 flags come from the extra0.10 sum threshold. This illustrated-domain sensitivity is an observed limitation, not evidence of1,662 sexual images. The original stricter0.10 policy is preserved in the [baseline policy](metadata/minor-safety/baseline-policy.json). The [declared transition](metadata/minor-safety/policy-transition.json) documents the implementation judgment behind separate cutoffs after the optional threshold-preference question; no user-selected answer was inferred. Under the0.10 CLIP/0.30 EfficientNet rule,37 original images from seven identities receive additional precautionary regeneration. Saved raw detector outputs are reevaluated against the new criteria without changing pixels or model weights; historical original scores remain preserved. Earlier0.10-screened replacements remain valid under the new rule. The six model-gallery examples already passed the stricter0.10 check. New teen/child TARs are held until the exact image checksums pass. During repair the default/base Datasets configurations whitelist already-uploaded, checksum-approved original TARs; entire flagged TARs are temporarily omitted. The [stream-filter snapshot](metadata/minor-safety/public-stream-filter.json) records that reduced subset. Previously published TARs with unresolved flags have also been temporarily removed from current main, as recorded in the [public quarantine audit](metadata/minor-safety/public-quarantine.json); old Git revisions remain historical versions. Screened replacements return under the same TAR names. The complete500-person plan remains the target, not a claim about this temporarily filtered stream. Full wildcard streaming is restored after the recheck and all replacement uploads complete. Replacements use fully covered, age-appropriate opaque clothing and are checked again. If a neutral reference changes, all ten emotions are regenerated against the new reference. When the original neutral already passes, its exact pixels and other passing expressions are normally retained; only flagged expressions are regenerated against that same neutral. Difficult cases may instead receive a coherent fully covering outfit variant for the entire ten-image family, recorded in the [recipe overrides](metadata/minor-safety/profile-recipe-overrides.json). Every released group still has ten passing expressions. Published replacement audits distinguish changed and retained PNG hashes, parameters and the corresponding TAR changes. Individual image assets remain inside TARs. New neutral-reference searches prefer scores below{policy.get('neutral_preference_threshold',.07):.2f} to leave room for later expression edits. Within a16-candidate search, the best neutral that meets both active model/view criteria can also be used. Already accepted candidate PNGs are checkpointed with exact prompt, seed and reference linkage. New families generated under the active policy additionally wait for a policy-specific visual review gate before upload. Full PNG/TAR integrity validation and anonymous reference-index checks are separate from classifier judgments. ''')