Open History to see the last commit
1/**
2 * Seed Speech rate cards (#672). BytePlus prices the voice product on its
3 * own billing pages, not the ModelArk pricing page:
4 *
5 * - Seed Audio 1.0: pay-as-you-go USD per minute of generated audio,
6 * metered by the second. The API page states the billed quantity: the
7 * response's `original_duration` (seconds before `speech_rate`), "with a
8 * maximum of 120s". That number exists only in the response, so the card
9 * carries the published maximum as its estimate: an upper bound a caller
10 * can hold before the request runs. BytePlus publishes no way to get
11 * seconds from `text_prompt`, so none is made up here.
12 * - Seed ASR: the catalog row is the flash endpoint
13 * (`volc.seedasr.auc_turbo`), which the billing page prices as "Audio
14 * File ASR Fast Mode", USD per hour of audio.
15 *
16 * Pre-paid packages are not a per-request price and are ignored. Each page
17 * is loaded through `tryDocs`: one that fails or stops parsing keeps the
18 * stored card and is reported in `docsFailures`.
19 */
20import { compileUnitCard } from '@modelschemas/rate-card'
21import type { RateCard } from '@modelschemas/rate-card'
22
23import { fetchByteplusDoc } from './byteplus-docs.ts'
24import { pricingContent, tableRows } from './byteplus-pricing.ts'
25import type { ByteplusDoc } from './byteplus-pricing.ts'
26import { tagDocsFacts } from './fact-sources.ts'
27import { tryDocs, unavailable } from './model-facts.ts'
28import type { DocsRun } from './model-facts.ts'
29import { sha256Text } from './types.ts'
30import type { ModelInfo } from './types.ts'
31
32const VOICE_DOCS = 'https://docs.byteplus.com/en/docs/byteplusvoice'
33export const BYTEPLUS_AUDIO_PRICING_URL = `${VOICE_DOCS}/audiopricing`
34export const BYTEPLUS_AUDIO_API_URL = `${VOICE_DOCS}/seedaudio-01`
35export const BYTEPLUS_ASR_PRICING_URL = `${VOICE_DOCS}/asrbilling`
36
37const SECONDS_PER_UNIT: Array<[RegExp, number]> = [
38 [/\bminute$/i, 60],
39 [/\bhour$/i, 3600],
40]
41
42interface SpeechRate {
43 /** The text line above the table ("Audio File ASR Fast Mode"). */
44 label: string
45 usdPerSecond: number
46}
47
48/**
49 * The pay-as-you-go row of every `Payment | Fee (USD) | Unit` table on a
50 * voice billing page. A table with those columns whose pay-as-you-go row
51 * cannot be read throws; a table without them is not a price table.
52 */
53export function parseSpeechRates(doc: ByteplusDoc): Array<SpeechRate> {
54 const out: Array<SpeechRate> = []
55 let text = ''
56 for (const op of doc.data['0']?.ops ?? []) {
57 const spec = op.attributes?.aceTable
58 if (!spec) {
59 if (typeof op.insert === 'string') text += op.insert
60 continue
61 }
62 const label =
63 text
64 .split('\n')
65 .map((line) => line.replace(/^\*+/, '').trim())
66 .filter((line) => line !== '')
67 .at(-1)
68 ?.replace(/:$/, '') ?? ''
69 text = ''
70 const rows = tableRows(doc, spec)
71 const header = rows?.[0]?.map((cell) => cell.toLowerCase()) ?? []
72 const payment = header.indexOf('payment')
73 const fee = header.indexOf('fee (usd)')
74 const unit = header.indexOf('unit')
75 if (!rows || payment < 0 || fee < 0 || unit < 0) continue
76 const row = rows.find((cells) =>
77 /^pay-as-you-go$/i.test(cells[payment] ?? ''),
78 )
79 const usd = /^\d+(?:\.\d+)?$/.test(row?.[fee] ?? '')
80 ? Number(row?.[fee])
81 : 0
82 const seconds = SECONDS_PER_UNIT.find(([pattern]) =>
83 pattern.test(row?.[unit] ?? ''),
84 )?.[1]
85 if (!row || usd <= 0 || !seconds) {
86 throw new Error(
87 `byteplus speech pricing: unreadable pay-as-you-go row under "${label}": ${JSON.stringify(row ?? null)}`,
88 )
89 }
90 // 0.15 / 60 is 0.0025000000000000005: drop the float noise.
91 out.push({ label, usdPerSecond: Number((usd / seconds).toPrecision(12)) })
92 }
93 return out
94}
95
96/** Seed Audio 1.0 USD per second: the page's only price table. */
97export function parseSeedAudioRate(doc: ByteplusDoc): number {
98 const rates = parseSpeechRates(doc)
99 const [only] = rates
100 if (!only || rates.length !== 1) {
101 throw new Error(
102 `byteplus audio pricing: ${String(rates.length)} price tables, expected 1`,
103 )
104 }
105 return only.usdPerSecond
106}
107
108/** Seed ASR flash USD per second: the "Audio File ASR Fast Mode" table. */
109export function parseSeedAsrRate(doc: ByteplusDoc): number {
110 const fast = parseSpeechRates(doc).filter(
111 (rate) => rate.label.toLowerCase() === 'audio file asr fast mode',
112 )
113 const [only] = fast
114 if (!only || fast.length !== 1) {
115 throw new Error(
116 `byteplus asr pricing: ${String(fast.length)} "Audio File ASR Fast Mode" tables, expected 1`,
117 )
118 }
119 return only.usdPerSecond
120}
121
122/** The billed-seconds maximum the Seed Audio API page states for `original_duration`. */
123export function parseSeedAudioCap(doc: ByteplusDoc): number {
124 const text = Object.values(doc.data)
125 .flatMap((zone) => zone.ops ?? [])
126 .map((op) => (typeof op.insert === 'string' ? op.insert : ''))
127 .join('')
128 const cap = /duration used for billing, with a maximum of (\d+)\s*s\b/.exec(
129 text,
130 )?.[1]
131 if (!cap) {
132 throw new Error(
133 'byteplus audio api page: no "duration used for billing, with a maximum of Ns"',
134 )
135 }
136 return Number(cap)
137}
138
139interface CachedNumber {
140 value: number
141 hash: string
142 extractedAt: string
143}
144
145/** One number read off one voice docs page, or null (counted in `run`). */
146function pageNumber(
147 run: DocsRun,
148 kv: KVNamespace | undefined,
149 url: string,
150 read: (doc: ByteplusDoc) => number,
151): Promise<CachedNumber | null> {
152 return tryDocs(run, url, (cached) =>
153 cached<CachedNumber>(kv, url, async () => {
154 const content = pricingContent(
155 await fetchByteplusDoc(url),
156 `byteplus speech page ${url}`,
157 )
158 return {
159 value: read(JSON.parse(content) as ByteplusDoc),
160 hash: await sha256Text(content),
161 extractedAt: new Date().toISOString(),
162 }
163 }),
164 )
165}
166
167/** Billed on `original_duration`; omitted, it is estimated at the published maximum. */
168export function compileSeedAudioCard(
169 usdPerSecond: number,
170 cap: { seconds: number; url: string; hash: string },
171 source: RateCard['source'],
172): RateCard {
173 return {
174 inputs: {
175 original_duration: {
176 param: 'original_duration',
177 bound: 'usage',
178 kind: 'number',
179 estimate: {
180 inputs: {},
181 value: cap.seconds,
182 source: { url: cap.url, hash: cap.hash },
183 },
184 },
185 },
186 tables: {},
187 price: { '*': [{ var: 'original_duration' }, usdPerSecond] },
188 examples: [],
189 source,
190 }
191}
192
193type SpeechFacts = Pick<
194 ModelInfo,
195 'pricing' | 'factSources' | 'serverTools' | 'absent'
196>
197
198/** Card lookup for the Seed Speech rows; null for every other id. */
199export async function byteplusSpeechPricing(
200 run: DocsRun,
201 kv?: KVNamespace,
202): Promise<(rawId: string) => SpeechFacts | null> {
203 const [audio, cap, asr] = await Promise.all([
204 pageNumber(run, kv, BYTEPLUS_AUDIO_PRICING_URL, parseSeedAudioRate),
205 pageNumber(run, kv, BYTEPLUS_AUDIO_API_URL, parseSeedAudioCap),
206 pageNumber(run, kv, BYTEPLUS_ASR_PRICING_URL, parseSeedAsrRate),
207 ])
208 const facts = (
209 page: CachedNumber | null,
210 url: string,
211 pricing: RateCard | null,
212 ): SpeechFacts =>
213 page && pricing
214 ? { pricing, factSources: tagDocsFacts({ pricing }, url, page.hash) }
215 : unavailable('pricing')
216 const source = (page: CachedNumber, url: string): RateCard['source'] => ({
217 url,
218 hash: page.hash,
219 extractedAt: page.extractedAt,
220 })
221 const cards: Record<string, SpeechFacts> = {
222 'seed-audio-1.0': facts(
223 audio,
224 BYTEPLUS_AUDIO_PRICING_URL,
225 audio && cap
226 ? compileSeedAudioCard(
227 audio.value,
228 { seconds: cap.value, url: BYTEPLUS_AUDIO_API_URL, hash: cap.hash },
229 source(audio, BYTEPLUS_AUDIO_PRICING_URL),
230 )
231 : null,
232 ),
233 'seed-asr': facts(
234 asr,
235 BYTEPLUS_ASR_PRICING_URL,
236 asr &&
237 compileUnitCard(
238 {
239 quantity: { param: 'audio_seconds', bound: 'usage' },
240 rates: asr.value,
241 },
242 source(asr, BYTEPLUS_ASR_PRICING_URL),
243 ),
244 ),
245 }
246 return (rawId) => cards[rawId] ?? null
247}