← Files Uni Lecture TutorARCHIVED FILE

skills/automatic-lecture-learning/scripts/ult_language.py

23.2 KB · Nov 30, 2026 · 18:13 UTC

↓ Download file

See the change to this file →

"""Stateless CEFR-informed formative language learning. No official level, audio
analysis, semantic grading, network, automatic scheduling or authenticated history.
The host supplies rubric judgements from actually observed tasks; this helper
validates their structure and deterministic session transitions only.
"""
import argparse
import copy
from datetime import date, timedelta
import json
import re
from collections import defaultdict
from ult_safe_io import read_json, safe_error

LEVELS=('Pre-A1','A1','A2','B1','B2','C1','C2')
SKILLS=('reading','listening','writing','spoken_production','written_interaction','spoken_interaction','mediation','phonology')
TEXT=('reading','writing','written_interaction','mediation')
AUDIO=('listening','spoken_production','spoken_interaction','phonology')
DOMAINS=('general','academic','professional','daily_life','exam','travel','custom')
STRANDS=('meaning_input','meaning_output','language_focus','fluency')
RUBRICS={
 'reading':('gist','detail','interpretation'), 'listening':('gist','detail','interpretation'),
 'writing':('task','coherence','range','accuracy'),
 'spoken_production':('task','coherence','range','accuracy','intelligibility'),
 'written_interaction':('task','responsiveness','appropriateness','accuracy'),
 'spoken_interaction':('task','responsiveness','appropriateness','intelligibility'),
 'mediation':('source_fidelity','selection','audience','clarity'),
 'phonology':('intelligibility','target_feature')}
PHASES=('placement','goal','study','paused','complete')
LIMIT=1_000_000
MAX_EVENTS=500
MAX_PLACEMENT=40
class LanguageError(ValueError): pass

def need(ok,msg):
    if not ok: raise LanguageError(msg)

def fields(v,required,optional=()):
    need(type(v) is dict and set(required)<=set(v)<=set(required)|set(optional),'invalid language record fields')

def text(v,limit):
    need(type(v) is str and 0<len(v.strip())<=limit and len(v)<=limit and not any(0xD800<=ord(c)<=0xDFFF for c in v),'invalid bounded text')

def identifier(v):
    need(type(v) is str and re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}',v) is not None,'invalid language record ID')

def integer(v,lo,hi):need(type(v) is int and lo<=v<=hi,'invalid integer bound')

def iso(v):
    need(type(v) is str and re.fullmatch(r'\d{4}-\d{2}-\d{2}',v) is not None,'invalid date')
    try:return date.fromisoformat(v)
    except ValueError:raise LanguageError('invalid date') from None

def task_check(t,available):
    fields(t,('id','skill','band','modality','fingerprint','strand','objective'))
    identifier(t['id']);need(t['skill'] in SKILLS and t['skill'] in available,'task skill unavailable')
    need(t['band'] in LEVELS and t['strand'] in STRANDS,'invalid task band or strand')
    need(t['modality']==('audio' if t['skill'] in AUDIO else 'text'),'actual task modality required')
    need(type(t['fingerprint']) is str and re.fullmatch('[a-f0-9]{64}',t['fingerprint']) is not None,'task needs declared content fingerprint')
    text(t['objective'],240)

def rubric_check(task,result,placement=False):
    fields(result,('outcome','assistance','ratings','evidence_origin','date'))
    need(result['outcome'] in ('completed','skipped','ungraded') and result['assistance'] in ('none','hint','model','translation'),'invalid performance outcome')
    need(result['evidence_origin'] in ('observed_text','observed_audio','reported'),'invalid performance provenance');iso(result['date'])
    if result['evidence_origin']=='observed_audio':need(task['modality']=='audio','audio evidence on text task')
    if result['evidence_origin']=='observed_text':need(task['modality']=='text','transcript cannot establish audio performance')
    if placement:need(result['assistance']=='none','placement requires unaided response; skip or exit instead')
    ratings=result['ratings'];need(type(ratings) is dict,'invalid rubric')
    if result['outcome']=='completed':
        need(set(ratings)==set(RUBRICS[task['skill']]),'rubric must cover skill-specific criteria')
        for v in ratings.values():integer(v,0,2)
    else:need(not ratings,'skipped or ungraded response cannot assert ratings')

