Files
CloudLab Deploy 4c312cac39
CloudLab CI/CD / 门禁 doctor (push) Failing after 38s
CloudLab CI/CD / 单元测试 (push) Skipped
CloudLab CI/CD / 归档完整性 (push) Skipped
CloudLab CI/CD / 构建站点与归档 (push) Skipped
CloudLab CI/CD / 部署到 lab.hdtime.space(rsync) (push) Skipped
CloudLab CI/CD / 构建镜像并推送 Gitea 容器仓库 (push) Skipped
CloudLab CI/CD / 容器部署到 lab.hdtime.space (push) Skipped
CloudLab CI/CD / 发布版本(Tag) (push) Skipped
feat(platform): add CloudLab execution platform and IDE web source
Freeze the real-execution control plane, runner, manifests, validation cases and tests under cloudlab-platform; preserve the IDE/static web source under cloudlab-web. Generated material library and runtime state are intentionally excluded.
2026-11-18 00:14:35 +08:00

214 lines
10 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generate the CloudLab app data layer from a built site directory."""
import json, os, re, sys, hashlib, shutil, urllib.parse
SITE = sys.argv[1] if len(sys.argv) > 1 else '/var/www/cloudlab'
APP = sys.argv[2] if len(sys.argv) > 2 else '/root/dsh_workspace/cloudlab-app/app'
DATA = os.path.join(APP, 'data')
os.makedirs(DATA, exist_ok=True)
def rel(p): return os.path.relpath(p, SITE).replace(os.sep, '/')
def read(p, n=None):
with open(p, 'rb') as f:
b = f.read(n) if n else f.read()
return b.decode('utf-8', 'ignore')
def size(p): return os.path.getsize(p)
TEXT_EXT = {'.md','.markdown','.json','.csv','.tsv','.txt','.py','.js','.sh','.xml','.yaml','.yml','.html','.htm','.sql','.bat','.ini','.cfg','.toml','.r','.ipynb'}
BIN_EXT = {'.png','.jpg','.jpeg','.gif','.webp','.svg','.pdf','.zip','.gz','.mp4','.mp3','.woff','.woff2','.ttf','.ico','.sdf','.pdb','.mol','.mol2','.xlsx','.docx','.pptx'}
# ---------- 1. file manifest ----------
files = []
for root, dirs, names in os.walk(SITE):
dirs[:] = [d for d in dirs if d not in ('app',) and not d.startswith('.')]
for n in names:
if n.startswith('.'): continue
p = os.path.join(root, n)
r = rel(p)
if r.startswith('app/'): continue
ext = os.path.splitext(n)[1].lower()
try: s = size(p)
except OSError: continue
files.append({'p': r, 'n': n, 'e': ext.lstrip('.'), 's': s, 'd': os.path.dirname(r)})
files.sort(key=lambda x: x['p'])
with open(os.path.join(DATA, 'files.json'), 'w', encoding='utf-8') as f:
json.dump({'generated': __import__('datetime').datetime.now().astimezone().isoformat(timespec='seconds'),
'n': len(files), 'files': files}, f, ensure_ascii=False, separators=(',', ':'))
print('files.json', len(files))
# ---------- 2. molecules ----------
mlib = json.load(open(os.path.join(SITE, 'AtomLab/data/分子库.json'), encoding='utf-8'))
mol_dir = os.path.join(DATA, 'mol'); os.makedirs(mol_dir, exist_ok=True)
light = []
ORDER = {'SINGLE':1,'DOUBLE':2,'TRIPLE':3,'AROMATIC':4,'QUADRUPLE':5}
for m in mlib.get('molecules', []):
key = m.get('key')
if not key: continue
d = m.get('desc') or {}
light.append({
'k': key, 'zh': m.get('zh') or key, 'en': m.get('en') or '',
'cat': m.get('category') or '', 'f': m.get('formula') or '',
'mw': d.get('mw'), 'smiles': m.get('smiles') or '',
'logp': d.get('logp'), 'tpsa': d.get('tpsa'),
'hbd': d.get('hbd'), 'hba': d.get('hba'), 'rings': d.get('rings'),
'heavy': d.get('heavy_atoms'), 'n': m.get('n_atoms') or len(m.get('atoms') or []),
'note': (m.get('note') or '')[:200],
'pubchem_url': m.get('pubchem_url') or '',
'has3d': bool(m.get('coords'))
})
coords = m.get('coords') or []
if not coords: continue
atoms = m.get('atoms') or []
syms = [a.get('sym', 'C') for a in atoms]
bonds = [[b.get('a'), b.get('b'), ORDER.get(str(b.get('order')), 1)] for b in (m.get('bonds') or [])]
geo = {'k': key, 'zh': m.get('zh') or key, 'f': m.get('formula') or '',
'atoms': syms, 'xyz': coords, 'bonds': bonds,
'desc': {kk: d.get(kk) for kk in ('mw','exact_mass','logp','tpsa','hbd','hba','rotb','rings','aromatic_rings','fraction_csp3','formal_charge','heteroatoms','lipinski_violations') if kk in d}}
with open(os.path.join(mol_dir, key + '.json'), 'w', encoding='utf-8') as f:
json.dump(geo, f, ensure_ascii=False, separators=(',', ':'))
light.sort(key=lambda x: (x['cat'], x['zh']))
with open(os.path.join(DATA, 'molecules.json'), 'w', encoding='utf-8') as f:
json.dump({'meta': mlib.get('meta', {}), 'n': len(light), 'molecules': light}, f, ensure_ascii=False, separators=(',', ':'))
print('molecules.json', len(light))
# ---------- 3. protocols ----------
pdir = os.path.join(SITE, '实验协议库/数据')
topics = []
for fn in sorted(os.listdir(pdir)):
if not fn.endswith('.json') or fn == '汇总.json': continue
try: t = json.load(open(os.path.join(pdir, fn), encoding='utf-8'))
except Exception: continue
meta = t.get('meta') or {}
entries = []
for e in t.get('entries') or []:
# 第一个字符串值作为标题
title = ''
for v in e.values():
if isinstance(v, str) and v.strip():
title = v.strip().split('。')[0][:60]; break
entries.append({'title': title, 'body': e})
topics.append({'id': meta.get('topic_id') or fn[:-5], 'title': meta.get('title') or fn[:-5],
'icon': meta.get('icon') or '', 'note': meta.get('note') or '',
'entries': entries})
with open(os.path.join(DATA, 'protocols.json'), 'w', encoding='utf-8') as f:
json.dump({'n_topics': len(topics), 'topics': topics}, f, ensure_ascii=False, separators=(',', ':'))
print('protocols.json', len(topics), sum(len(t['entries']) for t in topics))
# ---------- 4. sequences ----------
seqs = []
for root, dirs, names in os.walk(SITE):
dirs[:] = [d for d in dirs if d != 'app']
for n in names:
if n.lower().endswith(('.fasta', '.fa')):
p = os.path.join(root, n)
content = read(p)
seqs.append({'p': rel(p), 'name': n, 'size': size(p), 'content': content[:200000]})
with open(os.path.join(DATA, 'sequences.json'), 'w', encoding='utf-8') as f:
json.dump({'n': len(seqs), 'sequences': seqs}, f, ensure_ascii=False, separators=(',', ':'))
print('sequences.json', len(seqs))
# ---------- 5. evolution lab model ----------
for src, dst in [('AtomLab/data/进化实验台.json', 'evo.json'),
('AtomLab/data/环境耦合数据集.json', 'env.json')]:
p = os.path.join(SITE, src)
if os.path.exists(p):
json.dump(json.load(open(p, encoding='utf-8')), open(os.path.join(DATA, dst), 'w', encoding='utf-8'),
ensure_ascii=False, separators=(',', ':'))
print('evo/env copied')
# ---------- 6. datasets (csv) ----------
ds = []
for f in files:
if f['e'] in ('csv', 'tsv'):
ds.append({'p': f['p'], 'n': f['n'], 's': f['s'], 'd': f['d']})
with open(os.path.join(DATA, 'datasets.json'), 'w', encoding='utf-8') as f:
json.dump({'n': len(ds), 'datasets': ds}, f, ensure_ascii=False, separators=(',', ':'))
print('datasets.json', len(ds))
# ---------- 7. search index ----------
def title_of(p, ext, raw):
if ext == 'md':
for line in raw.splitlines()[:80]:
if line.startswith('# '): return line[2:].strip()[:120]
if ext == 'json':
try:
d = json.loads(raw)
if isinstance(d, dict):
for k in ('title', 'name'):
if isinstance(d.get(k), str): return d[k][:120]
m = d.get('meta')
if isinstance(m, dict) and isinstance(m.get('title'), str): return m['title'][:120]
except Exception: pass
return os.path.basename(p)
index = []
total = 0
LIMIT = 12 * 1024 * 1024
for f in files:
if f['e'] not in ('md','json','csv','txt','py','js','xml','tsv','yaml','yml','sh','r','ipynb','sql'): continue
if f['s'] > 1_200_000: continue
p = os.path.join(SITE, f['p'])
try: raw = read(p)
except Exception: continue
text = raw
if f['e'] == 'json':
text = re.sub(r'\s+', ' ', raw)
title = title_of(p, f['e'], raw)
snippet = text[:1200]
total += len(snippet)
index.append({'p': f['p'], 't': title, 's': snippet})
if total > LIMIT: break
# synthetic entries that open the bench directly (molecule / protocol / sequence)
try:
mols = json.load(open(os.path.join(DATA, 'molecules.json'), encoding='utf-8')).get('molecules', [])
for m in mols:
k = m.get('k', '')
if not k: continue
desc = ' · '.join(str(x) for x in [m.get('cat',''), m.get('f',''), ('MW ' + str(m.get('mw','')))] if x)
index.append({'p': 'AtomLab 分子库 / ' + (m.get('cat') or '分子'),
't': ' · '.join(x for x in [m.get('zh',''), m.get('en',''), m.get('f','')] if x),
's': desc + ' · ' + (m.get('note') or '')[:300],
'u': '/app/chem.html?mol=' + urllib.parse.quote(k, safe='')})
except Exception as e:
print('search molecules skipped:', e)
try:
prots = json.load(open(os.path.join(DATA, 'protocols.json'), encoding='utf-8')).get('topics', [])
for t in prots:
tid = t.get('id', '')
if not tid: continue
n = len(t.get('entries') or [])
index.append({'p': '实验协议库 / ' + tid,
't': (t.get('icon') or '📋') + ' ' + (t.get('title') or tid),
's': (t.get('note') or '')[:400] + (' · ' + str(n) + ' 步' if n else ''),
'u': '/app/bio.html?topic=' + urllib.parse.quote(tid, safe='')})
except Exception as e:
print('search protocols skipped:', e)
try:
seqs = json.load(open(os.path.join(DATA, 'sequences.json'), encoding='utf-8')).get('sequences', [])
for s in seqs:
p = s.get('p', '')
if not p: continue
index.append({'p': p,
't': s.get('name') or os.path.basename(p),
's': 'FASTA 序列 · ' + str(round((s.get('size') or 0)/1024, 1)) + ' KB · 可在序列工作台载入',
'u': '/app/bio.html?seq=' + urllib.parse.quote(p, safe='')})
except Exception as e:
print('search sequences skipped:', e)
with open(os.path.join(DATA, 'search.json'), 'w', encoding='utf-8') as f:
json.dump({'n': len(index), 'docs': index}, f, ensure_ascii=False, separators=(',', ':'))
print('search.json', len(index), round(total/1e6,1), 'MB raw text')
# ---------- 8. sync generated data into the served app ----------
site_data = os.path.join(SITE, 'app', 'data')
if os.path.realpath(site_data) != os.path.realpath(DATA):
os.makedirs(site_data, exist_ok=True)
for name in os.listdir(DATA):
src = os.path.join(DATA, name)
dst = os.path.join(site_data, name)
if os.path.isdir(src):
shutil.copytree(src, dst, dirs_exist_ok=True)
else:
shutil.copy2(src, dst)
print('synced data ->', site_data)