Initial commit: Lumen Android puzzle notebook v1.7

This commit is contained in:
Hadrian Burkhardt
2026-10-31 03:28:48 +01:00
commit 07e9253663
76 changed files with 3770 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
package com.lumen.daily;
public class ExportNarration {
static String quote(String value){return "\""+value.replace("\\","\\\\").replace("\"","\\\"").replace("\n","\\n").replace("\r","\\r")+"\"";}
public static void main(String[] args){System.out.print("[");boolean first=true;for(StoryBook.Page p:StoryBook.PAGES){if(p.kind==StoryBook.Kind.PUZZLE)continue;if(!first)System.out.print(",");first=false;System.out.print("{\"pageId\":"+quote(p.id)+",\"resource\":"+quote("narration_"+p.id.replace('.','_'))+",\"text\":"+quote(p.text)+"}");}System.out.println("]");}
}
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Verify every bundled recording matches the current diary text and its WAV master."""
import array, hashlib, json, math, subprocess, tempfile, wave
from pathlib import Path
root=Path(__file__).resolve().parents[1]
source=root/'assets/narration';raw=root/'app/src/main/res/raw'
with tempfile.TemporaryDirectory(prefix='lumen-audio-text-') as temp:
subprocess.run(['javac','-d',temp,str(root/'app/src/main/java/com/lumen/daily/StoryBook.java'),str(root/'scripts/ExportNarration.java')],check=True)
canonical=json.loads(subprocess.check_output(['java','-cp',temp,'com.lumen.daily.ExportNarration']))
assert canonical==json.loads((source/'scripts.json').read_text()),'Regenerate the script export after editing diary text'
manifest=json.loads((source/'manifest.json').read_text());runtime=json.loads((raw/'narration_manifest.json').read_text())
assert runtime['tracks']==manifest['tracks']
assert len(canonical)==5==len(manifest['tracks'])
for record in canonical:
track=manifest['tracks'][record['pageId']]
assert track['text']==record['text']
assert track['textSha256']==hashlib.sha256(record['text'].encode()).hexdigest()
assert track['resource']==record['resource']
assert '\n\n'.join(cue['text'] for cue in track['cues'])==record['text']
previous=0
for cue in track['cues']:
assert previous<=cue['startMs']<cue['endMs']<=track['durationMs']
previous=cue['endMs']
wav=source/'wav'/(record['resource']+'.wav');flac=raw/track['file']
with wave.open(str(wav),'rb') as reader:
assert reader.getnchannels()==1 and reader.getsampwidth()==2 and reader.getframerate()==24000
assert reader.getnframes()==track['frames']
master=reader.readframes(reader.getnframes())
samples=array.array('h',master);peak=max(abs(v) for v in samples)
assert 1000<peak<32767,'Silent or clipped audio'
decoded=subprocess.check_output(['ffmpeg','-v','error','-i',str(flac),'-f','s16le','-acodec','pcm_s16le','-'])
assert decoded==master,'Runtime FLAC must preserve the WAV master exactly'
assert track['flacSha256']==hashlib.sha256(flac.read_bytes()).hexdigest()
print(f"PASS {record['pageId']}: {track['durationMs']/1000:.1f}s, lossless, text/cues match")
for p in (root/'app/src/main/java').rglob('*.java'):
assert 'android.speech.tts' not in p.read_text(),f'Android reader reintroduced in {p}'
assert 'TTS_SERVICE' not in (root/'app/src/main/AndroidManifest.xml').read_text()
print('All five recordings verified; no Android text-to-speech dependency.')
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Destructive test fixtures are restricted to the disposable .qa app, never the main app."""
import argparse
from pathlib import Path
import re
import subprocess
import time
import xml.etree.ElementTree as ET
parser=argparse.ArgumentParser()
parser.add_argument('--adb',default='/home/ubuntu/Android/Sdk/platform-tools/adb')
parser.add_argument('--serial',required=True)
parser.add_argument('--package',default='com.lumen.daily.qa')
parser.add_argument('--output',default='artifacts/storybook-check')
args=parser.parse_args()
assert re.fullmatch(r'[a-zA-Z0-9_.]+\.qa',args.package),'Only a disposable .qa app may be tested'
PKG=args.package
BASE=[args.adb,'-s',args.serial]
OUT=Path(args.output);OUT.mkdir(parents=True,exist_ok=True)
def adb(*cmd,stdin=None):
result=subprocess.run(BASE+list(cmd),input=stdin,capture_output=True,check=True)
return result.stdout
def tap_node(node):
b=list(map(int,re.findall(r'\d+',node.get('bounds'))))
adb('shell','input','tap',str((b[0]+b[2])//2),str((b[1]+b[3])//2))
def dump():
adb('shell','uiautomator','dump','/sdcard/lumen-story-test.xml')
tree=ET.fromstring(adb('exec-out','cat','/sdcard/lumen-story-test.xml'))
for n in tree.iter('node'):
if n.get('text')=='Do not consent':
tap_node(n)
return dump()
return tree
def find(text,scroll=False,exact=False):
for attempt in range(12 if scroll else 1):
tree=dump()
for n in tree.iter('node'):
value=n.get('text','')
if value.casefold()==text.casefold() if exact else text.casefold() in value.casefold():
return n
if scroll:adb('shell','input','swipe','600','1400','600','700','250')
raise AssertionError('Missing '+text+'; visible '+str([n.get('text') for n in tree.iter('node') if n.get('text')]))
def tap(text,scroll=False,exact=False):
tap_node(find(text,scroll,exact))
dump()
def shot(name):(OUT/name).write_bytes(adb('exec-out','screencap','-p'))
def launch():adb('shell','am','start','-n',PKG+'/com.lumen.daily.MainActivity')
def prefs():return ET.fromstring(adb('shell','run-as',PKG,'cat','shared_prefs/lumen.xml'))
def pref(name):
for n in prefs():
if n.get('name')==name:return n.get('value',n.text)
return None
def replace_prefs(changes):
adb('shell','am','force-stop',PKG)
root=prefs()
for key,(kind,value) in changes.items():
for n in list(root):
if n.get('name')==key:root.remove(n)
n=ET.SubElement(root,kind,{'name':key})
if kind=='string':n.text=value
else:n.set('value',value)
xml=ET.tostring(root,encoding='utf-8',xml_declaration=True)
adb('shell',f"run-as {PKG} sh -c 'cat > shared_prefs/lumen.xml'",stdin=xml)
def setting(name):return adb('shell','settings','get','system',name).decode().strip()
def page(expected):assert pref('notebook_last_page')==expected,(expected,pref('notebook_last_page'))
def cell_node(row,col):
for n in dump().iter('node'):
if n.get('content-desc','').startswith(f'Row {row}, column {col},'):return n
raise AssertionError('Missing accessible grid cell')
rotation=setting('user_rotation');auto=setting('accelerometer_rotation')
results=[]
try:
launch();dump()
# Reset only this disposable app's game data; keep its independent UMP choice.
replace_prefs({'notebook_open':('boolean','false'),'notebook_last_page':('string','cottage.dedication'),'solved':('int','0'),
'done_story_v1_0':('boolean','false'),'grid_story_v1_0':('string','0'*49),
'notebook_note_open':('boolean','false'),'notebook_handle_seen':('boolean','false')})
launch();dump();shot('00-home.png');tap('Open Mara’s notebook',scroll=True);dump()
if pref('notebook_open')!='true':
tap('Open Mara’s notebook',scroll=True);dump()
find('For you, when you are ready');page('cottage.dedication');shot('01-dedication.png')
# Swipe from outside the writing area; grid/body drags must not share this gesture.
adb('shell','input','swipe','1120','650','650','650','350')
find('By the cottage window');page('cottage.window');shot('02-cottage-entry.png')
results.append('PASS: edge swipe opens the next illustrated leaf')
print(results[-1],flush=True)
# Exercise the bundled FLAC recording; no device reader or voice download is used.
# UIAutomator waits for idle; continuously updating playback clocks can outlast
# a short recording. Toggle by the known button bounds, then inspect while paused.
play=find('Play this reading',scroll=True)
tap_node(play);time.sleep(2);shot('02-recording-playing.png');tap_node(play)
find('Resume recording')
paused_text=next(n.get('text') for n in dump().iter('node') if n.get('text','').startswith('Paused · '))
def elapsed(value):
minute,second=map(int,re.search(r'(\d+):(\d+)',value).groups());return minute*60+second
first=elapsed(paused_text)
assert 1<=first<8,paused_text
tap_node(play);time.sleep(2);tap_node(play)
find('Resume recording')
resumed_text=next(n.get('text') for n in dump().iter('node') if n.get('text','').startswith('Paused · '))
second=elapsed(resumed_text)
assert first+1<=second<=first+4,(paused_text,resumed_text)
tap('Stop',exact=True);find('Play this reading')
results.append('PASS: bundled recording play, pause, exact-position resume and stop')
print(results[-1],flush=True)
tap('Speed',scroll=True,exact=True);tap('Unhurried');dump();assert pref('recording_speed') is not None
tap('Next leaf');find('A spark in the drawer');page('cottage.match.puzzle');shot('03-match-puzzle.png')
before=pref('grid_story_v1_0')
node=cell_node(1,1);bounds=list(map(int,re.findall(r'\d+',node.get('bounds'))))
x=(bounds[0]+bounds[2])//2;y=(bounds[1]+bounds[3])//2
adb('shell','input','swipe',str(x),str(y),str(x+100),str(y),'300')
dump();page('cottage.match.puzzle')
assert pref('grid_story_v1_0')!=before
tap('Undo a mark');dump();assert pref('grid_story_v1_0')==before
results.append('PASS: grid drag edits a cell without turning; undo restores it')
print(results[-1],flush=True)
tap('Next leaf');tap('Read ahead');find('One small light');page('cottage.match.memory')
assert pref('done_story_v1_0')=='false' and pref('solved')=='0'
shot('04-match-memory.png');tap('Next leaf');find('A note I nearly forgot');shot('05-folded-note.png')
tap('Unfold Gran’s note');find('For the crossing');assert pref('notebook_note_open')=='true';shot('05-open-note.png')
tap('Bookmark');dump();assert pref('notebook_manual_bookmark')=='cottage.folded.note'
tap('Next leaf');find('The handle, carefully mended');shot('06-lantern-sketch.png')
# Select the accessible illustration, not its caption.
image=next(n for n in dump().iter('node') if n.get('content-desc','').startswith('Watercolour of Mara'))
tap_node(image);find('A careful repair');tap('Keep that thought');dump();assert pref('notebook_handle_seen')=='true'
tap('Contents');tap('Return to my ribbon bookmark');find('For the crossing');page('cottage.folded.note')
adb('shell','am','force-stop',PKG);launch();find('For the crossing');page('cottage.folded.note')
assert pref('notebook_note_open')=='true' and pref('solved')=='0'
results.append('PASS: read-ahead does not award a puzzle; note, inspection and ribbon persist across process restart')
print(results[-1],flush=True)
# Near-solved fixture verifies completion routing and no double award on revisiting.
picture=['0011000','0111100','0011000','0001000','0001000','0001000','0001000']
solution=''.join('1' if c=='1' else '2' for row in picture for c in row)
replace_prefs({'notebook_last_page':('string','cottage.match.puzzle'),'notebook_open':('boolean','true'),
'grid_story_v1_0':('string','0'+solution[1:])})
launch();find('A spark in the drawer');node=cell_node(1,1)
tap_node(node);tap_node(node)
find('One small light');page('cottage.match.memory');assert pref('done_story_v1_0')=='true' and pref('solved')=='1'
tap('Previous leaf');find('Already restored');tap('Next leaf');find('One small light');assert pref('solved')=='1'
results.append('PASS: solving reveals the memory and increments once; replay preserves completion')
print(results[-1],flush=True)
adb('shell','settings','put','system','accelerometer_rotation','0')
adb('shell','settings','put','system','user_rotation','1')
find('One small light');shot('07-landscape.png');page('cottage.match.memory')
results.append('PASS: orientation change restores the same leaf')
finally:
for name,value in [('user_rotation',rotation),('accelerometer_rotation',auto)]:
if value=='null':adb('shell','settings','delete','system',name)
else:adb('shell','settings','put','system',name,value)
dump()
(OUT/'results.txt').write_text('\n'.join(results)+'\n')
print('Story notebook checks completed; original rotation settings restored.',flush=True)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Prepare immutable WAV masters and bundled FLACs; Android performs no speech synthesis."""
import argparse, hashlib, importlib.metadata, json, subprocess
from pathlib import Path
import numpy as np
import soundfile as sf
import onnxruntime as ort
import espeakng_loader
from kokoro_onnx import Kokoro
from kokoro_onnx.config import EspeakConfig
parser=argparse.ArgumentParser()
parser.add_argument('--model',type=Path,required=True)
parser.add_argument('--voices',type=Path,required=True)
parser.add_argument('--voice',default='bf_emma')
parser.add_argument('--speed',type=float,default=.82)
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
a=parser.parse_args()
source=a.root/'assets/narration';raw=a.root/'app/src/main/res/raw'
(source/'wav').mkdir(parents=True,exist_ok=True);raw.mkdir(parents=True,exist_ok=True)
options=ort.SessionOptions();options.intra_op_num_threads=4;options.inter_op_num_threads=1
session=ort.InferenceSession(str(a.model),sess_options=options,providers=['CPUExecutionProvider'])
session.disable_fallback()
config=EspeakConfig(lib_path=str(espeakng_loader.get_library_path()),data_path=str(espeakng_loader.get_data_path()))
engine=Kokoro.from_session(session,str(a.voices),espeak_config=config)
tracks={}
for record in json.loads((source/'scripts.json').read_text()):
paragraphs=[]
for part in record['text'].split('\n\n'):
if paragraphs and len(part)<45:paragraphs[-1]+='\n\n'+part
elif paragraphs and len(paragraphs[-1])<45:paragraphs[-1]+='\n\n'+part
else:paragraphs.append(part)
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[]
for part in paragraphs:
print(f"Rendering {record['pageId']} · {len(cues)+1}/{len(paragraphs)}",flush=True)
samples,sample_rate=engine.create(part.replace('\n',' '),voice=a.voice,speed=a.speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
assert sample_rate==rate
samples=np.asarray(samples,dtype=np.float32).reshape(-1)
assert len(samples)>rate*.3 and np.isfinite(samples).all()
fade=min(240,len(samples)//4)
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
start=frames;pieces.append(samples);frames+=len(samples)
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part})
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
audio*=.86/peak
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
sf.write(wav,audio,rate,subtype='PCM_16')
subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True)
decoded,check_rate=sf.read(flac,dtype='int16');master,_=sf.read(wav,dtype='int16')
assert check_rate==rate and np.array_equal(decoded,master)
tracks[record['pageId']]={**record,'file':flac.name,'sampleRate':rate,'channels':1,'frames':len(audio),
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
manifest={'voice':a.voice,'speed':a.speed,'language':'en-gb','method':'Synthetic narration rendered during development; bundled file playback only.',
'modelSha256':hashlib.sha256(a.model.read_bytes()).hexdigest(),'voicesSha256':hashlib.sha256(a.voices.read_bytes()).hexdigest(),
'packages':{p:importlib.metadata.version(p) for p in ['kokoro-onnx','onnxruntime','soundfile','espeakng-loader']},'tracks':tracks}
(source/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
(raw/'narration_manifest.json').write_text(json.dumps({'tracks':tracks},ensure_ascii=False,indent=2)+'\n')
print('All five narration masters and runtime FLACs prepared.',flush=True)