def eligible(task,result):
    return (result['outcome']=='completed' and result['assistance']=='none' and result['evidence_origin']==('observed_audio' if task['modality']=='audio' else 'observed_text'))

def passes(task,result):
    # Transparent criterion rule, NOT calibrated CEFR cut scores: all criteria
    # at least partially met and at least half fully met. No averaged levels.
    return eligible(task,result) and min(result['ratings'].values())>=1 and sum(v==2 for v in result['ratings'].values())*2>=len(result['ratings'])

def goal_check(g):
    fields(g,('domain','target','minutes','days','situations'))
    need(g['domain'] in DOMAINS and g['target'] in LEVELS,'invalid language goal');integer(g['minutes'],5,240);integer(g['days'],1,7)
    need(type(g['situations']) is list and 1<=len(g['situations'])<=8,'specify meaningful goal situations')
    for t in g['situations']:text(t,160)

def validate(s):
    fields(s,('format','version','revision','target_language','support_language','available','phase','history_trust','events','pending','goal','placement_closed','paused_from','action_ids'),('starting_band',))
    need(s['format']=='ult-language' and s['version']=='1.0','unsupported language record');integer(s['revision'],0,2000)
    text(s['target_language'],64);text(s['support_language'],64)
    need(s.get('starting_band','A2') in LEVELS,'invalid diagnostic starting band')
    need(s['phase'] in PHASES and s['history_trust'] in ('current_context','reported'),'invalid language phase or trust')
    av=s['available'];need(type(av) is list and av and len(av)<=len(SKILLS) and all(type(k) is str and k in SKILLS for k in av) and len(av)==len(set(av)),'invalid available skill set')
    need(type(s['placement_closed']) is bool,'invalid placement flag')
    need(s['paused_from'] in (None,'placement','goal','study') and (s['phase']=='paused')==(s['paused_from'] is not None),'invalid pause state')
    effective=s['paused_from'] if s['phase']=='paused' else s['phase']
    if s['goal'] is not None:goal_check(s['goal'])
    need(effective!='study' or (s['goal'] is not None and s['placement_closed']),'goal required before study')
    need(effective!='goal' or (s['goal'] is None and s['placement_closed']),'goal phase requires ended placement')
    need(effective!='placement' or (s['goal'] is None and not s['placement_closed']),'placement cannot have an active goal')
    ids=s['action_ids'];need(type(ids) is list and len(ids)==s['revision'] and len(ids)<=2000,'invalid action history')
    for v in ids:identifier(v)
    need(len(ids)==len(set(ids)),'replayed action')
    events=s['events'];need(type(events) is list and len(events)<=MAX_EVENTS,'language event limit; export and start new scope')
    items=set();fingerprints=set();nplacement=0;prior_date=None;study_seen=False
    for e in events:
        fields(e,('task','result','stage'));t=e['task'];p=e['result'];task_check(t,av)
        need(e['stage'] in ('placement','study'),'invalid performance stage')
        if e['stage']=='placement':
            nplacement+=1;need(not study_seen and nplacement<=MAX_PLACEMENT,'invalid placement event chronology')
        else:study_seen=True;need(s['placement_closed'] and s['goal'] is not None,'study without goal')
        rubric_check(t,p,e['stage']=='placement')
        need(s['history_trust']=='current_context' or p['evidence_origin']=='reported','reported state cannot assert current observations')
        need(t['id'] not in items,'duplicate language task ID');items.add(t['id'])
        if e['stage']=='placement':need(t['fingerprint'] not in fingerprints,'placement task content reused')
        fingerprints.add(t['fingerprint'])
        dt=iso(p['date']);need(prior_date is None or dt>=prior_date,'language dates out of order');prior_date=dt
    p=s['pending']
    if p is not None:
        need(effective in ('placement','study'),'pending task outside language learning phase');task_check(p,av)
        need(p['id'] not in items,'pending task already assessed')
        if effective=='placement':need(nplacement<MAX_PLACEMENT and p['fingerprint'] not in fingerprints,'placement exhausted or task reused')
    return s

