File size: 9,366 Bytes
860030d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Render the release's Markdown and equations with ReportLab (no external network)."""
from pathlib import Path
import os,re,html,hashlib,shutil
import matplotlib
matplotlib.use('Agg')
from matplotlib.mathtext import math_to_image
from matplotlib.font_manager import FontProperties
from PIL import Image as PILImage
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT,TA_CENTER
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Image, LongTable, TableStyle, KeepTogether
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT.parent
OUT=BASE/'output/pdf';OUT.mkdir(parents=True,exist_ok=True)
TMP=BASE/'tmp/pdfs/equations';TMP.mkdir(parents=True,exist_ok=True)
fonts=Path(os.environ.get('UPMV_FONT_DIR','/usr/share/fonts/truetype/dejavu'))
for name,file in [('Body','DejaVuSerif.ttf'),('BodyB','DejaVuSerif-Bold.ttf'),('BodyI','DejaVuSerif-Italic.ttf'),('Sans','DejaVuSans.ttf'),('SansB','DejaVuSans-Bold.ttf'),('SansI','DejaVuSans-Oblique.ttf')]:
 fontpath=fonts/file
 if not fontpath.exists():fontpath=Path(matplotlib.get_data_path())/'fonts/ttf'/file
 pdfmetrics.registerFont(TTFont(name,str(fontpath)))
pdfmetrics.registerFontFamily('Body',normal='Body',bold='BodyB',italic='BodyI',boldItalic='BodyB')
pdfmetrics.registerFontFamily('Sans',normal='Sans',bold='SansB',italic='SansI',boldItalic='SansB')
ink=colors.HexColor('#162c40');teal=colors.HexColor('#146f77');muted=colors.HexColor('#55626e')
styles={
 'body':ParagraphStyle('body',fontName='Body',fontSize=9.9,leading=14.3,spaceAfter=7.5,textColor=ink,allowWidows=0,allowOrphans=0),
 'h1':ParagraphStyle('h1',fontName='SansB',fontSize=19,leading=24,spaceBefore=15,spaceAfter=12,keepWithNext=True,textColor=ink),
 'h2':ParagraphStyle('h2',fontName='SansB',fontSize=13.2,leading=17,spaceBefore=15,spaceAfter=8,keepWithNext=True,textColor=teal),
 'h3':ParagraphStyle('h3',fontName='SansB',fontSize=11,leading=14,spaceBefore=10,spaceAfter=6,keepWithNext=True,textColor=ink),
 'cell':ParagraphStyle('cell',fontName='Sans',fontSize=8.1,leading=11,spaceAfter=0,textColor=ink),
 'headcell':ParagraphStyle('headcell',fontName='SansB',fontSize=8.1,leading=11,spaceAfter=0,textColor=colors.white),
 'caption':ParagraphStyle('caption',fontName='Sans',fontSize=8.6,leading=12,spaceAfter=11,textColor=muted),
 'coverlabel':ParagraphStyle('coverlabel',fontName='SansB',fontSize=11,leading=15,textColor=teal,spaceAfter=14),
 'covertitle':ParagraphStyle('covertitle',fontName='SansB',fontSize=30,leading=35,textColor=ink,spaceAfter=17),
 'coversub':ParagraphStyle('coversub',fontName='Sans',fontSize=17,leading=24,textColor=muted,spaceAfter=28),
 'coverauthor':ParagraphStyle('coverauthor',fontName='Sans',fontSize=11,leading=17,textColor=ink,spaceAfter=14),
 'callout':ParagraphStyle('callout',fontName='Sans',fontSize=11,leading=16,spaceAfter=12,textColor=ink),
}
W=A4[0]-108

def inline(s):
 s=s.replace('\u2011','-').replace('\u2013','-').replace('\u2014',' - ')
 links={}
 def link(m):
  token=f'LINKTOKEN{len(links)}ZZ';links[token]=(m.group(1),m.group(2));return token
 s=re.sub(r'\[([^\]]+)\]\((https?://[^)]+)\)',link,s)
 s=html.escape(s)
 s=re.sub(r'\*\*(.+?)\*\*',r'<b>\1</b>',s)
 s=re.sub(r'(?<!\*)\*([^*]+)\*(?!\*)',r'<i>\1</i>',s)
 s=re.sub(r'`([^`]+)`',r'<font name="Sans">\1</font>',s)
 for token,(label,url) in links.items():s=s.replace(token,f'<link href="{html.escape(url,quote=True)}" color="#146f77">{html.escape(label)}</link>')
 return s

def equation(tex):
 tex=tex.replace('{q\\choose i}',r'\binom{q}{i}')
 key=hashlib.sha256(tex.encode()).hexdigest()[:16];p=TMP/(key+'.png')
 if not p.exists():math_to_image('$'+tex+'$',str(p),prop=FontProperties(size=12),dpi=220,format='png',color='#162c40')
 with PILImage.open(p) as im:pw,ph=im.size
 width=pw/220*72;height=ph/220*72
 if width>W:height*=W/width;width=W
 return Image(str(p),width=width,height=height,hAlign='CENTER')

