fix(openai): prompt engineering and transcript model
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
"""Offline, provider-free scoring of human-reviewed Phase 1 speech observations."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import unicodedata
|
||||
|
||||
NORMALIZATION = 'persian-wer-v1'
|
||||
|
||||
def tokens(text):
|
||||
if not isinstance(text,str):
|
||||
raise ValueError('Transcript must be a string')
|
||||
text=unicodedata.normalize('NFC',text).translate(str.maketrans({'ي':'ی','ك':'ک','\u200c':' '}))
|
||||
chars=[]
|
||||
for i,char in enumerate(text):
|
||||
if char.isdecimal():
|
||||
char=str(unicodedata.decimal(char))
|
||||
# Preserve identifier separators and numeric punctuation: AC-42, 1.5, 1405/07.
|
||||
internal=(char in '-_/.:,٫٬' and i>0 and i+1<len(text)
|
||||
and text[i-1].isalnum() and text[i+1].isalnum())
|
||||
value_symbol = char in '%٪+−' or (char == '-' and i+1<len(text) and text[i+1].isdecimal())
|
||||
chars.append(' ' if unicodedata.category(char).startswith('P') and not internal and not value_symbol else char)
|
||||
return ''.join(chars).split()
|
||||
|
||||
def word_errors(reference,hypothesis):
|
||||
"""Return substitutions/deletions/insertions, with a deterministic minimum edit alignment."""
|
||||
ref,hyp=tokens(reference),tokens(hypothesis)
|
||||
if not ref:
|
||||
raise ValueError('A nonempty human reference is required')
|
||||
if max(len(ref),len(hyp))>4096:
|
||||
raise ValueError('Speech token bound exceeded')
|
||||
previous=[(j,0,0,j) for j in range(len(hyp)+1)]
|
||||
for i,word in enumerate(ref,1):
|
||||
current=[(i,0,i,0)]
|
||||
for j,heard in enumerate(hyp,1):
|
||||
if word==heard:
|
||||
current.append(previous[j-1])
|
||||
else:
|
||||
cost,s,d,ins=previous[j-1];sub=(cost+1,s+1,d,ins)
|
||||
cost,s,d,ins=previous[j];delete=(cost+1,s,d+1,ins)
|
||||
cost,s,d,ins=current[-1];insert=(cost+1,s,d,ins+1)
|
||||
current.append(min((sub,delete,insert),key=lambda x:x[0]))
|
||||
previous=current
|
||||
cost,s,d,ins=previous[-1]
|
||||
return dict(reference_words=len(ref),substitutions=s,deletions=d,insertions=ins,
|
||||
errors=cost,wer=cost/len(ref))
|
||||
|
||||
def percentile(values,p):
|
||||
if not values:return None
|
||||
values=sorted(values);position=(len(values)-1)*p
|
||||
low=math.floor(position);high=math.ceil(position)
|
||||
return values[low]+(values[high]-values[low])*(position-low)
|
||||
|
||||
def finite_metric(value):
|
||||
if type(value) not in (int,float) or not math.isfinite(value) or value<0:
|
||||
raise ValueError('Nonnegative measured metric required')
|
||||
return value
|
||||
|
||||
def indexed(rows):
|
||||
result={}
|
||||
for row in rows:
|
||||
key=row['sample_id']
|
||||
if key in result:raise ValueError('Duplicate sample identity')
|
||||
result[key]=row
|
||||
return result
|
||||
|
||||
def score(manifest,annotations,observations,*,split='held_out',root=Path('.')):
|
||||
"""Score only supplied observations. Null prerequisites never become passing evidence."""
|
||||
planned=indexed(manifest['samples']);labels=indexed(annotations['annotations'])
|
||||
measured=indexed(observations['observations'])
|
||||
profile=observations['effective_profile']
|
||||
digest=hashlib.sha256(json.dumps(profile,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()
|
||||
if observations['effective_profile_sha256']!=digest:
|
||||
raise ValueError('Effective profile digest mismatch')
|
||||
if any(key not in planned for key in measured) or any(key not in planned for key in labels):
|
||||
raise ValueError('Unknown sample identity')
|
||||
selected=[s for s in planned.values() if s['split']==split]
|
||||
rows=[];missing=[];speakers=set();groups={}
|
||||
thresholds={'quiet':.10,'office':.15,'moderate_noise':.25}
|
||||
for sample in selected:
|
||||
key=sample['sample_id'];label=labels.get(key);observation=measured.get(key)
|
||||
if not label or not observation or label.get('review_status')!='approved' or not label.get('reviewed_by'):
|
||||
missing.append(key);continue
|
||||
if not sample.get('consent_reference') or not sample.get('speaker_id') or sample.get('native_iranian_persian') is not True:
|
||||
missing.append(key);continue
|
||||
path=sample.get('recording_path');expected=sample.get('recording_sha256')
|
||||
if not path or not expected or not sample.get('duration_seconds'):
|
||||
missing.append(key);continue
|
||||
recording=root/path
|
||||
if not recording.is_file() or hashlib.sha256(recording.read_bytes()).hexdigest()!=expected:
|
||||
raise ValueError('Recording missing or digest mismatch: '+key)
|
||||
finite_metric(sample['duration_seconds'])
|
||||
if observation.get('effective_profile_sha256')!=digest or not observation.get('session_reference'):
|
||||
raise ValueError('Observation profile/session identity required')
|
||||
result=word_errors(label['reference_text'],observation['final_transcript'])
|
||||
critical=label.get('critical_facts',[])
|
||||
ids=[fact['fact_id'] for fact in critical]
|
||||
if len(set(ids))!=len(ids) or any(f.get('kind') not in ('number','date','identifier','negation') or not f.get('literal') for f in critical):
|
||||
raise ValueError('Invalid designated critical facts')
|
||||
judgments=observation.get('critical_fact_results')
|
||||
if judgments is None or set(judgments)!=set(ids) or any(type(v) is not bool for v in judgments.values()):
|
||||
raise ValueError('Human critical fact judgments required')
|
||||
if critical and not observation.get('critical_reviewed_by'):
|
||||
raise ValueError('Critical fact reviewer required')
|
||||
critical_errors=sum(not value for value in judgments.values())
|
||||
completion=finite_metric(observation['completion_delay_ms'])
|
||||
response=finite_metric(observation['response_latency_ms'])
|
||||
for name in ('segmentation_errors','truncated_transcripts'):
|
||||
if type(observation.get(name)) is not int or observation[name]<0:
|
||||
raise ValueError('Measured error count required')
|
||||
result.update(sample_id=key,condition=sample['condition'],critical_errors=critical_errors,
|
||||
completion_delay_ms=completion,response_latency_ms=response,
|
||||
empty_transcripts=int(not observation['final_transcript'].strip()),
|
||||
segmentation_errors=observation['segmentation_errors'],
|
||||
truncated_transcripts=observation['truncated_transcripts'])
|
||||
rows.append(result);speakers.add(sample['speaker_id'])
|
||||
group=groups.setdefault(sample['condition'],Counter())
|
||||
for name in ('reference_words','errors','critical_errors','empty_transcripts','segmentation_errors','truncated_transcripts'):
|
||||
group[name]+=result[name]
|
||||
group['samples']+=1
|
||||
for condition,group in groups.items():
|
||||
group['wer']=group['errors']/group['reference_words']
|
||||
group['wer_gate']='passed' if group['wer']<=thresholds[condition] else 'failed'
|
||||
group['critical_gate']='passed' if group['critical_errors']==0 else 'failed'
|
||||
# Full planned cohort prerequisites must hold even when scoring held-out speech.
|
||||
cohort=Counter(s.get('condition') for s in planned.values())
|
||||
splits=Counter(s.get('split') for s in planned.values())
|
||||
all_speakers={s['speaker_id'] for s in planned.values() if s.get('speaker_id')}
|
||||
cohort_ready=(len(planned)==30 and cohort==Counter(quiet=10,office=10,moderate_noise=10)
|
||||
and splits==Counter(development=20,held_out=10) and len(all_speakers)>=3
|
||||
and all(s.get('native_iranian_persian') is True and s.get('consent_reference')
|
||||
and s.get('recording_path') and s.get('recording_sha256') and s.get('duration_seconds')
|
||||
and labels.get(s['sample_id'],{}).get('review_status')=='approved'
|
||||
and labels.get(s['sample_id'],{}).get('reviewed_by')
|
||||
and labels.get(s['sample_id'],{}).get('reference_text')
|
||||
for s in planned.values())
|
||||
and all(any(s['condition']==condition and s['split']==split
|
||||
and labels.get(s['sample_id'],{}).get('critical_facts') for s in planned.values())
|
||||
for condition in ('quiet','office'))
|
||||
and all(any(s['split']==part and s['condition']==condition for s in planned.values())
|
||||
for part in ('development','held_out') for condition in thresholds))
|
||||
failed=any(g['wer_gate']=='failed' or (c!='moderate_noise' and g['critical_gate']=='failed') for c,g in groups.items())
|
||||
status='failed' if failed else 'blocked' if missing or not cohort_ready or not selected else 'passed'
|
||||
return dict(normalization=NORMALIZATION,split=split,effective_profile=profile,effective_profile_sha256=digest,
|
||||
asr_accuracy_status=status,phase_acceptance_status='not_run', # frontend/pause evidence is separate
|
||||
cohort_ready=cohort_ready,missing_samples=missing,scored_samples=len(rows),
|
||||
groups=groups,rows=rows,
|
||||
completion_delay_ms=dict(p50=percentile([r['completion_delay_ms'] for r in rows],.5),
|
||||
p95=percentile([r['completion_delay_ms'] for r in rows],.95)),
|
||||
response_latency_ms=dict(p50=percentile([r['response_latency_ms'] for r in rows],.5),
|
||||
p95=percentile([r['response_latency_ms'] for r in rows],.95)),
|
||||
usage=observations.get('usage'),cost=observations.get('cost'),
|
||||
provider_authorization=observations.get('provider_authorization'))
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--manifest',type=Path,required=True)
|
||||
parser.add_argument('--annotations',type=Path,required=True)
|
||||
parser.add_argument('--observations',type=Path,required=True)
|
||||
parser.add_argument('--split',choices=('development','held_out'),default='held_out')
|
||||
args=parser.parse_args()
|
||||
try:
|
||||
documents=[json.loads(p.read_text(encoding='utf-8')) for p in (args.manifest,args.annotations,args.observations)]
|
||||
result=score(*documents,split=args.split,root=args.manifest.parent)
|
||||
except (ValueError,KeyError,TypeError,OSError) as exc:
|
||||
parser.exit(2,'Speech scoring failed: '+str(exc)+'\n')
|
||||
print(json.dumps(result,ensure_ascii=False,indent=2))
|
||||
return 0 if result['asr_accuracy_status']=='passed' else 1
|
||||
|
||||
if __name__=='__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user