fix(openai): prompt engineering and transcript model
This commit is contained in:
@@ -4,7 +4,9 @@ from urllib.parse import quote
|
||||
|
||||
from app.modules.knowledge.service import SearchInput
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.configuration import OpenAIInputSettings
|
||||
from app.modules.voice.serialization import bounded_json
|
||||
from app.modules.voice.openai_style import effective_instructions
|
||||
|
||||
class ProviderProtocolError(ValueError):
|
||||
pass
|
||||
@@ -35,10 +37,17 @@ def strict_json(raw):
|
||||
|
||||
class RealtimeAdapter:
|
||||
def __init__(self, transport, *, model="gpt-realtime-mini", voice="shimmer",
|
||||
no_active_classifier=None, settings=None):
|
||||
no_active_classifier=None, settings=None, input_settings=None):
|
||||
self.settings = settings or RuntimeSettings()
|
||||
if not isinstance(self.settings, RuntimeSettings):
|
||||
raise ValueError("Validated runtime settings required")
|
||||
input_settings = input_settings if input_settings is not None else OpenAIInputSettings()
|
||||
if not isinstance(input_settings, OpenAIInputSettings):
|
||||
raise ValueError('Validated OpenAI input settings required')
|
||||
# Revalidate copies too: Pydantic model_copy deliberately bypasses validation.
|
||||
self.input_settings = OpenAIInputSettings.model_validate({
|
||||
key: getattr(input_settings, key) for key in OpenAIInputSettings.model_fields})
|
||||
self.reasoning = self.input_settings.reasoning(model)
|
||||
self.transport, self.model, self.voice = transport, model, voice
|
||||
# The default classifier is restricted to the empirically verified
|
||||
# OpenAI profile below. Other profiles require separate acceptance.
|
||||
@@ -46,12 +55,10 @@ class RealtimeAdapter:
|
||||
|
||||
def setup(self):
|
||||
return dict(type="session.update", session=dict(
|
||||
type="realtime", model=self.model, instructions=POLICY,
|
||||
type="realtime", model=self.model, instructions=effective_instructions(POLICY),
|
||||
**({"reasoning": self.reasoning.copy()} if self.reasoning is not None else {}),
|
||||
output_modalities=["audio"], tool_choice="auto",
|
||||
audio=dict(input=dict(format=dict(type="audio/pcm", rate=24000),
|
||||
transcription=dict(model="whisper-1", language="fa"),
|
||||
turn_detection=dict(type="server_vad", create_response=False,
|
||||
interrupt_response=False)),
|
||||
audio=dict(input=self.input_settings.audio_input(),
|
||||
output=dict(format=dict(type="audio/pcm", rate=24000), voice=self.voice)),
|
||||
tools=[dict(type="function", name="search_knowledge",
|
||||
description="Retrieve evidence from authorized selected documents.",
|
||||
@@ -67,8 +74,22 @@ class RealtimeAdapter:
|
||||
if isinstance(wanted, list):
|
||||
return isinstance(actual, list) and len(actual) == len(wanted) and all(
|
||||
contains(a, w) for a, w in zip(actual, wanted))
|
||||
if type(wanted) is float:
|
||||
return type(actual) in (int, float) and actual == wanted
|
||||
return type(actual) is type(wanted) and actual == wanted
|
||||
return contains(session, expected)
|
||||
if not contains(session, expected):
|
||||
return False
|
||||
if self.reasoning is None and session.get('reasoning') is not None:
|
||||
return False
|
||||
if session['audio']['input']['turn_detection'].get('idle_timeout_ms') is not None:
|
||||
return False
|
||||
transcription = session['audio']['input']['transcription']
|
||||
# The provider must not silently enable a conflicting language mode.
|
||||
empty_defaults = dict(language=(None,), languages=(None, []),
|
||||
prompt=(None, ''), keywords=(None, []))
|
||||
return all(key not in transcription or transcription[key] in empty_defaults[key]
|
||||
for key in empty_defaults
|
||||
if key not in expected['audio']['input']['transcription'])
|
||||
|
||||
def serialize(self, event):
|
||||
return bounded_json(event, self.settings.max_provider_message_bytes, ensure_ascii=False)
|
||||
|
||||
@@ -6,12 +6,19 @@ from app.infrastructure.realtime import RealtimeAdapter, connect as connect_open
|
||||
|
||||
async def create_adapter(config, limits):
|
||||
config.require_voice()
|
||||
input_settings = None
|
||||
if config.provider == 'openai':
|
||||
from app.modules.voice.configuration import OpenAIInputSettings
|
||||
input_settings = OpenAIInputSettings.model_validate({
|
||||
key: getattr(config, key) for key in OpenAIInputSettings.model_fields})
|
||||
input_settings.reasoning(config.selected_model)
|
||||
connect = connect_gemini if config.provider == 'gemini' else connect_openai
|
||||
transport = await asyncio.wait_for(connect(config.selected_key.get_secret_value(),
|
||||
config.selected_model, config.selected_proxy, limits), limits.connect_timeout_seconds)
|
||||
try:
|
||||
adapter = GeminiLiveAdapter if config.provider == 'gemini' else RealtimeAdapter
|
||||
return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits)
|
||||
return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits,
|
||||
**({'input_settings': input_settings} if config.provider == 'openai' else {}))
|
||||
except BaseException:
|
||||
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
|
||||
raise
|
||||
|
||||
@@ -3,11 +3,82 @@ import ipaddress
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
from pydantic import AliasChoices, Field, SecretStr, field_validator, model_validator
|
||||
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class VoiceSettings(BaseSettings):
|
||||
class OpenAIInputSettings(BaseModel):
|
||||
"""Bounded operator configuration for committed-turn ASR and server VAD."""
|
||||
model_config = dict(frozen=True, extra='forbid', hide_input_in_errors=True)
|
||||
openai_realtime_reasoning_effort: Literal['low', 'medium'] | None = None
|
||||
openai_realtime_asr_model: Literal['whisper-1', 'gpt-transcribe'] = 'whisper-1'
|
||||
openai_realtime_asr_language: Literal['fa', 'en'] | None = 'fa'
|
||||
openai_realtime_asr_languages: tuple[Literal['fa', 'en'], ...] = ()
|
||||
openai_realtime_asr_prompt: str = Field(default='', max_length=1024)
|
||||
openai_realtime_asr_keywords: tuple[str, ...] = Field(default=(), max_length=64)
|
||||
openai_realtime_vad_threshold: float = Field(default=0.5, ge=0, le=1, allow_inf_nan=False)
|
||||
openai_realtime_vad_prefix_padding_ms: int = Field(default=300, ge=0, le=2000)
|
||||
openai_realtime_vad_silence_duration_ms: int = Field(default=500, ge=100, le=2000)
|
||||
openai_realtime_noise_reduction: Literal['near_field', 'far_field'] | None = None
|
||||
|
||||
@field_validator('openai_realtime_asr_language', 'openai_realtime_noise_reduction',
|
||||
'openai_realtime_reasoning_effort', mode='before')
|
||||
@classmethod
|
||||
def optional_input_setting(cls, value):
|
||||
return None if value == 'null' else value
|
||||
|
||||
@field_validator('openai_realtime_asr_keywords')
|
||||
@classmethod
|
||||
def vocabulary(cls, values):
|
||||
if len(set(values)) != len(values):
|
||||
raise ValueError('Duplicate ASR keywords')
|
||||
for word in values:
|
||||
if not word.strip() or len(word) > 100 or any(c in word for c in '<>\r\n'):
|
||||
raise ValueError('Invalid ASR keyword')
|
||||
return values
|
||||
|
||||
@model_validator(mode='after')
|
||||
def asr_combination(self):
|
||||
languages = self.openai_realtime_asr_languages
|
||||
if len(set(languages)) != len(languages):
|
||||
raise ValueError('Duplicate ASR languages')
|
||||
if self.openai_realtime_asr_model == 'whisper-1':
|
||||
if languages or self.openai_realtime_asr_keywords:
|
||||
raise ValueError('Plural languages and keywords require gpt-transcribe')
|
||||
elif self.openai_realtime_asr_language is not None:
|
||||
raise ValueError('gpt-transcribe requires plural languages; set singular language to null')
|
||||
if self.openai_realtime_asr_language is not None and languages:
|
||||
raise ValueError('Conflicting ASR language fields')
|
||||
return self
|
||||
|
||||
def reasoning(self, model):
|
||||
effort = self.openai_realtime_reasoning_effort
|
||||
if effort is not None and effort not in ('low', 'medium'):
|
||||
raise ValueError('Unsupported reasoning effort')
|
||||
if effort is not None and model not in ('gpt-realtime-2.1', 'gpt-realtime-2.1-mini'):
|
||||
raise ValueError('Reasoning effort requires a supported OpenAI Realtime model')
|
||||
return None if effort is None else dict(effort=effort)
|
||||
|
||||
def audio_input(self):
|
||||
transcription = dict(model=self.openai_realtime_asr_model)
|
||||
if self.openai_realtime_asr_language is not None:
|
||||
transcription['language'] = self.openai_realtime_asr_language
|
||||
if self.openai_realtime_asr_languages:
|
||||
transcription['languages'] = list(self.openai_realtime_asr_languages)
|
||||
if self.openai_realtime_asr_prompt:
|
||||
transcription['prompt'] = self.openai_realtime_asr_prompt
|
||||
if self.openai_realtime_asr_keywords:
|
||||
transcription['keywords'] = list(self.openai_realtime_asr_keywords)
|
||||
return dict(format=dict(type='audio/pcm', rate=24000), transcription=transcription,
|
||||
turn_detection=dict(type='server_vad', create_response=False, interrupt_response=False,
|
||||
threshold=self.openai_realtime_vad_threshold,
|
||||
prefix_padding_ms=self.openai_realtime_vad_prefix_padding_ms,
|
||||
silence_duration_ms=self.openai_realtime_vad_silence_duration_ms),
|
||||
noise_reduction=None if self.openai_realtime_noise_reduction is None else
|
||||
dict(type=self.openai_realtime_noise_reduction))
|
||||
|
||||
|
||||
class VoiceSettings(OpenAIInputSettings, BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
|
||||
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
||||
gemini_api_key: SecretStr = SecretStr('')
|
||||
@@ -64,6 +135,8 @@ class VoiceSettings(BaseSettings):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def cookie_policy(self):
|
||||
if self.provider == 'openai':
|
||||
self.reasoning(self.openai_realtime_model)
|
||||
for o in self.trusted_origins:
|
||||
h = urlsplit(o).hostname
|
||||
if not self.cookie_secure:
|
||||
@@ -122,5 +195,12 @@ class VoiceSettings(BaseSettings):
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
|
||||
def profile(self):
|
||||
return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
||||
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
|
||||
profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
||||
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
|
||||
if self.provider == 'openai':
|
||||
profile['audio_input'] = self.audio_input()
|
||||
profile['reasoning'] = self.reasoning(self.selected_model)
|
||||
from app.infrastructure.realtime import POLICY
|
||||
from app.modules.voice.openai_style import instruction_profile
|
||||
profile.update(instruction_profile(POLICY))
|
||||
return profile
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Fixed OpenAI delivery revision; no document facts or unreviewed examples."""
|
||||
from hashlib import sha256
|
||||
|
||||
STYLE_REVISION = 'iranian-persian-professional-v1'
|
||||
STYLE = """Delivery style (subordinate to the grounding policy above):
|
||||
Speak standard Iranian Persian in a respectful, professional conversational tone.
|
||||
Use natural pronunciation, short complete sentences, moderate pacing, and brief
|
||||
pauses between meaningful clauses. Avoid repeated greetings, ceremonial wording,
|
||||
excessive filler, and a radio-announcer persona.
|
||||
Pronounce technical English terms clearly. Preserve exact identifiers, quantities,
|
||||
dates, conditions, exclusions, and negation; never simplify away material meaning.
|
||||
When clarification is needed, ask one concise question in Persian.
|
||||
For no_evidence, explain in Persian that the available document evidence is
|
||||
insufficient; do not claim that the fact is false or that a technical failure occurred.
|
||||
For error, explain in Persian that a technical problem prevented checking the
|
||||
documents; do not describe it as absence of evidence or supply a fallback answer.
|
||||
Explain conflicting evidence faithfully and briefly. Delivery never overrides
|
||||
fresh retrieval, source mistrust, authorization, or faithful grounding."""
|
||||
|
||||
|
||||
def effective_instructions(policy):
|
||||
return policy + '\n\n' + STYLE
|
||||
|
||||
|
||||
def instruction_profile(policy):
|
||||
return dict(style_revision=STYLE_REVISION,
|
||||
effective_instructions_digest=sha256(
|
||||
effective_instructions(policy).encode('utf-8')).hexdigest())
|
||||
@@ -1483,6 +1483,10 @@ class VoiceRuntime:
|
||||
audio.done = True
|
||||
self.wake.set()
|
||||
elif kind.startswith("conversation.item.input_audio_transcription."):
|
||||
if kind not in ("conversation.item.input_audio_transcription.delta",
|
||||
"conversation.item.input_audio_transcription.completed",
|
||||
"conversation.item.input_audio_transcription.failed"):
|
||||
raise ValueError("Unknown input transcription event")
|
||||
turn = self.inputs[event["item_id"]]
|
||||
if type(event["content_index"]) is not int or event["content_index"] != 0:
|
||||
raise ValueError("Input transcript layout")
|
||||
@@ -1499,6 +1503,8 @@ class VoiceRuntime:
|
||||
# Only index zero is supported: one fixed-size completion
|
||||
# per retained input mapping, bounded by max_input_turns.
|
||||
turn.transcript_parts[index] = fingerprint
|
||||
elif event['content_index'] in turn.transcript_parts:
|
||||
raise ValueError('Input transcript delta after completion')
|
||||
self.control(dict(type="transcript", turn_ref=turn.ref, role="user",
|
||||
text=text, status="completed" if kind.endswith("completed") else "partial"))
|
||||
elif kind.endswith("failed"):
|
||||
|
||||
@@ -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