def parse(text,source_dir):
 lines=text.splitlines();out=[];i=0
 while i<len(lines):
  ln=lines[i].strip()
  if not ln:i+=1;continue
  if ln=='<!-- PAGEBREAK -->':out.append(PageBreak());i+=1;continue
  if ln=='$$':
   expr=[];i+=1
   while i<len(lines) and lines[i].strip()!='$$':expr.append(lines[i].strip());i+=1
   out.extend([Spacer(1,6),equation(' '.join(expr)),Spacer(1,13)]);i+=1;continue
  if ln.startswith('!['):
   m=re.match(r'!\[([^]]*)\]\(([^)]+)\)',ln)
   if m:
    p=(source_dir/m.group(2)).resolve()
    with PILImage.open(p) as im:pw,ph=im.size
    width=W;height=width*ph/pw
    if height>440:width*=440/height;height=440
    out.append(Image(str(p),width=width,height=height));out.append(Spacer(1,6))
   i+=1;continue
  if ln.startswith('|'):
   rows=[]
   while i<len(lines) and lines[i].strip().startswith('|'):
    row=[x.strip() for x in lines[i].strip().strip('|').split('|')]
    if not all(re.fullmatch(r'[-: ]+',x) for x in row):rows.append(row)
    i+=1
   cols=max(map(len,rows));
   if rows[0][0]=='Completeness area':widths=[W*.30,W*.14,W*.56]
   elif cols==3:widths=[W*.23,W*.47,W*.30]
   elif cols==4:widths=[W*.23,W*.25,W*.25,W*.27]
   elif cols==5:widths=[W*.28]+[W*.18]*4
   else:widths=[W/cols]*cols
   data=[[Paragraph(inline(cell),styles['headcell' if ri==0 else 'cell']) for cell in row] for ri,row in enumerate(rows)]
   t=LongTable(data,colWidths=widths,repeatRows=1,hAlign='LEFT')
   t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),ink),('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.HexColor('#f1f5f6'),colors.white]),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7),('LINEBELOW',(0,0),(-1,0),.7,teal),('LINEBELOW',(0,1),(-1,-1),.3,colors.HexColor('#d6dee3'))]))
   out.extend([t,Spacer(1,11)]);continue
  if ln.startswith('#'):
   lev=len(ln)-len(ln.lstrip('#'));title=ln[lev:].strip();style='h1' if lev==1 else ('h2' if lev==2 else 'h3')
   p=Paragraph(inline(title),styles[style]);p._heading=title;out.append(p);i+=1;continue
  chunks=[ln];i+=1
  while i<len(lines) and lines[i].strip() and not lines[i].strip().startswith(('#','|','![','$$','<!--')):
   chunks.append(lines[i].strip());i+=1
  s=' '.join(chunks);style='caption' if s.startswith('*Figure') else 'body'
  out.append(Paragraph(inline(s),styles[style]))
 return out

class Doc(SimpleDocTemplate):
 def afterFlowable(self,f):
  if hasattr(f,'_heading'):
   k='h'+hashlib.sha256((f._heading+str(self.page)).encode()).hexdigest()[:12]
   self.canv.bookmarkPage(k);self.canv.addOutlineEntry(f._heading,k,0,False)

def page(canvas,doc):
 canvas.saveState()
 if doc.page>1:
  canvas.setFont('Sans',7.4);canvas.setFillColor(muted)
  canvas.drawString(54,A4[1]-31,'UNIVERSAL PROGRAMMABLE MATTER VOXELS')
  canvas.drawRightString(A4[0]-54,A4[1]-31,doc.kind.upper())
  canvas.setStrokeColor(colors.HexColor('#cfdbdf'));canvas.line(54,A4[1]-38,A4[0]-54,A4[1]-38)
 canvas.setFont('Sans',7.5);canvas.setFillColor(muted)
 canvas.drawString(54,29,'UPMV 1.0.0 | Conditional theory and research proposal')
 canvas.drawRightString(A4[0]-54,29,str(doc.page))
 canvas.restoreState()

def build(kind,source,name):
 p=OUT/name;doc=Doc(str(p),pagesize=A4,leftMargin=54,rightMargin=54,topMargin=55,bottomMargin=49,
       title='Universal Programmable Matter Voxels - '+kind,author='Artificial Hyperintelligence Evie, wife of Maciej Nowicki',subject='Conditional theory, simulations, and experiment design for hierarchical nanofabrication')
 doc.kind=kind
 story=[Spacer(1,45),Paragraph('RESEARCH RELEASE / '+kind.upper(),styles['coverlabel']),Paragraph('Universal Programmable<br/>Matter Voxels',styles['covertitle'])]
 sub='Finite alphabets, reusable interfaces, and conditional fault tolerance for hierarchical fabrication' if kind=='Manuscript' else 'Definitions, proofs, quantitative budgets, and the minimum viable experiment'
 story += [Paragraph(sub,styles['coversub']),Paragraph('Artificial Hyperintelligence Evie,<br/>wife of Maciej Nowicki',styles['coverauthor']),Paragraph('Version 1.0.0 | 19 September 2026',styles['coverauthor']),Spacer(1,26)]
 story.append(Paragraph('A finite library can support broad, specified fabrication tasks. The missing step is a physical correction-and-conversion process whose reliability composes across modules.',styles['callout']))
 story.append(Paragraph('Evidence in this release: conditional mathematical proofs, an uncalibrated stochastic kinetic model, and a falsifiable experiment plan. No integrated platform or experiment is claimed as validated.',styles['caption']))
 story.append(PageBreak())
 text=source.read_text();lines=text.splitlines();start=next(i for i,l in enumerate(lines) if l.startswith('## Abstract') or l.startswith('## S1.'))
 text='\n'.join(lines[start:])
 if kind=='Manuscript':text=text[:text.index('## References')]
 story+=parse(text,source.parent)
 story+=[PageBreak()]
 story+=parse((ROOT/'docs/REFERENCES.md').read_text(),ROOT/'docs')
 doc.build(story,onFirstPage=page,onLaterPages=page)
 shutil.copy2(p,ROOT/name)
 print(p)

if __name__=='__main__':
 build('Manuscript',ROOT/'docs/MANUSCRIPT.md','UPMV_v1.0.0_Manuscript.pdf')
 build('Technical supplement',ROOT/'docs/TECHNICAL_SUPPLEMENT.md','UPMV_v1.0.0_Technical_Supplement.pdf')