"""Generate guarded media price changes from the captured APIPro quote (no network).""" import argparse import json from decimal import Decimal, ROUND_HALF_UP from pathlib import Path FIXED = { 'grok-imagine-image-quality': '5.6', 'gemini-2.5-flash-image-c': '5.6', 'gemini-3-pro-image-preview-c': '5.6', 'gemini-3.1-flash-image-preview-c': '5.6', 'gpt-image-2-c': '5.6', 'gpt-image-2-pro': '5.6', 'qwen-image-2.0-pro': '6.5', 'qwen-image-max': '6.5', } TOKENS = { 'gemini-2.5-flash-image', 'gemini-3-pro-image', 'gemini-3-pro-image-preview', 'gemini-3.1-flash-image', 'gemini-3.1-flash-image-preview', 'gemini-3.1-flash-lite-image', 'gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst', } def number(value): return float(Decimal(str(value)).quantize(Decimal('.00000001'), rounding=ROUND_HALF_UP)) def changes(catalog, source): quotes = {row['model_name']: row for row in source['data']} result = [] for model in catalog: name = model['model'] if model['provider'] != 'apipro' or model['deleted'] or model['type'] != 'image' or model['mode'] != 'async': continue quote = quotes.get(name) if name in FIXED and model['pricing'] is None: assert quote and quote['quota_type'] == 1 and quote['model_price'] > 0 discount = Decimal(FIXED[name]) price = {'unit': 'CNY / image', 'price': number(Decimal(str(quote['model_price'])) * Decimal('7.2') * discount / 10), 'discount': float(discount), 'discountLabel': f'{discount}折', 'exchangeRate': 7.2, 'standardPrice': {'price': quote['model_price'], 'unit': 'USD / image'}, 'priceSource': 'APIPro 模型广场 2026-10-13,单张请求'} elif name in TOKENS and model['pricing']: assert quote and quote['quota_type'] == 0 price = dict(model['pricing']) usd_input = Decimal(str(quote['model_ratio'])) * 2 usd_output = usd_input * Decimal(str(quote['completion_ratio'])) # Do not activate a route if a newer quote conflicts with its stored rate. for field, raw in [('input', usd_input), ('output', usd_output)]: assert number(price[field]) == number(raw * Decimal('7.2') * Decimal('.56')), name price['taskBilling'] = 'gemini-image-tokens' if name.startswith('gemini') else 'openai-image-tokens' if quote.get('image_ratio') is not None: price['imageInput'] = number(usd_input * Decimal(str(quote['image_ratio'])) * Decimal('7.2') * Decimal('.56')) price['listPriceUsd'] = dict(price['listPriceUsd'], imageInput=number(usd_input * Decimal(str(quote['image_ratio'])))) price['usageSource'] = 'provider-reported-only' else: continue result.append({'id': model['id'], 'model': name, 'before': model['pricing'], 'after': price}) assert len(result) == len(FIXED) + len(TOKENS), f'Expected 17 exact routes, got {len(result)}' return result def main(): args = argparse.ArgumentParser() args.add_argument('--sources', type=Path, required=True) args.add_argument('--migration', type=Path, required=True) opt = args.parse_args() plan = changes(json.loads((opt.sources/'catalog.json').read_text(encoding='utf-8')), json.loads((opt.sources/'apipro.json').read_text(encoding='utf-8'))) def literal(value): return "'" + json.dumps(value, ensure_ascii=False, separators=(',', ':')).replace("'", "''") + "'::jsonb" rows = [] for row in plan: old = 'NULL' if row['before'] is None else literal(row['before']) rows.append(f"('{row['id']}', '{row['model']}', {old}, {literal(row['after'])})") sql = "-- Exact old-price guards preserve administrator edits; no enable-state or wallet changes.\n" sql += "WITH reviewed(id,upstream_model,old_price,new_price) AS (VALUES\n" + ',\n'.join(rows) + ")\n" sql += "UPDATE model_catalog m SET pricing=r.new_price,updated_at=now() FROM reviewed r,model_providers p\n" sql += "WHERE m.id=r.id AND m.upstream_model=r.upstream_model AND m.provider_id=p.id AND p.code='apipro'\n" sql += "AND m.deleted_at IS NULL AND m.model_type='image' AND m.call_mode='async' AND m.pricing IS NOT DISTINCT FROM r.old_price;\n" opt.migration.write_text(sql, encoding='utf-8') (opt.sources/'media-price-changes.json').write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding='utf-8') print(f'Prepared {len(plan)} guarded changes (8 missing prices, 9 usage billing configurations).') if __name__ == '__main__': main()