91 lines
5.6 KiB
Python
91 lines
5.6 KiB
Python
"""Non-destructive legacy media/history migration; no profile or service changes."""
|
|
import argparse,hashlib,json,os,shutil,sqlite3,tempfile,time
|
|
from pathlib import Path
|
|
|
|
def digest(p):
|
|
h=hashlib.sha256()
|
|
with p.open('rb') as f:
|
|
while b:=f.read(4*1024**2):h.update(b)
|
|
return h.hexdigest()
|
|
|
|
def copy_tree(source,target,records):
|
|
if not source.exists():return
|
|
for p in sorted(source.rglob('*')):
|
|
rel=p.relative_to(source);q=target/rel
|
|
if p.is_symlink():raise ValueError('Symlink in Nutzdaten: '+str(p))
|
|
if p.is_dir():q.mkdir(parents=True,exist_ok=True);continue
|
|
if not p.is_file() or p.name.endswith(('-wal','-shm')):continue
|
|
q.parent.mkdir(parents=True,exist_ok=True)
|
|
temporary=q.with_name(q.name+'.migration-partial')
|
|
if p.suffix in ('.db','.sqlite3'):
|
|
if temporary.exists():temporary.unlink()
|
|
with sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True) as a,sqlite3.connect(temporary) as b:
|
|
a.backup(b)
|
|
if b.execute('PRAGMA integrity_check').fetchone()[0]!='ok':raise ValueError('SQLite beschädigt')
|
|
sha=digest(temporary)
|
|
else:sha=digest(p)
|
|
if q.exists():
|
|
if digest(q)!=sha:
|
|
temporary.unlink(missing_ok=True)
|
|
raise ValueError('Zielkonflikt; nichts überschrieben: '+str(q))
|
|
temporary.unlink(missing_ok=True)
|
|
else:
|
|
if p.suffix not in ('.db','.sqlite3'):shutil.copy2(p,temporary)
|
|
if digest(temporary)!=sha:raise ValueError('Kopie beschädigt')
|
|
temporary.replace(q);q.chmod(0o600)
|
|
records.append({'source':str(p),'target':str(q),'sha256':digest(q),'size':q.stat().st_size})
|
|
|
|
def merge_jobs(source,target,state):
|
|
if not source.exists():return {'imported':0}
|
|
remap={'/data/models/':'/var/lib/deck/applio-data/logs/','/data/uploads/':'/var/lib/deck/applio-data/datasets/.mikes-applio-ui/uploads/','/data/results/':'/var/lib/deck/applio-data/datasets/.mikes-applio-ui/results/','/app/logs/':'/var/lib/deck/applio-data/logs/','/app/assets/datasets/':'/var/lib/deck/applio-data/datasets/'}
|
|
with sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True) as old,sqlite3.connect(target,timeout=30) as new:
|
|
old.row_factory=sqlite3.Row
|
|
columns=[x[1] for x in old.execute('pragma table_info(jobs)')]
|
|
if columns!=[x[1] for x in new.execute('pragma table_info(jobs)')]:raise ValueError('Applio-Schema abweichend')
|
|
count=0;missing=[]
|
|
for row in old.execute('select * from jobs'):
|
|
d=dict(row)
|
|
existing=new.execute('select 1 from jobs where id=?',(d['id'],)).fetchone()
|
|
if existing:
|
|
for field in ('input_files','output_files'):
|
|
paths=json.loads(new.execute('select '+field+' from jobs where id=?',(d['id'],)).fetchone()[0]);changed=False
|
|
for i,path in enumerate(paths):
|
|
for prefix,dest in remap.items():
|
|
if path.startswith(prefix):paths[i]=dest+path[len(prefix):];changed=True;break
|
|
if changed:new.execute('update jobs set '+field+'=? where id=?',(json.dumps(paths),d['id']))
|
|
continue
|
|
for key in ('input_files','output_files'):
|
|
paths=json.loads(d[key]);mapped=[]
|
|
for p in paths:
|
|
for prefix,dest in remap.items():
|
|
if p.startswith(prefix):p=dest+p[len(prefix):];break
|
|
mapped.append(p)
|
|
host=Path(str(state)+p[len('/var/lib/deck'):]) if p.startswith('/var/lib/deck/') else Path(p)
|
|
if not host.is_file():missing.append({'job':d['id'],'field':key,'path':p})
|
|
d[key]=json.dumps(mapped)
|
|
# Imported jobs are history, never resume old queued/running work.
|
|
if d['status'] in ('wartend','laufend','queued','running'):
|
|
d['status']='abgebrochen';d['phase']='Historischer Auftrag; bei Übernahme nicht fortgesetzt';d['cancelled']=1
|
|
new.execute('insert into jobs ('+','.join(columns)+') values ('+','.join('?' for _ in columns)+')',[d[c] for c in columns]);count+=1
|
|
if new.execute('pragma integrity_check').fetchone()[0]!='ok':raise ValueError('Ziel-Datenbank beschädigt')
|
|
return {'imported':count,'missing_references':missing}
|
|
|
|
def run(state,ladypoly):
|
|
state=Path(state);archive=state/'legacy-userdata';archive.mkdir(exist_ok=True,mode=0o700);records=[]
|
|
sources=[('/data/music/ace-step-ui','ace-step-ui'),('/data/music/acestep','acestep-runs'),('/data/voice/xvc/output','xvc-output'),('/data/voice/omnivoice/output','omnivoice-output'),('/data/voice/studio/profiles','voice-profiles'),('/data/voice/applio/mikes-applio-ui','applio-ui'),('/var/lib/docker/volumes/mike-ai_router-images/_data','router-images'),('/var/lib/docker/volumes/mike-ai_router-state/_data','router-state')]
|
|
for source,name in sources:
|
|
copy_tree(Path(source),archive/name,records);print('Preserved:',name,flush=True)
|
|
copy_tree(Path('/data/music/yue2'),Path(ladypoly)/'outputs',records)
|
|
# Fill gaps in previously copied training datasets and outputs, retaining new files.
|
|
for name in ('datasets','logs'):
|
|
copy_tree(Path('/data/voice/applio')/name,state/'applio-data'/name,records)
|
|
result=merge_jobs(Path('/data/voice/applio/mikes-applio-ui/jobs/jobs.db'),state/'applio-data/jobs/jobs.db',state)
|
|
for root in (archive,state/'applio-data',Path(ladypoly)/'outputs'):
|
|
for p in [root,*root.rglob('*')]:
|
|
if not p.is_symlink():os.chown(p,65534,65534)
|
|
manifest={'created_at':time.time(),'files':records,'applio':result,'legacy_ui_note':'ACE-Step-Playlists/DB erhalten; vollständige UI weiterhin zurückgestellt.'}
|
|
out=archive/'migration-manifest.json';tmp=out.with_suffix('.tmp');tmp.write_text(json.dumps(manifest,ensure_ascii=False,indent=2));tmp.chmod(0o600);tmp.replace(out)
|
|
print(json.dumps({'files':len(records),'bytes':sum(r['size'] for r in records),'applio_jobs':result['imported'],'missing_references':len(result.get('missing_references',[]))}))
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser();p.add_argument('--state',required=True);p.add_argument('--ladypoly',required=True);a=p.parse_args();run(a.state,a.ladypoly)
|