Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

fal-unit-rate.ts

224 lines6.9 KB

1/**
2 * FAL Pricing sections are overwhelmingly a single unit rate —
3 * `- **Price**: $0.04 per megapixels`, `Your request will cost **$0.08** per
4 * image.`, `**$0.045/sec**`. Compile those without an LLM (issue #70); only
5 * the genuinely multi-rate pages fall through to the extract model.
6 */
7import { compileUnitCard } from '@modelschemas/rate-card'
8import type { RateCard } from '@modelschemas/rate-card'
9​
10import { compileFalTokenCard } from './fal-token-rate.ts'
11​
12/** `$0.04`, `$**0.04**`, `**0.17** $` — FAL emits all three. */
13const MONEY = String.raw`(?:\$[ \t]*\*{0,2}[ \t]*([0-9]+(?:\.[0-9]+)?)[ \t]*\*{0,2}|\*{0,2}[ \t]*([0-9]+(?:\.[0-9]+)?)[ \t]*\*{0,2}[ \t]*\$)`
14​
15function moneyRe(): RegExp {
16 return new RegExp(MONEY, 'g')
18​
19function amountOf(match: RegExpExecArray): number {
20 return Number(match[1] ?? match[2])
22​
23/** Every positive USD amount named anywhere in the section. */
24export function usdAmounts(section: string): Array<number> {
25 const found: Array<number> = []
26 for (const match of section.matchAll(moneyRe())) {
27 const amount = amountOf(match)
28 if (Number.isFinite(amount) && amount > 0) found.push(amount)
29 }
30 return found
32​
33/** `$X per [N] <unit>` or `$X/<unit>`, the money in any of the three spellings.
34 * Up to four words so "per output video second" still finds a known unit. */
35const UNIT_RATE = new RegExp(
36 `${MONEY}[ \\t]*(?:per[ \\t]+|/)\\*{0,2}[ \\t]*([0-9][0-9,]*)?[ \\t]*\\*{0,2}[ \\t]*([A-Za-z]+(?:[ \\t]+[A-Za-z]+){0,3})`,
37 'gi',
39​
40/**
41 * Unit phrase → the card's quantity param. Anything not listed falls
42 * through to the LLM rather than being guessed at.
43 */
44const UNIT_PARAMS: Record<string, string> = {
45 second: 'seconds',
46 seconds: 'seconds',
47 sec: 'seconds',
48 secs: 'seconds',
49 'compute second': 'compute_seconds',
50 'compute seconds': 'compute_seconds',
51 'gpu second': 'compute_seconds',
52 'gpu seconds': 'compute_seconds',
53 'input second': 'input_seconds',
54 'input seconds': 'input_seconds',
55 'audio second': 'audio_seconds',
56 'audio seconds': 'audio_seconds',
57 'video second': 'video_seconds',
58 'video seconds': 'video_seconds',
59 minute: 'minutes',
60 minutes: 'minutes',
61 'compute minute': 'compute_minutes',
62 'compute minutes': 'compute_minutes',
63 'audio minute': 'audio_minutes',
64 'audio minutes': 'audio_minutes',
65 image: 'images',
66 images: 'images',
67 megapixel: 'megapixels',
68 megapixels: 'megapixels',
69 character: 'characters',
70 characters: 'characters',
71 word: 'words',
72 words: 'words',
73 generation: 'generations',
74 generations: 'generations',
75 video: 'videos',
76 videos: 'videos',
77 frame: 'frames',
78 frames: 'frames',
79 page: 'pages',
80 pages: 'pages',
81 request: 'requests',
82 requests: 'requests',
83 run: 'requests',
84 runs: 'requests',
86​
87export interface FalUnitRate {
88 /** USD for `count` units. */
89 amount: number
90 count: number
91 /** Card input param the quantity binds to. */
92 param: string
93 /** The line the rate was read from, for the example's `quote`. */
94 quote: string
96​
97function lineAt(section: string, index: number): string {
98 const start = section.lastIndexOf('\n', index) + 1
99 const end = section.indexOf('\n', index)
100 return section.slice(start, end < 0 ? section.length : end).trim()
102​
103function paramFor(unit: string): string | undefined {
104 const words = unit
105 .toLowerCase()
106 .replace(/[ \t]+/g, ' ')
107 .trim()
108 .split(' ')
109 .filter((word) => word.length > 0)
110 let best: string | undefined
111 let bestLen = 0
112 for (let i = 0; i < words.length; i++) {
113 const room = words.length - i
114 for (let len = 1; len <= room && len <= 4; len++) {
115 const param = UNIT_PARAMS[words.slice(i, i + len).join(' ')]
116 if (param !== undefined && len > bestLen) {
117 best = param
118 bestLen = len
119 }
120 }
121 }
122 return best
124​
125/**
126 * The section's single unit rate, or `null` when it names more than one
127 * price, no price, or a unit we do not have a param for. Deliberately
128 * fail-closed: a page with several rates is a table the LLM should read.
129 */
130/**
131 * "For **$1.00**, you can run this model **25 times.**" restates the same
132 * rate as a reciprocal. Drop it before counting distinct prices, or every
133 * page carrying it would look multi-rate. The quote still comes from the
134 * untouched text.
135 */
136const RECIPROCAL = /For[ \t]+\*{0,2}\$1(?:\.0{1,2})?\*{0,2}[^.]*\.(?:\*{0,2})/gi
137​
138export function parseFalUnitRate(section: string): FalUnitRate | null {
139 const amounts = usdAmounts(section.replace(RECIPROCAL, ''))
140 if (amounts.length === 0) return null
141 if (new Set(amounts).size > 1) return null
142​
143 let rate: FalUnitRate | null = null
144 for (const match of section.matchAll(UNIT_RATE)) {
145 const amount = amountOf(match)
146 if (!Number.isFinite(amount) || amount <= 0) return null
147 const param = paramFor(match[4] ?? '')
148 if (param === undefined) return null
149 const count = Number((match[3] ?? '1').replace(/,/g, ''))
150 if (!Number.isFinite(count) || count <= 0) return null
151 const next: FalUnitRate = {
152 amount,
153 count,
154 param,
155 quote: lineAt(section, match.index),
156 }
157 // A repeated sentence is fine; two different rates are a table.
158 if (
159 rate &&
160 (rate.amount !== amount || rate.count !== count || rate.param !== param)
161 ) {
162 return null
163 }
164 rate ??= next
165 }
166 return rate
168​
169/**
170 * Compile the section's unit rate into a card with a synthesized one-unit
171 * example quoting the source line, so `verifyExamples` has something real
172 * to check. `null` when the section is not this shape.
173 */
174export function compileFalUnitCard(
175 section: string,
176 requestProperties: ReadonlySet<string>,
177 source: RateCard['source'],
178): RateCard | null {
179 const rate = parseFalUnitRate(section)
180 if (rate === null) return null
181 const card = compileUnitCard(
182 {
183 quantity: {
184 param: rate.param,
185 // Only a real request field may be request-bound (#68); everything
186 // else is a usage quantity the caller supplies.
187 bound: requestProperties.has(rate.param) ? 'request' : 'usage',
188 },
189 rates: rate.amount / rate.count,
190 },
191 source,
192 )
193 if (card === null) return null
194 return {
195 ...card,
196 examples: [
197 {
198 params: { [rate.param]: rate.count },
199 usd: rate.amount,
200 quote: rate.quote,
201 },
202 ],
203 }
205​
206/**
207 * Unit-rate card when the Pricing section names a positive dollar amount
208 * in a single known unit (issue #114). Empty text, all zeros, and
209 * "see pricing page" name no amount, so they stay null. A named price the
210 * unit-rate path cannot stand behind also stays null — no invented card.
211 */
212export function priceFalNamedSection(
213 section: string,
214 requestProperties: ReadonlySet<string>,
215 source: RateCard['source'],
216): RateCard | null {
217 if (usdAmounts(section).length === 0) return null
218 // Unit rate first: a per-image line must not be reread as tokens.
219 // Token sections name "units" or "tokens", which this unit list refuses.
220 return (
221 compileFalUnitCard(section, requestProperties, source) ??
222 compileFalTokenCard(section, source)
223 )