def new(target_language,support_language,available=None,starting_band='A2'):
    s={'format':'ult-language','version':'1.0','revision':0,'target_language':target_language,'support_language':support_language,
       'available':list(TEXT if available is None else available),'phase':'placement','history_trust':'current_context','events':[],
       'pending':None,'goal':None,'placement_closed':False,'paused_from':None,'action_ids':[],'starting_band':starting_band}
    return validate(s)

def placement_profile(s):
    validate(s)
    if not s['placement_closed']:return {'status':'placement_in_progress','feedback_deferred':True,'official_cefr':False}
    profile={}
    for skill in SKILLS:
        rows=[e for e in s['events'] if e['stage']=='placement' and e['task']['skill']==skill and eligible(e['task'],e['result'])]
        if skill not in s['available']:profile[skill]={'status':'not_available','working_band':None,'sample_count':0};continue
        by=defaultdict(list)
        for e in rows:by[e['task']['band']].append(passes(e['task'],e['result']))
        # Two distinct successful tasks at same band; a contradiction at that
        # band or lower means uncertainty, not a higher official level.
        supported=[b for b,v in by.items() if len(v)>=2 and all(v) and not any(any(not x for x in vs) for lo,vs in by.items() if LEVELS.index(lo)<=LEVELS.index(b))]
        band=max(supported,key=LEVELS.index) if supported else None
        profile[skill]={'status':'provisional_task_band' if band else 'insufficient_evidence','working_band':band,'sample_count':len(rows),'unresolved_bands':[b for b in LEVELS if b in by and any(not x for x in by[b])]}
    return {'status':'formative_profile','skills':profile,'official_cefr':False,'global_level':None,'semantic_grading_verified':False,'history_authenticated':False,'policy':'heuristic criterion sampling; not a calibrated language examination'}

def next_placement(s):
    validate(s);need(s['phase']=='placement','not in placement')
    if s['pending'] is not None:return {'activity':'await_response','task':copy.deepcopy(s['pending'])}
    rows=[e for e in s['events'] if e['stage']=='placement']
    if len(rows)>=MAX_PLACEMENT:return {'activity':'finish_placement','reason':'sampling budget reached'}
    # Probe weaker/less sampled skills before extending successful bands. A
    # single outcome never determines a global level.
    candidates=[]
    for skill in s['available']:
        rs=[e for e in rows if e['task']['skill']==skill]
        if len(rs)>=6:continue
        if not rs:band=s.get('starting_band','A2')
        else:
            last=rs[-1];i=LEVELS.index(last['task']['band']);recent=[e for e in rs if e['task']['band']==last['task']['band']]
            if not eligible(last['task'],last['result']):band=last['task']['band']
            elif not passes(last['task'],last['result']):band=LEVELS[max(0,i-1)]
            elif len(recent)>=2 and all(passes(e['task'],e['result']) for e in recent):band=LEVELS[min(len(LEVELS)-1,i+1)]
            else:band=last['task']['band']
        candidates.append((len(rs),SKILLS.index(skill),skill,band))
    if not candidates:return {'activity':'finish_placement','reason':'skill sampling budget reached'}
    _,_,skill,band=min(candidates)
    return {'activity':'generate_distinct_diagnostic_task','skill':skill,'band':band,'modality':'audio' if skill in AUDIO else 'text','feedback_deferred':True,'official_cefr':False}

