scripts/render_documentation.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/render_documentation.py · SHA-256: f458f2ce4138aab1…
line=' - **Locus 1:** Arm 1A bicistronic HLA-E-SCT-GSG-P2A-CD47-IgV-GPI is the nonviral comparator; Arm 1B has antisense constitutive EEF1A1-to-CD47 and sense inducible 5xISRE-to-HLA-E. '+DELIVERY+' Exact edited beta/alpha/delta/iEC densities remain unmeasured; QuantiBRITE, matched immune killing and GSIS are preregistered Stage-0 acceptance targets.'
# Bind named ranking summaries and table values to the current named architecture.
for arch in facts['layer1']['ranked_architectures']:
aid=arch['architecture_id']
if aid not in original: continue
if original.startswith('|') and ranking_columns is not None:
columns=_table_cells(line)
if len(columns) != table_width:
raise ValueError('Ranking row width differs from its header')
pediatric=arch['utility_pediatric_early_onset_t1d'];adult=arch['utility_adult_onset_lada']
values={'pediatric':pediatric['series_system_joint_survival_probability'],
'adult':adult['series_system_joint_survival_probability'],
'composite':arch.get('composite_series_system_utility')}
for key,value in values.items():
index=ranking_columns[key]
if index is None: continue
floor=pediatric.get('heuristic_conservative_floor_index') if key=='pediatric' else None
columns[index]=_score_cell(columns[index],value,floor)
if ranking_columns['rank'] is not None:
columns[ranking_columns['rank']]=f" **`#{arch['global_rank_among_all_combinations']} / {facts['layer1']['audit_ledger'].get('search',{}).get('all_stacks')}`** "
if ranking_columns['discount'] is not None:
index=ranking_columns['discount'];columns[index]=_score_cell(columns[index],pediatric.get('manufacturing_locus_penalty_factor'))
if ranking_columns['limiting'] is not None:
columns[ranking_columns['limiting']]=str(pediatric.get('limiting_bottleneck_gate'))+' ('+f(pediatric.get('limiting_bottleneck_score'),4)+')'
if aid.startswith('ISLET1_CHASSIS_B') and ranking_columns['specification'] is not None:
index=ranking_columns['specification']
columns[index]=columns[index].split(' Scenario-B scope:')[0]+' Scenario-B scope: unmaterialized six-locus research comparator; exact 2A-free donor/function unavailable. '
line='|'.join(columns)
elif ('Scenario Output' in original or 'Reference Profile' in original or 'current global rank #' in original) and original.lstrip().startswith(('1.','2.','-')):
line=f"- **`{aid}`**: current global rank #{arch['global_rank_among_all_combinations']}, K={arch['genomic_locus_edit_count_K']}, B={arch['base_edit_count_B']}; composite prior-anchored index {f(arch.get('composite_series_system_utility'),4)}. Physical qualification remains pending."
if original.startswith('|') and (not line.startswith('|') or len(_table_cells(line))!=len(_table_cells(original))):
raise ValueError('A document substitution would corrupt an authored table row')
output.append(line)
text='\n'.join(output).strip()+'\n'
# Keep old study-design details, but correct active row-allocation and stale counts.
text=re.sub(r'column sums \$\+2\$ on.*?\$-6\$ on `X5`', 'column sums from the current machine run table '+str(list(facts['layer1']['protocol'].get('column_sums_across_36_runs_by_factor',{}).values())),text)
text=re.sub(r'`[\d,]+`(?= pinned files)', '`'+f"{facts['manifest_pin_count']:,}"+'`',text)
text=re.sub(r'`(?:233|312)`(?=\s+(?:edit|expanded|gene-symbol))',lambda m:'`'+str(facts['corpus']['raw_edit_entries'] if m.group(0)=='`233`' else facts['corpus'].get('expanded_gene_occurrences'))+'`',text)
# A generated footer may itself contain a protected source link. Inspect a
# read-only expanded view for presence, without exposing URLs to edits.
presence_text=text
for key,value in reversed(protected_links):
presence_text=presence_text.replace(key,value)
if 'Shy' in text and DELIVERY not in text: text+='\n'+DELIVERY+'\n'
if 'RNLS' in text and RNLS not in text: text+='\n'+RNLS+'\n'
if 'cHS4' in text and CHS4 not in text: text+='\nCurrent cHS4 provenance: '+CHS4+'. Earlier 217-bp U78775.1 descriptions are superseded accession matches.\n'
if '356k' in text and STATUTE not in presence_text: text+='\n'+STATUTE+'\n'
if 'single 22-aa GSG-P2A' not in text and ('P2A' in text or 'tPT2A' in text): text+='\nCurrent encoded element: '+P2A+'. SCT encodes B2M signal MSRSVALAVLALLSLSGLEA (20 aa); ER cleavage and mature N-terminus remain processing assay gates.\n'
if 'CGBE1' in text: text=text.replace('or `CGBE1` for', '(CGBE1 is an unimplemented contingency, with no qualified guide) for')
# A single generated scope paragraph is present in each current companion document.
# Only an ATX heading can be split safely after one line. In particular a
# setext underline belongs to its preceding paragraph, including multiple
# heading lines; prepend generated blocks when there is no ATX heading.
no_header=re.match(r'^ {0,3}#{1,6}(?:[ \t]+|$)',text.partition('\n')[0]) is None
scope='\n<!-- OPENISLET_CURRENT_LAYER_SCOPE -->\n'+n['layer2']+'\n\n'+n['layer3']+'\n\n'+n['layer4']+'\n\n'+n['layer5']+'\n<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->\n'
# An unclosed authored fence consumes the rest of a Markdown document.
# Put generated scope before it so re-renders never trap generated blocks
# inside an authored literal and append a second copy on each invocation.
if unclosed_key is not None:text=text.replace(unclosed_key,scope+'\n'+unclosed_key,1)
else:text+=scope
if no_header:first,rest='',text
else:first,sep,rest=text.partition('\n')
historical_names = {'ISLET-1-MASTER-SPEC-v0.1.md',
'ISLET-1-CANDIDATE-BLUEPRINTS-AND-OPTIMIZER-v0.2.md',
'ISLET-1-SYNTHESIS-REPORT-v0.4.md',
'PROJECT-ISLET-1-RING1-DISCOVERY-ATLAS-AND-STRATEGY.md'}
historical_notice = '> **Earlier-revision rationale:** The body originated in an earlier design revision and retains historical reasoning. Unrendered historical values are not current release claims; the generated facts above and current machine-readable artifacts govern active numerical outputs.'
rest=rest.replace(historical_notice+'\n\n','')
if filename in historical_names:
rest=historical_notice+'\n\n'+rest.lstrip()
rendered=(first+'\n\n' if first else '')+facts_block(facts)+'\n\n'+rest.lstrip()
if fences or protected_links:
# Restore after every prose/count substitution. Later protected syntax
# may contain an earlier token (e.g. HTML inside a link title), so unwind
# in reverse creation order. The prefix was absent from authored input.
for key,value in reversed(fences+protected_links):
if rendered.count(key)!=1:
raise ValueError('Authored literal rendering lost unique placeholder provenance')
rendered=rendered.replace(key,value)
if literal_prefix in rendered:raise ValueError('Unrestored authored literal rendering marker')
return rendered
def _publish_document_batch(prepared,rollback_journal=None):
try:from .study_artifact_exports import publish_byte_artifacts
except ImportError:from study_artifact_exports import publish_byte_artifacts
publish_byte_artifacts({path:text.encode('utf-8') for path,text in prepared.items()},rollback_journal=rollback_journal)
def write_documentation(root: Path | str, manifest_pin_count: int, render: bool = True, *, rollback_journal=None) -> dict:
root=Path(root)
_safe_location(root)
if isinstance(manifest_pin_count,bool) or not isinstance(manifest_pin_count,int) or manifest_pin_count<0: raise ValueError('manifest_pin_count must be a nonnegative integer')
if type(render) is not bool:raise ValueError('render must be boolean')
try:from .study_artifact_exports import PublicationLease
except ImportError:from study_artifact_exports import PublicationLease
with PublicationLease(root/'.openislet-documentation.lock') as lease:
return _write_documentation_locked(root,manifest_pin_count,render,lease,rollback_journal)
def _write_documentation_locked(root,manifest_pin_count,render,lease=None,rollback_journal=None):
facts=derive_facts(root,manifest_pin_count)
target=root/'data/extracted/documentation_facts_v0.8.0.json'
prepared={target:json.dumps(facts,indent=2,ensure_ascii=False,allow_nan=False)+'\n'}
if render:
doc_candidates = [root/'README.md', root/'CLAUDE.md', root/'ISLET-1-BLUEPRINT.md', *sorted((root/'docs').glob('*.md'))]
for path in [p for p in doc_candidates if p.exists()]:
if path.name in RENDER_EXEMPT_DOCS:
text=_read_regular(path).decode('utf-8')
text=re.sub(r'[\d,]+(?= atomic effects)',f"{facts['corpus']['atomic_effects']:,}",text)
text=re.sub(r'`[\d,]+`(?= pinned files)', '`'+f"{manifest_pin_count:,}"+'`', text)
prepared[path]=text
continue
text=_read_regular(path).decode('utf-8')
prepared[path]=render_text(text,facts,path.name)
for relative,digest in facts.get('source_sha256',{}).items():
if hashlib.sha256(_read_regular(root/relative)).hexdigest()!=digest:
raise ValueError('A source changed during documentation rendering')
if lease is not None:lease.require_owned()
_publish_document_batch(prepared,rollback_journal=rollback_journal)
if lease is not None:lease.require_owned()
return facts
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);parser.add_argument('--manifest-pin-count',type=int,required=True);parser.add_argument('--facts-only',action='store_true');args=parser.parse_args()
write_documentation(args.root,args.manifest_pin_count,not args.facts_only)