def curriculum(s):
    validate(s);need(s['placement_closed'] and s['goal'] is not None,'placement and goal required')
    profile=placement_profile(s)['skills'];g=s['goal'];minutes=g['minutes']*g['days'];q,rem=divmod(minutes,4)
    return {'status':'proposed_plan','domain':g['domain'],'target_band':g['target'],'situations':g['situations'],
        'weekly_minutes':minutes,'strand_minutes':{k:q+int(i<rem) for i,k in enumerate(STRANDS)},
        'starting_bands':{k:profile[k]['working_band'] for k in s['available']},'unmeasured_skills':[k for k in SKILLS if not profile[k]['working_band']],
        'official_cefr':False,'duration_to_goal_prediction':None,'heuristic':True}

def _study_evidence(s,day):
    """Separate interaction history, observed grading and exact-content familiarity.

    A recorded fingerprint is not proof of actual exposure or semantic novelty.
    Count first recorded successful content only for diversity-based interval growth
    and band promotion; familiar successful recall still starts a base review interval.
    """
    seen=set();rows=[];by_scope=defaultdict(list)
    for e in s['events']:
        t=e['task'];p=e['result'];fp=t['fingerprint'];first=fp not in seen;seen.add(fp)
        if e['stage']!='study':continue
        d=iso(p['date']);need(d<=day,'review date precedes latest performance')
        graded=p['outcome']=='completed' and p['evidence_origin']==('observed_audio' if t['modality']=='audio' else 'observed_text')
        row=(e,first,graded);rows.append(row);by_scope[(t['skill'],t['objective'])].append(row)
    return rows,by_scope


def _review_records(by_scope,day):
    due=[]
    for (skill,obj),history in by_scope.items():
        graded=[(e,first) for e,first,is_graded in history if is_graded]
        if not graded:continue
        e,_=graded[-1];p=e['result'];t=e['task'];d=iso(p['date']);successful=passes(t,p)
        # Skips, ungraded interactions and reported history cannot replace or
        # interrupt observed grading. An actual unsuccessful graded attempt can.
        distinct_days=set()
        for row,first in reversed(graded):
            if not passes(row['task'],row['result']):break
            if first:distinct_days.add(row['result']['date'])
        interval=(1,3,7,14,30)[min(max(len(distinct_days)-1,0),4)] if successful else 0
        try:when=d+timedelta(days=interval)
        except OverflowError:raise LanguageError('review date out of range') from None
        if when>day:continue
        last,_,last_graded=history[-1]
        deferred_today=(not last_graded and last['result']['evidence_origin']!='reported' and last['result']['outcome'] in ('skipped','ungraded') and iso(last['result']['date'])==day)
        distinct=sum(first and passes(row['task'],row['result']) for row,first in graded)
        familiar=sum(not first and passes(row['task'],row['result']) for row,first in graded)
        evidence={'last_graded_task_id':t['id'],'last_graded_date':d.isoformat(),
                  'last_graded_outcome':'unaided_success' if successful else ('assisted' if p['assistance']!='none' else 'needs_repair'),
                  'distinct_recorded_content_successes':distinct,'previously_recorded_content_successes':familiar,
                  'distinct_success_days_in_streak':len(distinct_days),'interval_days':interval,
                  'semantic_novelty_verified':False,'mastery_verified':False}
        due.append({'activity':'spaced_retrieval' if successful else 'diagnose_and_repair',
                    'skill':skill,'objective':obj,'band':t['band'],'due_date':when.isoformat(),
                    'novel_task_required':True,'heuristic':True,'deferred_today':deferred_today,
                    'review_evidence':evidence})
    # Rotate other due objectives ahead of today's skipped/ungraded item, but
    # keep the original debt visible. If only deferred items remain, let the
    # learner choose to pause or switch explicitly; never auto-credit the skip.
    return sorted(due,key=lambda r:(r['deferred_today'],r['due_date'],r['skill'],r['objective']))


def next_study(s,today):
    validate(s);need(s['phase']=='study','not in study');day=iso(today)
    if s['pending'] is not None:return {'activity':'await_response','task':copy.deepcopy(s['pending'])}
    g=s['goal'];profile=placement_profile(s)['skills'];classified,by_scope=_study_evidence(s,day)
    rows=[e for e,_,_ in classified];due=_review_records(by_scope,day)
    if due:
        result=due[0].copy()
        result['due_review_count']=len(due)
        result['deferred_due_count']=sum(r['deferred_today'] for r in due)
        return result
    counts={k:sum(e['task']['strand']==k for e in rows[-16:]) for k in STRANDS};strand=min(STRANDS,key=lambda k:(counts[k],STRANDS.index(k)))
    preferred={'meaning_input':('reading','listening'),'meaning_output':('writing','spoken_production','mediation','written_interaction','spoken_interaction'),'language_focus':('writing','phonology','reading','listening','written_interaction','mediation','spoken_interaction','spoken_production'),'fluency':('spoken_interaction','written_interaction','spoken_production','writing','reading','listening','mediation','phonology')}[strand]
    options=[k for k in preferred if k in s['available']] or s['available'];skill=min(options,key=lambda k:sum(e['task']['skill']==k for e in rows[-16:]))
    band=profile[skill]['working_band'] or 'A1'
    prior=[(e,first) for e,first,_ in classified if e['task']['skill']==skill and eligible(e['task'],e['result'])]
    promotion=False
    if prior:
        last,first=prior[-1];band=last['task']['band'];i=LEVELS.index(band)
        if not passes(last['task'],last['result']):band=LEVELS[max(0,i-1)]
        elif len(prior)>=2:
            earlier,earlier_first=prior[-2]
            # Exact repeats (including content recorded during placement, under
            # another objective, or in imported history) cannot promote a band.
            if first and earlier_first and earlier['task']['band']==band and passes(earlier['task'],earlier['result']):
                target=LEVELS[min(i+1,LEVELS.index(g['target']))] if i<=LEVELS.index(g['target']) else band
                promotion=target!=band;band=target
    return {'activity':'goal_task','domain':g['domain'],'situations':g['situations'],'strand':strand,'skill':skill,'band':band,'modality':'audio' if skill in AUDIO else 'text','heuristic':True,'official_cefr':False,
            'practice_evidence':{'distinct_recorded_content_successes':sum(first and passes(e['task'],e['result']) for e,first in prior),'previously_recorded_content_successes':sum(not first and passes(e['task'],e['result']) for e,first in prior),'band_probe_promoted':promotion,'semantic_novelty_verified':False,'mastery_verified':False}}

def transition(s,event):
    validate(s);fields(event,('id','expected_revision','kind'),('task','task_id','result','goal'))
    identifier(event['id']);integer(event['expected_revision'],0,2000)
    kind=event['kind'];need(kind in ('issue','respond','finish_placement','set_goal','pause','resume','complete'),'invalid language event')
    expected={'issue':{'task'},'respond':{'task_id','result'},'set_goal':{'goal'}}.get(kind,set())
    need(set(event)-{'id','expected_revision','kind'}==expected,'unexpected event payload')
    if event['id'] in s['action_ids'] or event['expected_revision']!=s['revision']:
        return {'status':'stale','state':copy.deepcopy(s),'changed':False,'evidence_credit':False}
    n=copy.deepcopy(s);phase=n['phase'];p=n['pending']
    if kind=='issue':
        need(phase in ('placement','study') and p is None,'one active language task');task_check(event['task'],n['available']);n['pending']=copy.deepcopy(event['task'])
    elif kind=='respond':
        need(phase in ('placement','study') and p is not None,'no pending language task');need(event['task_id']==p['id'],'response does not match pending task');rubric_check(p,event['result'],phase=='placement')
        need(n['history_trust']=='current_context','explicit session recovery needed before new observations')
        n['events'].append({'stage':phase,'task':p,'result':copy.deepcopy(event['result'])});n['pending']=None
    elif kind=='finish_placement':
        need(phase=='placement','not in placement');n['pending']=None;n['placement_closed']=True;n['phase']='goal'
    elif kind=='set_goal':
        need(phase in ('goal','study') and p is None,'finish or pause current task first');goal_check(event['goal']);n['goal']=copy.deepcopy(event['goal']);n['phase']='study'
    elif kind=='pause':
        need(phase in ('placement','goal','study'),'cannot pause current phase');n['paused_from']=phase;n['phase']='paused'
    elif kind=='resume':
        need(phase=='paused','no paused session');n['phase']=n['paused_from'];n['paused_from']=None
        if n['history_trust']=='reported':
            # Old prompts/answers cannot establish new exposure-free placement.
            n['pending']=None;n['history_trust']='current_context'
    elif kind=='complete':
        need(phase=='study' and p is None,'complete requires no pending task');n['phase']='complete'
    n['revision']+=1;n['action_ids'].append(event['id']);validate(n)
    return {'status':'valid_transition','state':n,'changed':True,'evidence_credit':False,'semantic_grading_verified':False}

def recover(s):
    validate(s);n=copy.deepcopy(s);n['history_trust']='reported';n['pending']=None
    for e in n['events']:e['result']['evidence_origin']='reported'
    if n['phase']!='complete':
        if n['phase']!='paused':n['paused_from']=n['phase']
        n['phase']='paused'
    return validate(n)

def guard_companions(checkpoint=None,ledger=None):
    """Optional checked companion lock. Missing snapshots cannot prove exclusivity."""
    if checkpoint is not None:
        from ult_state import validate as validate_course
        from ult_policy import course_active_slots
        validate_course(checkpoint);need(not course_active_slots(checkpoint),'pause or exit active course assessment first')
    if ledger is not None:
        from ult_exam import validate as validate_exam
        from ult_policy import ledger_active
        validate_exam(ledger,checkpoint);need(not ledger_active(ledger),'pause or exit active exam assessment first')

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('command',choices=('new','validate','apply','next','profile','plan','recover'));p.add_argument('path');p.add_argument('--event');p.add_argument('--today');p.add_argument('--checkpoint');p.add_argument('--ledger');a=p.parse_args()
    try:
        s=read_json(a.path,LIMIT,max_nodes=50000)
        event=read_json(a.event,16000,max_nodes=5000) if a.command=='apply' and a.event else None
        if a.command in ('new','next') or (a.command=='apply' and isinstance(event,dict) and event.get('kind') not in ('pause','complete')):
            guard_companions(read_json(a.checkpoint,2_000_000) if a.checkpoint else None,read_json(a.ledger,5_000_000) if a.ledger else None)
        if a.command=='new':
            fields(s,('target_language','support_language'),('available','starting_band'));r=new(**s)
        elif a.command=='apply':need(a.event is not None,'event file required');r=transition(s,event)
        elif a.command=='next':r=next_placement(s) if s['phase']=='placement' else next_study(s,a.today)
        elif a.command=='profile':r=placement_profile(s)
        elif a.command=='plan':r=curriculum(s)
        elif a.command=='recover':r=recover(s)
        else:validate(s);r={'valid':True,'history_authenticated':False}
        raw=json.dumps(r,ensure_ascii=True,allow_nan=False);need(len(raw.encode())<=LIMIT,'language output limit; export a smaller scope');print(raw);return 0
    except (OSError,ValueError,TypeError,KeyError,RecursionError,OverflowError) as e:
        print(json.dumps({'status':'invalid','error':safe_error(e)},ensure_ascii=True));return 2
if __name__=='__main__':raise SystemExit(main())

SHA-256: 909e33db10e2d8a8a34729ecd80f0f46730e7a5944320c750c4fe119baa9f85e