@aeye/models 0.3.9 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReplicateScrape.md +290 -290
- package/aeye-models.md +23 -10
- package/dist/scripts/codegen.d.ts +4 -0
- package/dist/scripts/codegen.d.ts.map +1 -1
- package/dist/scripts/codegen.js +57 -46
- package/dist/scripts/codegen.js.map +1 -1
- package/dist/scripts/scrape.d.ts +2 -1
- package/dist/scripts/scrape.d.ts.map +1 -1
- package/dist/scripts/scrape.js +8 -4
- package/dist/scripts/scrape.js.map +1 -1
- package/dist/scripts/scrapers/aws.d.ts +5 -1
- package/dist/scripts/scrapers/aws.d.ts.map +1 -1
- package/dist/scripts/scrapers/aws.js +211 -57
- package/dist/scripts/scrapers/aws.js.map +1 -1
- package/dist/scripts/scrapers/docs.d.ts +43 -0
- package/dist/scripts/scrapers/docs.d.ts.map +1 -0
- package/dist/scripts/scrapers/docs.js +91 -0
- package/dist/scripts/scrapers/docs.js.map +1 -0
- package/dist/scripts/scrapers/openai.d.ts +4 -1
- package/dist/scripts/scrapers/openai.d.ts.map +1 -1
- package/dist/scripts/scrapers/openai.js +183 -445
- package/dist/scripts/scrapers/openai.js.map +1 -1
- package/dist/scripts/scrapers/openrouter.d.ts +1 -1
- package/dist/scripts/scrapers/openrouter.d.ts.map +1 -1
- package/dist/scripts/scrapers/openrouter.js +20 -79
- package/dist/scripts/scrapers/openrouter.js.map +1 -1
- package/dist/scripts/scrapers/replicate.js +140 -140
- package/dist/src/models/aws.d.ts.map +1 -1
- package/dist/src/models/aws.js +2180 -1033
- package/dist/src/models/aws.js.map +1 -1
- package/dist/src/models/openai.d.ts.map +1 -1
- package/dist/src/models/openai.js +1925 -1370
- package/dist/src/models/openai.js.map +1 -1
- package/dist/src/models/openrouter.d.ts.map +1 -1
- package/dist/src/models/openrouter.js +15699 -4981
- package/dist/src/models/openrouter.js.map +1 -1
- package/dist/src/strict-support.d.ts +2 -1
- package/dist/src/strict-support.d.ts.map +1 -1
- package/dist/src/strict-support.js +38 -16
- package/dist/src/strict-support.js.map +1 -1
- package/dist/src/transformers/replicate/black-forest-labs-flux-1-1-pro.js +1 -1
- package/dist/src/transformers/replicate/black-forest-labs-flux-1-1-pro.js.map +1 -1
- package/dist/src/transformers/replicate/black-forest-labs-flux-pro.js +1 -1
- package/dist/src/transformers/replicate/black-forest-labs-flux-pro.js.map +1 -1
- package/dist/src/transformers/replicate/openai-gpt-image-1.js +1 -1
- package/dist/src/transformers/replicate/openai-gpt-image-1.js.map +1 -1
- package/package.json +6 -7
- package/scripts/codegen.ts +133 -121
- package/scripts/patch-modelinfo.ts +139 -139
- package/scripts/scrape.ts +190 -182
- package/scripts/scrapers/__tests__/aws.test.ts +86 -86
- package/scripts/scrapers/aws.ts +276 -107
- package/scripts/scrapers/docs.ts +101 -0
- package/scripts/scrapers/extract.md +270 -270
- package/scripts/scrapers/openai.ts +252 -619
- package/scripts/scrapers/openrouter.ts +131 -217
- package/scripts/scrapers/replicate.ts +1144 -1144
- package/scripts/tsconfig.json +25 -25
- package/src/index.ts +12 -12
- package/src/models/aws.ts +2180 -1033
- package/src/models/openai.ts +1925 -1370
- package/src/models/openrouter.ts +19708 -8990
- package/src/models/replicate.ts +9101 -9101
- package/src/strict-support.ts +39 -16
- package/src/transformers/index.ts +25 -25
- package/src/transformers/replicate/abiruyt-text-extract-ocr.ts +31 -31
- package/src/transformers/replicate/adidoes-whisperx-video-transcribe.ts +36 -36
- package/src/transformers/replicate/adirik-e5-mistral-7b-instruct.ts +39 -39
- package/src/transformers/replicate/adirik-kosmos-g.ts +47 -47
- package/src/transformers/replicate/adirik-owlvit-base-patch32.ts +34 -34
- package/src/transformers/replicate/adirik-realvisxl-v3-0-turbo.ts +84 -84
- package/src/transformers/replicate/adirik-styletts2.ts +41 -41
- package/src/transformers/replicate/adirik-udop-large.ts +22 -22
- package/src/transformers/replicate/afiaka87-tortoise-tts.ts +30 -30
- package/src/transformers/replicate/ai-forever-kandinsky-2-2.ts +53 -53
- package/src/transformers/replicate/ai-forever-kandinsky-2.ts +61 -61
- package/src/transformers/replicate/alexgenovese-upscaler.ts +28 -28
- package/src/transformers/replicate/andreasjansson-blip-2.ts +37 -37
- package/src/transformers/replicate/andreasjansson-clip-features.ts +31 -31
- package/src/transformers/replicate/andreasjansson-llama-2-13b-embeddings.ts +32 -32
- package/src/transformers/replicate/andreasjansson-musicgen-looper.ts +68 -68
- package/src/transformers/replicate/anthropic-claude-3-5-sonnet.ts +70 -70
- package/src/transformers/replicate/anthropic-claude-3-7-sonnet.ts +63 -63
- package/src/transformers/replicate/anthropic-claude-4-sonnet.ts +77 -77
- package/src/transformers/replicate/arielreplicate-deoldify_image.ts +29 -29
- package/src/transformers/replicate/awerks-neon-tts.ts +27 -27
- package/src/transformers/replicate/awilliamson10-meta-nougat.ts +25 -25
- package/src/transformers/replicate/beautyyuyanli-multilingual-e5-large.ts +30 -30
- package/src/transformers/replicate/black-forest-labs-flux-1-1-pro-ultra.ts +46 -46
- package/src/transformers/replicate/black-forest-labs-flux-1-1-pro.ts +61 -61
- package/src/transformers/replicate/black-forest-labs-flux-2-dev.ts +73 -73
- package/src/transformers/replicate/black-forest-labs-flux-2-flex.ts +50 -50
- package/src/transformers/replicate/black-forest-labs-flux-2-pro.ts +66 -66
- package/src/transformers/replicate/black-forest-labs-flux-canny-dev.ts +50 -50
- package/src/transformers/replicate/black-forest-labs-flux-canny-pro.ts +46 -46
- package/src/transformers/replicate/black-forest-labs-flux-depth-dev.ts +39 -39
- package/src/transformers/replicate/black-forest-labs-flux-depth-pro.ts +34 -34
- package/src/transformers/replicate/black-forest-labs-flux-dev-lora.ts +63 -63
- package/src/transformers/replicate/black-forest-labs-flux-dev.ts +54 -54
- package/src/transformers/replicate/black-forest-labs-flux-fill-dev.ts +43 -43
- package/src/transformers/replicate/black-forest-labs-flux-fill-pro.ts +41 -41
- package/src/transformers/replicate/black-forest-labs-flux-kontext-dev.ts +36 -36
- package/src/transformers/replicate/black-forest-labs-flux-kontext-max.ts +45 -45
- package/src/transformers/replicate/black-forest-labs-flux-kontext-pro.ts +45 -45
- package/src/transformers/replicate/black-forest-labs-flux-pro-finetuned.ts +69 -69
- package/src/transformers/replicate/black-forest-labs-flux-pro-trainer.ts +39 -39
- package/src/transformers/replicate/black-forest-labs-flux-pro.ts +77 -77
- package/src/transformers/replicate/black-forest-labs-flux-redux-dev.ts +46 -46
- package/src/transformers/replicate/black-forest-labs-flux-redux-schnell.ts +39 -39
- package/src/transformers/replicate/black-forest-labs-flux-schnell.ts +40 -40
- package/src/transformers/replicate/bria-eraser.ts +35 -35
- package/src/transformers/replicate/bria-expand-image.ts +40 -40
- package/src/transformers/replicate/bria-fibo.ts +45 -45
- package/src/transformers/replicate/bria-generate-background.ts +41 -41
- package/src/transformers/replicate/bria-genfill.ts +48 -48
- package/src/transformers/replicate/bria-image-3-2.ts +33 -33
- package/src/transformers/replicate/bria-increase-resolution.ts +32 -32
- package/src/transformers/replicate/bytedance-bagel.ts +74 -74
- package/src/transformers/replicate/bytedance-dolphin.ts +36 -36
- package/src/transformers/replicate/bytedance-flux-pulid.ts +82 -82
- package/src/transformers/replicate/bytedance-pulid.ts +78 -78
- package/src/transformers/replicate/bytedance-sdxl-lightning-4step.ts +55 -55
- package/src/transformers/replicate/bytedance-seededit-3-0.ts +31 -31
- package/src/transformers/replicate/bytedance-seedream-3.ts +52 -52
- package/src/transformers/replicate/bytedance-seedream-4.ts +59 -59
- package/src/transformers/replicate/camenduru-metavoice.ts +28 -28
- package/src/transformers/replicate/center-for-curriculum-redesign-bge_1-5_query_embeddings.ts +35 -35
- package/src/transformers/replicate/chenxwh-openvoice.ts +40 -40
- package/src/transformers/replicate/chigozienri-mediapipe-face.ts +31 -31
- package/src/transformers/replicate/cjwbw-bigcolor.ts +42 -42
- package/src/transformers/replicate/cjwbw-canary-1b.ts +22 -22
- package/src/transformers/replicate/cjwbw-cogvlm.ts +35 -35
- package/src/transformers/replicate/cjwbw-docentr.ts +37 -37
- package/src/transformers/replicate/cjwbw-face-align-cog.ts +35 -35
- package/src/transformers/replicate/cjwbw-internlm-xcomposer.ts +29 -29
- package/src/transformers/replicate/cjwbw-night-enhancement.ts +35 -35
- package/src/transformers/replicate/cjwbw-parler-tts.ts +28 -28
- package/src/transformers/replicate/cjwbw-real-esrgan.ts +28 -28
- package/src/transformers/replicate/cjwbw-rudalle-sr.ts +37 -37
- package/src/transformers/replicate/cjwbw-seamless_communication.ts +83 -83
- package/src/transformers/replicate/cjwbw-supir-v0f.ts +45 -45
- package/src/transformers/replicate/cjwbw-supir-v0q.ts +44 -44
- package/src/transformers/replicate/cjwbw-supir.ts +47 -47
- package/src/transformers/replicate/cjwbw-voicecraft.ts +62 -62
- package/src/transformers/replicate/cjwbw-vqfr.ts +39 -39
- package/src/transformers/replicate/codeplugtech-object_remover.ts +31 -31
- package/src/transformers/replicate/codeslake-ifan-defocus-deblur.ts +35 -35
- package/src/transformers/replicate/comfyui-any-comfyui-workflow.ts +41 -41
- package/src/transformers/replicate/cswry-seesr.ts +39 -39
- package/src/transformers/replicate/cudanexus-ocr-surya.ts +44 -44
- package/src/transformers/replicate/curt-park-sentiment-analysis.ts +39 -39
- package/src/transformers/replicate/cuuupid-glm-4v-9b.ts +61 -61
- package/src/transformers/replicate/cuuupid-gte-qwen2-7b-instruct.ts +32 -32
- package/src/transformers/replicate/cuuupid-marker.ts +37 -37
- package/src/transformers/replicate/daanelson-imagebind.ts +45 -45
- package/src/transformers/replicate/daanelson-minigpt-4.ts +37 -37
- package/src/transformers/replicate/daanelson-whisperx.ts +39 -39
- package/src/transformers/replicate/datacte-proteus-v0-2.ts +85 -85
- package/src/transformers/replicate/datacte-proteus-v0-3.ts +77 -77
- package/src/transformers/replicate/datalab-to-marker.ts +63 -63
- package/src/transformers/replicate/datalab-to-ocr.ts +51 -51
- package/src/transformers/replicate/easel-advanced-face-swap.ts +35 -35
- package/src/transformers/replicate/easel-ai-avatars.ts +50 -50
- package/src/transformers/replicate/fermatresearch-high-resolution-controlnet-tile.ts +45 -45
- package/src/transformers/replicate/fermatresearch-magic-image-refiner.ts +53 -53
- package/src/transformers/replicate/fermatresearch-magic-style-transfer.ts +58 -58
- package/src/transformers/replicate/fermatresearch-sdxl-controlnet-lora.ts +58 -58
- package/src/transformers/replicate/fermatresearch-spanish-f5-tts.ts +36 -36
- package/src/transformers/replicate/fewjative-ultimate-sd-upscale.ts +55 -55
- package/src/transformers/replicate/flux-kontext-apps-change-haircut.ts +39 -39
- package/src/transformers/replicate/flux-kontext-apps-multi-image-kontext-max.ts +65 -65
- package/src/transformers/replicate/flux-kontext-apps-multi-image-kontext-pro.ts +65 -65
- package/src/transformers/replicate/flux-kontext-apps-multi-image-list.ts +54 -54
- package/src/transformers/replicate/flux-kontext-apps-professional-headshot.ts +37 -37
- package/src/transformers/replicate/flux-kontext-apps-restore-image.ts +31 -31
- package/src/transformers/replicate/fofr-become-image.ts +39 -39
- package/src/transformers/replicate/fofr-color-matcher.ts +36 -36
- package/src/transformers/replicate/fofr-deprecated-batch-image-captioning.ts +54 -54
- package/src/transformers/replicate/fofr-face-swap-with-ideogram.ts +28 -28
- package/src/transformers/replicate/fofr-face-to-many.ts +47 -47
- package/src/transformers/replicate/fofr-face-to-sticker.ts +40 -40
- package/src/transformers/replicate/fofr-latent-consistency-model.ts +79 -79
- package/src/transformers/replicate/fofr-prompt-classifier.ts +53 -53
- package/src/transformers/replicate/fofr-sdxl-emoji.ts +92 -92
- package/src/transformers/replicate/fofr-sdxl-multi-controlnet-lora.ts +110 -110
- package/src/transformers/replicate/fofr-sticker-maker.ts +54 -54
- package/src/transformers/replicate/georgedavila-bart-large-mnli-classifier.ts +36 -36
- package/src/transformers/replicate/google-gemini-2-5-flash.ts +90 -90
- package/src/transformers/replicate/google-gemini-3-pro.ts +91 -91
- package/src/transformers/replicate/google-imagen-3-fast.ts +32 -32
- package/src/transformers/replicate/google-imagen-3.ts +34 -34
- package/src/transformers/replicate/google-imagen-4-fast.ts +32 -32
- package/src/transformers/replicate/google-imagen-4-ultra.ts +32 -32
- package/src/transformers/replicate/google-imagen-4.ts +32 -32
- package/src/transformers/replicate/google-lyria-2.ts +28 -28
- package/src/transformers/replicate/google-nano-banana.ts +41 -41
- package/src/transformers/replicate/google-research-maxim.ts +38 -38
- package/src/transformers/replicate/google-upscaler.ts +29 -29
- package/src/transformers/replicate/grandlineai-instant-id-artistic.ts +61 -61
- package/src/transformers/replicate/grandlineai-instant-id-photorealistic.ts +35 -35
- package/src/transformers/replicate/ibm-granite-granite-embedding-278m-multilingual.ts +28 -28
- package/src/transformers/replicate/ideogram-ai-ideogram-character.ts +66 -66
- package/src/transformers/replicate/ideogram-ai-ideogram-v2-turbo.ts +51 -51
- package/src/transformers/replicate/ideogram-ai-ideogram-v2.ts +53 -53
- package/src/transformers/replicate/ideogram-ai-ideogram-v2a-turbo.ts +52 -52
- package/src/transformers/replicate/ideogram-ai-ideogram-v2a.ts +50 -50
- package/src/transformers/replicate/ideogram-ai-ideogram-v3-balanced.ts +82 -82
- package/src/transformers/replicate/ideogram-ai-ideogram-v3-quality.ts +77 -77
- package/src/transformers/replicate/ideogram-ai-ideogram-v3-turbo.ts +77 -77
- package/src/transformers/replicate/index.ts +612 -612
- package/src/transformers/replicate/j-min-clip-caption-reward.ts +38 -38
- package/src/transformers/replicate/jaaari-kokoro-82m.ts +31 -31
- package/src/transformers/replicate/jagilley-controlnet-scribble.ts +39 -39
- package/src/transformers/replicate/jingyunliang-hcflow-sr.ts +37 -37
- package/src/transformers/replicate/jingyunliang-swinir.ts +42 -42
- package/src/transformers/replicate/joehoover-instructblip-vicuna13b.ts +27 -27
- package/src/transformers/replicate/joehoover-mplug-owl.ts +24 -24
- package/src/transformers/replicate/juergengunz-ultimate-portrait-upscale.ts +55 -55
- package/src/transformers/replicate/krthr-clip-embeddings.ts +46 -46
- package/src/transformers/replicate/kshitijagrwl-pii-extractor-llm.ts +40 -40
- package/src/transformers/replicate/leonardoai-lucid-origin.ts +36 -36
- package/src/transformers/replicate/lucataco-ace-step.ts +41 -41
- package/src/transformers/replicate/lucataco-bakllava.ts +31 -31
- package/src/transformers/replicate/lucataco-codeformer.ts +33 -33
- package/src/transformers/replicate/lucataco-controlnet-tile.ts +34 -34
- package/src/transformers/replicate/lucataco-csm-1b.ts +40 -40
- package/src/transformers/replicate/lucataco-deepseek-ocr.ts +33 -33
- package/src/transformers/replicate/lucataco-demofusion-enhance.ts +43 -43
- package/src/transformers/replicate/lucataco-dreamshaper-xl-turbo.ts +55 -55
- package/src/transformers/replicate/lucataco-florence-2-base.ts +45 -45
- package/src/transformers/replicate/lucataco-fuyu-8b.ts +31 -31
- package/src/transformers/replicate/lucataco-gpt-oss-safeguard-20b.ts +50 -50
- package/src/transformers/replicate/lucataco-ip-adapter-faceid.ts +75 -75
- package/src/transformers/replicate/lucataco-ip_adapter-face-inpaint.ts +48 -48
- package/src/transformers/replicate/lucataco-ip_adapter-sdxl-face.ts +52 -52
- package/src/transformers/replicate/lucataco-llama-3-vision-alpha.ts +32 -32
- package/src/transformers/replicate/lucataco-magnet.ts +44 -44
- package/src/transformers/replicate/lucataco-modelscope-facefusion.ts +46 -46
- package/src/transformers/replicate/lucataco-moondream2.ts +32 -32
- package/src/transformers/replicate/lucataco-nomic-embed-text-v1.ts +28 -28
- package/src/transformers/replicate/lucataco-ollama-llama3-2-vision-11b.ts +37 -37
- package/src/transformers/replicate/lucataco-ollama-llama3-2-vision-90b.ts +47 -47
- package/src/transformers/replicate/lucataco-omnigen2.ts +43 -43
- package/src/transformers/replicate/lucataco-open-dalle-v1-1.ts +81 -81
- package/src/transformers/replicate/lucataco-orpheus-3b-0-1-ft.ts +38 -38
- package/src/transformers/replicate/lucataco-pasd-magnify.ts +35 -35
- package/src/transformers/replicate/lucataco-pheme.ts +33 -33
- package/src/transformers/replicate/lucataco-qwen-vl-chat.ts +30 -30
- package/src/transformers/replicate/lucataco-qwen2-5-omni-7b.ts +78 -78
- package/src/transformers/replicate/lucataco-qwen2-vl-7b-instruct.ts +43 -43
- package/src/transformers/replicate/lucataco-realistic-vision-v5-1.ts +50 -50
- package/src/transformers/replicate/lucataco-sdxl-clip-interrogator.ts +29 -29
- package/src/transformers/replicate/lucataco-smolvlm-instruct.ts +38 -38
- package/src/transformers/replicate/lucataco-snowflake-arctic-embed-l.ts +30 -30
- package/src/transformers/replicate/lucataco-ssd-1b.ts +76 -76
- package/src/transformers/replicate/lucataco-stable-diffusion-x4-upscaler.ts +30 -30
- package/src/transformers/replicate/lucataco-xtts-v2.ts +42 -42
- package/src/transformers/replicate/lucataco-xtts-v2.ts.invalid +31 -31
- package/src/transformers/replicate/luma-photon-flash.ts +47 -47
- package/src/transformers/replicate/luma-photon.ts +35 -35
- package/src/transformers/replicate/m1guelpf-whisper-subtitles.ts +46 -46
- package/src/transformers/replicate/mark3labs-embeddings-gte-base.ts +31 -31
- package/src/transformers/replicate/megvii-research-nafnet.ts +39 -39
- package/src/transformers/replicate/meta-musicgen.ts +53 -53
- package/src/transformers/replicate/methexis-inc-img2prompt.ts +43 -43
- package/src/transformers/replicate/mickeybeurskens-latex-ocr.ts +27 -27
- package/src/transformers/replicate/microsoft-bringing-old-photos-back-to-life.ts +38 -38
- package/src/transformers/replicate/minimax-image-01.ts +39 -39
- package/src/transformers/replicate/minimax-music-01.ts +35 -35
- package/src/transformers/replicate/minimax-music-1-5.ts +35 -35
- package/src/transformers/replicate/minimax-speech-02-hd.ts +52 -52
- package/src/transformers/replicate/minimax-speech-02-turbo.ts +52 -52
- package/src/transformers/replicate/minimax-voice-cloning.ts +36 -36
- package/src/transformers/replicate/mv-lab-instructir.ts +30 -30
- package/src/transformers/replicate/mv-lab-swin2sr.ts +37 -37
- package/src/transformers/replicate/nateraw-bge-large-en-v1-5.ts +37 -37
- package/src/transformers/replicate/nateraw-jina-embeddings-v2-base-en.ts +22 -22
- package/src/transformers/replicate/nicknaskida-whisper-diarization.ts +53 -53
- package/src/transformers/replicate/nightmareai-latent-sr.ts +40 -40
- package/src/transformers/replicate/nightmareai-real-esrgan.ts +28 -28
- package/src/transformers/replicate/nohamoamary-image-captioning-with-visual-attention.ts +29 -29
- package/src/transformers/replicate/nvidia-parakeet-rnnt-1-1b.ts +26 -26
- package/src/transformers/replicate/nvidia-sana-sprint-1-6b.ts +49 -49
- package/src/transformers/replicate/nvidia-sana.ts +62 -62
- package/src/transformers/replicate/openai-gpt-4-1-mini.ts +65 -65
- package/src/transformers/replicate/openai-gpt-4o-mini-transcribe.ts +32 -32
- package/src/transformers/replicate/openai-gpt-4o-mini.ts +72 -72
- package/src/transformers/replicate/openai-gpt-4o-transcribe.ts +36 -36
- package/src/transformers/replicate/openai-gpt-4o.ts +69 -69
- package/src/transformers/replicate/openai-gpt-5.ts +80 -80
- package/src/transformers/replicate/openai-gpt-image-1.ts +60 -60
- package/src/transformers/replicate/openai-whisper.ts +56 -56
- package/src/transformers/replicate/orpatashnik-styleclip.ts +40 -40
- package/src/transformers/replicate/pbevan1-llama-3-1-8b-ocr-correction.ts +56 -56
- package/src/transformers/replicate/pharmapsychotic-clip-interrogator.ts +37 -37
- package/src/transformers/replicate/philz1337x-clarity-upscaler.ts +56 -56
- package/src/transformers/replicate/philz1337x-crystal-upscaler.ts +29 -29
- package/src/transformers/replicate/piddnad-ddcolor.ts +28 -28
- package/src/transformers/replicate/platform-kit-mars5-tts.ts +38 -38
- package/src/transformers/replicate/playgroundai-playground-v2-5-1024px-aesthetic.ts +81 -81
- package/src/transformers/replicate/prunaai-flux-fast.ts +38 -38
- package/src/transformers/replicate/prunaai-flux-kontext-fast.ts +40 -40
- package/src/transformers/replicate/prunaai-hidream-l1-dev.ts +55 -55
- package/src/transformers/replicate/prunaai-hidream-l1-fast.ts +38 -38
- package/src/transformers/replicate/prunaai-hidream-l1-full.ts +61 -61
- package/src/transformers/replicate/prunaai-sdxl-lightning.ts +52 -52
- package/src/transformers/replicate/prunaai-wan-2-2-image.ts +36 -36
- package/src/transformers/replicate/qwen-qwen-image-edit-plus.ts +36 -36
- package/src/transformers/replicate/qwen-qwen-image-edit.ts +35 -35
- package/src/transformers/replicate/qwen-qwen-image.ts +67 -67
- package/src/transformers/replicate/recraft-ai-recraft-creative-upscale.ts +26 -26
- package/src/transformers/replicate/recraft-ai-recraft-crisp-upscale.ts +26 -26
- package/src/transformers/replicate/recraft-ai-recraft-v3-svg.ts +33 -33
- package/src/transformers/replicate/recraft-ai-recraft-v3.ts +33 -33
- package/src/transformers/replicate/replicate-all-mpnet-base-v2.ts +40 -40
- package/src/transformers/replicate/resemble-ai-chatterbox-multilingual.ts +43 -43
- package/src/transformers/replicate/resemble-ai-chatterbox-pro.ts +36 -36
- package/src/transformers/replicate/resemble-ai-chatterbox.ts +41 -41
- package/src/transformers/replicate/resemble-ai-chatterbox.ts.invalid +38 -38
- package/src/transformers/replicate/riffusion-riffusion.ts +35 -35
- package/src/transformers/replicate/rmokady-clip_prefix_caption.ts +47 -47
- package/src/transformers/replicate/runwayml-gen4-image-turbo.ts +34 -34
- package/src/transformers/replicate/runwayml-gen4-image.ts +44 -44
- package/src/transformers/replicate/sakemin-musicgen-chord.ts +46 -46
- package/src/transformers/replicate/sakemin-musicgen-remixer.ts +55 -55
- package/src/transformers/replicate/sakemin-musicgen-stereo-chord.ts +47 -47
- package/src/transformers/replicate/salesforce-blip.ts +46 -46
- package/src/transformers/replicate/sczhou-codeformer.ts +33 -33
- package/src/transformers/replicate/sdxl-based-realvisxl-v3-multi-controlnet-lora.ts +90 -90
- package/src/transformers/replicate/stability-ai-sdxl.ts +69 -69
- package/src/transformers/replicate/stability-ai-stable-audio-2-5.ts +33 -33
- package/src/transformers/replicate/stability-ai-stable-diffusion-3-5-large-turbo.ts +55 -55
- package/src/transformers/replicate/stability-ai-stable-diffusion-3-5-large.ts +73 -73
- package/src/transformers/replicate/stability-ai-stable-diffusion-3-5-medium.ts +47 -47
- package/src/transformers/replicate/stability-ai-stable-diffusion.ts +57 -57
- package/src/transformers/replicate/suno-ai-bark.ts +37 -37
- package/src/transformers/replicate/tencent-hunyuan-image-3.ts +35 -35
- package/src/transformers/replicate/tencentarc-gfpgan.ts +39 -39
- package/src/transformers/replicate/tencentarc-photomaker-style.ts +53 -53
- package/src/transformers/replicate/tencentarc-photomaker.ts +80 -80
- package/src/transformers/replicate/tencentarc-vqfr.ts +39 -39
- package/src/transformers/replicate/thomasmol-whisper-diarization.ts +44 -44
- package/src/transformers/replicate/topazlabs-image-upscale.ts +37 -37
- package/src/transformers/replicate/tstramer-material-diffusion.ts +85 -85
- package/src/transformers/replicate/vaibhavs10-incredibly-fast-whisper.ts +44 -44
- package/src/transformers/replicate/victor-upmeet-whisperx.ts +50 -50
- package/src/transformers/replicate/willywongi-donut.ts +26 -26
- package/src/transformers/replicate/x-lance-f5-tts.ts +47 -47
- package/src/transformers/replicate/xai-grok-4.ts +50 -50
- package/src/transformers/replicate/xinntao-esrgan.ts +35 -35
- package/src/transformers/replicate/yangxy-gpen.ts +41 -41
- package/src/transformers/replicate/yorickvp-llava-13b.ts +55 -55
- package/src/transformers/replicate/yorickvp-llava-v1-6-34b.ts +58 -58
- package/src/transformers/replicate/yorickvp-llava-v1-6-mistral-7b.ts +83 -83
- package/src/transformers/replicate/yorickvp-llava-v1-6-vicuna-13b.ts +108 -108
- package/src/transformers/replicate/zsxkib-aura-sr-v2.ts +32 -32
- package/src/transformers/replicate/zsxkib-aura-sr.ts +30 -30
- package/src/transformers/replicate/zsxkib-blip-3.ts +47 -47
- package/src/transformers/replicate/zsxkib-bsrgan.ts +28 -28
- package/src/transformers/replicate/zsxkib-dia.ts +42 -42
- package/src/transformers/replicate/zsxkib-diffbir.ts +57 -57
- package/src/transformers/replicate/zsxkib-flash-face.ts +47 -47
- package/src/transformers/replicate/zsxkib-flux-music.ts +36 -36
- package/src/transformers/replicate/zsxkib-idefics3.ts +96 -96
- package/src/transformers/replicate/zsxkib-instant-id.ts +58 -58
- package/src/transformers/replicate/zsxkib-jina-clip-v2.ts +47 -47
- package/src/transformers/replicate/zsxkib-molmo-7b.ts +54 -54
- package/src/transformers/replicate/zsxkib-realistic-voice-cloning.ts +54 -54
- package/src/transformers/replicate/zsxkib-seedvr2.ts +38 -38
- package/src/transformers/replicate/zsxkib-step1x-edit.ts +35 -35
- package/src/transformers/replicate/zsxkib-uform-gen.ts +29 -29
- package/src/transformers/replicate/zsyoaoa-invsr.ts +33 -33
- package/tsconfig.json +16 -16
- package/dist/scripts/_regen.d.ts +0 -2
- package/dist/scripts/_regen.d.ts.map +0 -1
- package/dist/scripts/_regen.js +0 -13
- package/dist/scripts/_regen.js.map +0 -1
|
@@ -1,1144 +1,1144 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Replicate Model Scraper
|
|
3
|
-
*
|
|
4
|
-
* Fetches model information from Replicate API using the Replicate npm module
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import type { ModelCapability, ModelInfo } from '@aeye/ai';
|
|
8
|
-
import { AI, detectTier } from '@aeye/ai';
|
|
9
|
-
import { OpenRouterProvider } from '@aeye/openrouter';
|
|
10
|
-
import * as fs from 'fs/promises';
|
|
11
|
-
import openapiTS from 'openapi-typescript';
|
|
12
|
-
import * as path from 'path';
|
|
13
|
-
import Replicate from 'replicate';
|
|
14
|
-
import ts from 'typescript';
|
|
15
|
-
import * as url from 'url';
|
|
16
|
-
import { z } from 'zod';
|
|
17
|
-
import { writeModelTS } from '../codegen';
|
|
18
|
-
import { exec, spawn } from 'child_process';
|
|
19
|
-
|
|
20
|
-
const __filename = url.fileURLToPath(import.meta.url);
|
|
21
|
-
const __dirname = path.dirname(__filename);
|
|
22
|
-
|
|
23
|
-
interface ReplicateModelData {
|
|
24
|
-
url: string;
|
|
25
|
-
owner: string;
|
|
26
|
-
name: string;
|
|
27
|
-
description: string | null;
|
|
28
|
-
visibility: string;
|
|
29
|
-
github_url: string | null;
|
|
30
|
-
paper_url: string | null;
|
|
31
|
-
license_url: string | null;
|
|
32
|
-
run_count: number;
|
|
33
|
-
cover_image_url: string | null;
|
|
34
|
-
default_example: {
|
|
35
|
-
model: string;
|
|
36
|
-
version: string;
|
|
37
|
-
input: Record<string, unknown>;
|
|
38
|
-
output: unknown;
|
|
39
|
-
} | null;
|
|
40
|
-
latest_version: {
|
|
41
|
-
id: string;
|
|
42
|
-
created_at: string;
|
|
43
|
-
cog_version: string;
|
|
44
|
-
openapi_schema: {
|
|
45
|
-
info: {
|
|
46
|
-
title: string;
|
|
47
|
-
version: string;
|
|
48
|
-
};
|
|
49
|
-
paths: Record<string, unknown>;
|
|
50
|
-
components: {
|
|
51
|
-
schemas: {
|
|
52
|
-
Input?: {
|
|
53
|
-
type: string;
|
|
54
|
-
properties: Record<string, unknown>;
|
|
55
|
-
required?: string[];
|
|
56
|
-
};
|
|
57
|
-
Output?: {
|
|
58
|
-
type: string;
|
|
59
|
-
properties?: Record<string, unknown>;
|
|
60
|
-
items?: unknown;
|
|
61
|
-
};
|
|
62
|
-
};
|
|
63
|
-
};
|
|
64
|
-
};
|
|
65
|
-
} | null;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Detect capabilities from model name, description, and schema
|
|
70
|
-
*/
|
|
71
|
-
function detectCapabilities(model: ReplicateModelData): Set<ModelCapability> {
|
|
72
|
-
const capabilities = new Set<ModelCapability>();
|
|
73
|
-
|
|
74
|
-
const lowerName = model.name.toLowerCase();
|
|
75
|
-
const lowerDesc = (model.description || '').toLowerCase();
|
|
76
|
-
|
|
77
|
-
// Image generation
|
|
78
|
-
if (
|
|
79
|
-
lowerName.includes('stable-diffusion') ||
|
|
80
|
-
lowerName.includes('sdxl') ||
|
|
81
|
-
lowerName.includes('flux') ||
|
|
82
|
-
lowerName.includes('imagen') ||
|
|
83
|
-
lowerName.includes('midjourney') ||
|
|
84
|
-
lowerName.includes('dalle') ||
|
|
85
|
-
lowerDesc.includes('image generation') ||
|
|
86
|
-
lowerDesc.includes('image edit') ||
|
|
87
|
-
lowerDesc.includes('text-to-image')
|
|
88
|
-
) {
|
|
89
|
-
capabilities.add('image');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Vision/image input
|
|
93
|
-
if (
|
|
94
|
-
lowerName.includes('vision') ||
|
|
95
|
-
lowerName.includes('image-to-text') ||
|
|
96
|
-
lowerDesc.includes('image analysis') ||
|
|
97
|
-
lowerDesc.includes('image understanding') ||
|
|
98
|
-
lowerDesc.includes('image edit')
|
|
99
|
-
) {
|
|
100
|
-
capabilities.add('vision');
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Transcription/hearing
|
|
104
|
-
if (
|
|
105
|
-
lowerName.includes('whisper') ||
|
|
106
|
-
lowerName.includes('transcribe') ||
|
|
107
|
-
lowerDesc.includes('speech-to-text') ||
|
|
108
|
-
lowerDesc.includes('transcription')
|
|
109
|
-
) {
|
|
110
|
-
capabilities.add('hearing');
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// Speech/audio output
|
|
114
|
-
if (
|
|
115
|
-
lowerName.includes('tts') ||
|
|
116
|
-
lowerName.includes('speech') ||
|
|
117
|
-
lowerName.includes('voice') ||
|
|
118
|
-
lowerDesc.includes('text-to-speech')
|
|
119
|
-
) {
|
|
120
|
-
capabilities.add('audio');
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Embeddings
|
|
124
|
-
if (lowerName.includes('embed') || lowerDesc.includes('embedding')) {
|
|
125
|
-
capabilities.add('embedding');
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Chat/language models
|
|
129
|
-
if (
|
|
130
|
-
lowerName.includes('llm') ||
|
|
131
|
-
lowerName.includes('chat') ||
|
|
132
|
-
lowerName.includes('gpt') ||
|
|
133
|
-
lowerName.includes('llama') ||
|
|
134
|
-
lowerName.includes('mistral') ||
|
|
135
|
-
lowerName.includes('gemma') ||
|
|
136
|
-
lowerName.includes('vicuna') ||
|
|
137
|
-
lowerDesc.includes('language model') ||
|
|
138
|
-
lowerDesc.includes('conversational')
|
|
139
|
-
) {
|
|
140
|
-
capabilities.add('chat');
|
|
141
|
-
capabilities.add('streaming');
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// If no capabilities detected but has a schema, add chat as default
|
|
145
|
-
if (capabilities.size === 0 && model.latest_version?.openapi_schema) {
|
|
146
|
-
capabilities.add('chat');
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
return capabilities;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Convert Replicate model to ModelInfo
|
|
154
|
-
*/
|
|
155
|
-
function convertReplicateModel(model: ReplicateModelData): ModelInfo {
|
|
156
|
-
const modelId = `${model.owner}/${model.name}`;
|
|
157
|
-
const capabilities = detectCapabilities(model);
|
|
158
|
-
const tier = detectTier(model.name);
|
|
159
|
-
|
|
160
|
-
return {
|
|
161
|
-
provider: 'replicate',
|
|
162
|
-
id: modelId,
|
|
163
|
-
name: model.name,
|
|
164
|
-
capabilities: capabilities, // Already an array
|
|
165
|
-
tier,
|
|
166
|
-
pricing: {},
|
|
167
|
-
contextWindow: 0, // Not consistently available in Replicate API
|
|
168
|
-
maxOutputTokens: undefined,
|
|
169
|
-
metadata: {
|
|
170
|
-
owner: model.owner,
|
|
171
|
-
description: model.description,
|
|
172
|
-
runCount: model.run_count,
|
|
173
|
-
githubUrl: model.github_url,
|
|
174
|
-
// paperUrl: model.paper_url,
|
|
175
|
-
// coverImageUrl: model.cover_image_url,
|
|
176
|
-
visibility: model.visibility,
|
|
177
|
-
source: 'replicate',
|
|
178
|
-
latestVersionId: model.latest_version?.id,
|
|
179
|
-
cogVersion: model.latest_version?.cog_version,
|
|
180
|
-
// schema: model.latest_version?.openapi_schema,
|
|
181
|
-
},
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
const ai = AI
|
|
186
|
-
.with()
|
|
187
|
-
.providers({
|
|
188
|
-
openrouter: new OpenRouterProvider({
|
|
189
|
-
apiKey: process.env.OPENROUTER_API_KEY!,
|
|
190
|
-
hooks: {
|
|
191
|
-
chat: {
|
|
192
|
-
beforeRequest: (a, b, c, d) => {
|
|
193
|
-
const now = Date.now().toString();
|
|
194
|
-
|
|
195
|
-
const requestResolved = path.resolve(__dirname, '../../cache/replicate', now + '-request.json');
|
|
196
|
-
fs.writeFile(requestResolved, JSON.stringify(b, null, 2));
|
|
197
|
-
|
|
198
|
-
const content = a.messages.map((m) => m.content).join('\n---\n');
|
|
199
|
-
const contentResolved = path.resolve(__dirname, '../../cache/replicate', now + '-content.txt');
|
|
200
|
-
fs.writeFile(contentResolved, content);
|
|
201
|
-
},
|
|
202
|
-
afterRequest: (a, b, c, d) => {
|
|
203
|
-
const now = Date.now().toString();
|
|
204
|
-
|
|
205
|
-
const responseResolved = path.resolve(__dirname, '../../cache/replicate', now + '-response.json');
|
|
206
|
-
fs.writeFile(responseResolved, JSON.stringify(c, null, 2));
|
|
207
|
-
|
|
208
|
-
const content = c.content;
|
|
209
|
-
const contentResolved = path.resolve(__dirname, '../../cache/replicate', now + '-response.txt');
|
|
210
|
-
fs.writeFile(contentResolved, content);
|
|
211
|
-
},
|
|
212
|
-
onError: (a, b, e, d) => {
|
|
213
|
-
const now = Date.now().toString();
|
|
214
|
-
|
|
215
|
-
const errorResolved = path.resolve(__dirname, '../../cache/replicate', now + '-error.txt');
|
|
216
|
-
fs.writeFile(errorResolved, String(e));
|
|
217
|
-
},
|
|
218
|
-
},
|
|
219
|
-
},
|
|
220
|
-
}),
|
|
221
|
-
})
|
|
222
|
-
.create({})
|
|
223
|
-
;
|
|
224
|
-
|
|
225
|
-
const jsonReplacer = (key: string, value: any) => {
|
|
226
|
-
if (value instanceof Set) {
|
|
227
|
-
return Array.from(value);
|
|
228
|
-
}
|
|
229
|
-
return value;
|
|
230
|
-
};
|
|
231
|
-
|
|
232
|
-
const typeInfo = await fs.readFile(path.join(__dirname, 'extract.md'), 'utf-8');
|
|
233
|
-
|
|
234
|
-
const optionalTransform = (val: any) =>
|
|
235
|
-
!val || Object.values(val).every((v) => v === null || v === undefined)
|
|
236
|
-
? undefined
|
|
237
|
-
: Object.fromEntries(Object.entries(val).filter(([_, v]) => v !== null && v !== undefined));
|
|
238
|
-
|
|
239
|
-
const extract = ai.prompt({
|
|
240
|
-
name: 'extract',
|
|
241
|
-
description: 'Extract model information & a transformer definition from Replicate model data',
|
|
242
|
-
content: `Extract model information & a transformer definition from the following data.
|
|
243
|
-
|
|
244
|
-
<modelData>
|
|
245
|
-
{{modelData}}
|
|
246
|
-
</modelData>
|
|
247
|
-
|
|
248
|
-
{{#if modelTypes}}
|
|
249
|
-
Here are the types for the model based on the OpenAPI schema:
|
|
250
|
-
\`\`\`ts
|
|
251
|
-
{{modelTypes}}
|
|
252
|
-
\`\`\`
|
|
253
|
-
|
|
254
|
-
Schemas["Input"] is what convertRequest should return.
|
|
255
|
-
Schemas["Output"] is what parseResponse is given as the first argument.
|
|
256
|
-
|
|
257
|
-
These types will be available and can be referenced like above to ensure type safety.
|
|
258
|
-
{{/if}}
|
|
259
|
-
|
|
260
|
-
Create a TypeScript implementation of a ReplicateTransformer for the model.
|
|
261
|
-
Here's an example transformer implementation for reference. This is the exact format to follow:
|
|
262
|
-
<exampleTransformerImplementation>
|
|
263
|
-
{
|
|
264
|
-
// this key comes from modelData.owner/modelData.name
|
|
265
|
-
// // The definition is wrapped in an immediately-invoked function expression so any cached or reusable functions can be defined here.
|
|
266
|
-
"google/nano-banana": (() => {
|
|
267
|
-
// you must use this ReplicateTransformer type to avoid TypeScript errors
|
|
268
|
-
const transformer: ReplicateTransformer = {
|
|
269
|
-
imageGenerate: {
|
|
270
|
-
// only use variable known to be in this request type based on the types below
|
|
271
|
-
convertRequest: async (request, ctx){{#if modelTypes}}: Promise<Schemas["Input"]>{{/if}} => ({
|
|
272
|
-
prompt: request.prompt,
|
|
273
|
-
...request.extra, // always spread extra to allow for additional parameters
|
|
274
|
-
}),
|
|
275
|
-
// only use known output schema from the model and only use properties expected on the response type based on the types below
|
|
276
|
-
parseResponse: async (response{{#if modelTypes}}: Schemas["Output"]{{/if}}, ctx) => ({
|
|
277
|
-
images: [{ url: await toURL(response) }],
|
|
278
|
-
extra: { response }, // include full response in extra object
|
|
279
|
-
}),
|
|
280
|
-
},
|
|
281
|
-
imageEdit: {
|
|
282
|
-
convertRequest: async (request, ctx){{#if modelTypes}}: Promise<Schemas["Input"]>{{/if}} => ({
|
|
283
|
-
prompt: request.prompt,
|
|
284
|
-
image_input: [await toURL(request.image)],
|
|
285
|
-
...request.extra, // always spread extra to allow for additional parameters
|
|
286
|
-
}),
|
|
287
|
-
parseResponse: async (response{{#if modelTypes}}: Schemas["Output"]{{/if}}, ctx) => ({
|
|
288
|
-
images: [{ url: await toURL(response) }],
|
|
289
|
-
extra: { response }, // include full response in extra object
|
|
290
|
-
}),
|
|
291
|
-
},
|
|
292
|
-
};
|
|
293
|
-
return transformer;
|
|
294
|
-
})(), // immediately invoke the function to return the typed transformer
|
|
295
|
-
}
|
|
296
|
-
</exampleTransformerImplementation>
|
|
297
|
-
|
|
298
|
-
The transformer code you return should match EXACTLY the format above. It will be injected in code like so by the developer:
|
|
299
|
-
<transformerResult>
|
|
300
|
-
import { toURL, toBase64, toText, toStream, toReadableStream, toFile } from '@aeye/core';
|
|
301
|
-
import { ReplicateTransformer } from '@aeye/replicate';
|
|
302
|
-
|
|
303
|
-
const transformer: Record<string, ReplicateTransformer> = <transformerImplementation>;
|
|
304
|
-
</transformerResult>
|
|
305
|
-
|
|
306
|
-
<availableFunctions>
|
|
307
|
-
- \`toURL(resource, mimeType?: string, fallback?: string): Promise<string>\` converts to URL string
|
|
308
|
-
- \`toBase64(resource, mimeType?: string, fallback?: string): Promise<string>\`
|
|
309
|
-
- \`toText(resource, fallback?: string): Promise<string>\`
|
|
310
|
-
- \`toStream(resource, fallback?: Readable): Promise<Readable>\`
|
|
311
|
-
- \`toReadableStream(resource, fallback?: ReadableStream): Promise<ReadableStream>\`
|
|
312
|
-
- \`toFile(resource, mimeType?: string, filename?: string): Promise<File>\`
|
|
313
|
-
</availableFunctions>
|
|
314
|
-
|
|
315
|
-
Here's how the replicate code looks around the transformer: This is an example to illustrate how the transformer you generate is used.
|
|
316
|
-
<replicateCode>
|
|
317
|
-
// =============================================================
|
|
318
|
-
// Execute
|
|
319
|
-
// =============================================================
|
|
320
|
-
const { convertRequest, parseResponse } = transformer;
|
|
321
|
-
const client = new Replicate({ /* config */ });
|
|
322
|
-
const input = await convertRequest(request, ctx);
|
|
323
|
-
const output = await client.run(modelId, { input, signal });
|
|
324
|
-
const response = await parseResponse(output, ctx);
|
|
325
|
-
|
|
326
|
-
// =============================================================
|
|
327
|
-
// Stream
|
|
328
|
-
// =============================================================
|
|
329
|
-
const { convertRequest, parseChunk } = transformer;
|
|
330
|
-
const client = new Replicate({ /* config */ });
|
|
331
|
-
const input = await convertRequest(request, ctx);
|
|
332
|
-
for await (const event of client.stream(modelId, { input, signal })) {
|
|
333
|
-
if (signal?.aborted) {
|
|
334
|
-
throw new Error('Request aborted');
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// Parse chunk using transformer
|
|
338
|
-
const chunk = await parseChunk(event, ctx);
|
|
339
|
-
yield chunk;
|
|
340
|
-
}
|
|
341
|
-
</replicateCode>
|
|
342
|
-
|
|
343
|
-
Here is type information you need to use to understand the shape of all the types:
|
|
344
|
-
It is EXTREMELY important you only use properties that are guaranteed to be present based on the types below when it comes to transformer, request, response, and chunk types.
|
|
345
|
-
The request parameters in the converted request should only be the properties that are known to be in the input schema for the model. The rest may be passed in via \`extra\` property.
|
|
346
|
-
<typeInfo>
|
|
347
|
-
{{typeInfo}}
|
|
348
|
-
</typeInfo>
|
|
349
|
-
`,
|
|
350
|
-
strict: true,
|
|
351
|
-
outputRetries: 3,
|
|
352
|
-
schema: z.object({
|
|
353
|
-
transformerImplementation: z.string()
|
|
354
|
-
// .regex(/^\{\n\s+"[^"]+\/[^"]+": \(\(\) => \{(.|\r|\n)*\}\)\(\),\n\}$/)
|
|
355
|
-
.describe(`The TypeScript implementation of the model handler (without imports or \`\`\` marks) - described BETWEEN the <exampleTransformerImplementation> tags. Follow the rules outlined.`),
|
|
356
|
-
modelInfo: z.object({
|
|
357
|
-
capabilities: z.array(z.enum([
|
|
358
|
-
'chat',
|
|
359
|
-
'tools',
|
|
360
|
-
'vision',
|
|
361
|
-
'json',
|
|
362
|
-
'structured',
|
|
363
|
-
'streaming',
|
|
364
|
-
'reasoning',
|
|
365
|
-
'image',
|
|
366
|
-
'audio',
|
|
367
|
-
'hearing',
|
|
368
|
-
'embedding',
|
|
369
|
-
'zdr'
|
|
370
|
-
])).describe(`Set of capabilities this model supports:
|
|
371
|
-
|
|
372
|
-
- chat: Text input & output
|
|
373
|
-
- tools: Ability to make tool calls
|
|
374
|
-
- vision: Image inputs
|
|
375
|
-
- json: Supports JSON response format
|
|
376
|
-
- structured: Supports structured output (strict JSON response format)
|
|
377
|
-
- streaming: Supports streaming responses
|
|
378
|
-
- reasoning: Enhanced reasoning capabilities
|
|
379
|
-
- image: Image output
|
|
380
|
-
- audio: Audio output
|
|
381
|
-
- hearing: Audio input
|
|
382
|
-
- embedding: Text -> embedding generation
|
|
383
|
-
- zdr: Supports zero-data-retention through a parameter`),
|
|
384
|
-
tier: z.enum(['flagship', 'efficient', 'legacy', 'experimental']).describe(`Model performance and quality tiers.
|
|
385
|
-
Used for categorizing models by their capabilities and cost.
|
|
386
|
-
|
|
387
|
-
- flagship: Top-tier models with best performance
|
|
388
|
-
- efficient: Smaller, faster, more cost-effective models
|
|
389
|
-
- legacy: Older models, may be deprecated
|
|
390
|
-
- experimental: Preview/beta models`),
|
|
391
|
-
pricing: z.object({
|
|
392
|
-
text: z.object({
|
|
393
|
-
input: z.number().optional(),
|
|
394
|
-
output: z.number().optional(),
|
|
395
|
-
cached: z.number().optional(),
|
|
396
|
-
}).optional()
|
|
397
|
-
.transform(optionalTransform),
|
|
398
|
-
audio: z.object({
|
|
399
|
-
input: z.number().optional(),
|
|
400
|
-
output: z.number().optional(),
|
|
401
|
-
perSecond: z.number().optional(),
|
|
402
|
-
}).optional()
|
|
403
|
-
.transform(optionalTransform),
|
|
404
|
-
image: z.object({
|
|
405
|
-
input: z.number().optional(),
|
|
406
|
-
output: z.array(z.object({
|
|
407
|
-
quality: z.string().describe('Quality level - like low, medium, high'),
|
|
408
|
-
sizes: z.array(z.object({
|
|
409
|
-
width: z.number(),
|
|
410
|
-
height: z.number(),
|
|
411
|
-
cost: z.number().describe('Cost per image in USD'),
|
|
412
|
-
})).describe('Supported image sizes and their costs'),
|
|
413
|
-
})).optional()
|
|
414
|
-
.transform(optionalTransform),
|
|
415
|
-
}).optional()
|
|
416
|
-
.transform(optionalTransform),
|
|
417
|
-
reasoning: z.object({
|
|
418
|
-
input: z.number().optional(),
|
|
419
|
-
output: z.number().optional(),
|
|
420
|
-
cached: z.number().optional(),
|
|
421
|
-
}).optional()
|
|
422
|
-
.transform(optionalTransform),
|
|
423
|
-
embeddings: z.object({
|
|
424
|
-
cost: z.number().optional(),
|
|
425
|
-
}).optional()
|
|
426
|
-
.transform(optionalTransform),
|
|
427
|
-
perRequest: z.number().optional().describe('Flat cost per request in USD'),
|
|
428
|
-
}).describe('Pricing information. input/output/cached are per 1 million tokens unless otherwise specified. Leave null/undefined if unknown - 0 is free. Do not specify 0 unless it is free.'),
|
|
429
|
-
contextWindow: z.number(),
|
|
430
|
-
maxOutputTokens: z.number().optional(),
|
|
431
|
-
metrics: z.object({
|
|
432
|
-
tokensPerSecond: z.number().optional().describe('Processing speed in tokens per second'),
|
|
433
|
-
timeToFirstToken: z.number().optional().describe('Time to first token in milliseconds'),
|
|
434
|
-
averageRequestDuration: z.number().optional().describe('Average request duration in milliseconds'),
|
|
435
|
-
accuracyScore: z.number().optional().describe('Accuracy score based on benchmark tests 0-1'),
|
|
436
|
-
}).optional()
|
|
437
|
-
.transform(optionalTransform)
|
|
438
|
-
.describe('Performance metrics if available'),
|
|
439
|
-
tokenizer: z.enum(([
|
|
440
|
-
'Other', 'GPT', 'Mistral', 'Llama3', 'Qwen3', 'Qwen', 'Gemini', 'DeepSeek', 'Claude', 'Grok', 'Llama4', 'Llama2', 'Cohere', 'Nova', 'Router'
|
|
441
|
-
])).optional().describe('The tokenizer type used by this model if known, otherwise leave undefined'),
|
|
442
|
-
supportedParameters: z.array(z.enum([
|
|
443
|
-
// Chat Request
|
|
444
|
-
'maxTokens', // max_tokens / max_completion_tokens
|
|
445
|
-
'temperature', // temperature
|
|
446
|
-
'topP', // top_p
|
|
447
|
-
'frequencyPenalty', // frequency_penalty
|
|
448
|
-
'presencePenalty', // presence_penalty
|
|
449
|
-
'stop', // stop
|
|
450
|
-
'seed', // seed
|
|
451
|
-
'responseFormat', // response_format
|
|
452
|
-
'structuredOutput', // structured_outputs
|
|
453
|
-
'tools', // tools
|
|
454
|
-
'toolChoice', // tool_choice
|
|
455
|
-
'logitBias', // logit_bias
|
|
456
|
-
'logProbabilities', // logprobs
|
|
457
|
-
'reason', // reasoning
|
|
458
|
-
// Image
|
|
459
|
-
'imageBackground', // background
|
|
460
|
-
'imageMultiple', // n
|
|
461
|
-
'imageFormat', // output_format ()
|
|
462
|
-
'imageStream', // stream / partial_images
|
|
463
|
-
'imageStyle',
|
|
464
|
-
// Embedding
|
|
465
|
-
'embeddingDimensions', // dimensions
|
|
466
|
-
// Transcription
|
|
467
|
-
'transcribeStream', // stream
|
|
468
|
-
'transcribePrompt', // prompt
|
|
469
|
-
// Speech
|
|
470
|
-
'speechInstructions', // instructions
|
|
471
|
-
])).optional().describe('The supported parameters for this model'),
|
|
472
|
-
}).describe('The extracted model information'),
|
|
473
|
-
}),
|
|
474
|
-
input: async ({ modelData, modelTypes }: { model: string, modelData: ReplicateModelData, modelTypes: string }) => {
|
|
475
|
-
return {
|
|
476
|
-
modelData: JSON.stringify(modelData, (k, v) => {
|
|
477
|
-
if (k === "embeddings" && Array.isArray(v) && v.length > 20) {
|
|
478
|
-
return [`...${v.length} ${typeof v[0]}s...`];
|
|
479
|
-
}
|
|
480
|
-
if (Array.isArray(v) && v.length > 20) {
|
|
481
|
-
return [`...${v.length} ${typeof v[0]}s...`];
|
|
482
|
-
}
|
|
483
|
-
return v;
|
|
484
|
-
}, 2),
|
|
485
|
-
typeInfo,
|
|
486
|
-
modelTypes,
|
|
487
|
-
};
|
|
488
|
-
},
|
|
489
|
-
config: (input) => ({
|
|
490
|
-
model: input?.model,
|
|
491
|
-
temperature: 0,
|
|
492
|
-
topP: 1,
|
|
493
|
-
}),
|
|
494
|
-
})
|
|
495
|
-
|
|
496
|
-
async function extractTypes(model: ReplicateModelData): Promise<string> {
|
|
497
|
-
if (!model.latest_version?.openapi_schema) {
|
|
498
|
-
return '';
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
let extracted = await extractSchemasString(model.latest_version.openapi_schema as any);
|
|
502
|
-
if (!extracted) {
|
|
503
|
-
return '';
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
return extracted.replaceAll('components["schemas"]', 'Schemas').replaceAll(' ', ' ');
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
async function extractSchemasString(schemaObject: any): Promise<string> {
|
|
510
|
-
try {
|
|
511
|
-
const ast = await openapiTS(schemaObject, {
|
|
512
|
-
propertiesRequiredByDefault: false,
|
|
513
|
-
defaultNonNullable: false,
|
|
514
|
-
});
|
|
515
|
-
|
|
516
|
-
const printer = ts.createPrinter({
|
|
517
|
-
newLine: ts.NewLineKind.LineFeed,
|
|
518
|
-
removeComments: true,
|
|
519
|
-
});
|
|
520
|
-
|
|
521
|
-
const dummySourceFile = ts.createSourceFile("temp.ts", "", ts.ScriptTarget.ESNext, true);
|
|
522
|
-
|
|
523
|
-
const componentsNode = ast.find(node => {
|
|
524
|
-
if (ts.isInterfaceDeclaration(node)) {
|
|
525
|
-
const name = printer.printNode(ts.EmitHint.Unspecified, node.name, dummySourceFile);
|
|
526
|
-
return name === 'components';
|
|
527
|
-
}
|
|
528
|
-
return false;
|
|
529
|
-
}) as ts.InterfaceDeclaration | undefined;
|
|
530
|
-
|
|
531
|
-
if (!componentsNode) {
|
|
532
|
-
console.error("Error: Could not find the 'components' node in the generated AST.");
|
|
533
|
-
return "";
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
let extractedMembersString = "";
|
|
537
|
-
|
|
538
|
-
// Get the inner content of the 'schemas' property
|
|
539
|
-
for (const member of componentsNode.members) {
|
|
540
|
-
if (ts.isPropertySignature(member)) {
|
|
541
|
-
const propName = printer.printNode(ts.EmitHint.Unspecified, member.name, dummySourceFile);
|
|
542
|
-
|
|
543
|
-
if (propName === 'schemas' && member.type && ts.isTypeLiteralNode(member.type)) {
|
|
544
|
-
member.type.members.forEach(schemaMember => {
|
|
545
|
-
extractedMembersString += printer.printNode(ts.EmitHint.Unspecified, schemaMember, dummySourceFile) + "\n";
|
|
546
|
-
});
|
|
547
|
-
break;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
if (!extractedMembersString.trim()) {
|
|
553
|
-
console.error("Error: Found no user-defined schema types within the 'components.schemas' structure.");
|
|
554
|
-
return "";
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
return `type Schemas = {\n ${extractedMembersString.replaceAll('\n', '\n ').trim()}\n};`;
|
|
558
|
-
} catch (error) {
|
|
559
|
-
console.error("An unexpected error occurred during schema extraction:", error);
|
|
560
|
-
return "";
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/**
|
|
565
|
-
* Fetch all models from Replicate collections
|
|
566
|
-
*/
|
|
567
|
-
async function fetchAllModels(apiKey?: string): Promise<ReplicateModelData[]> {
|
|
568
|
-
console.log('Fetching Replicate models...');
|
|
569
|
-
|
|
570
|
-
const client = new Replicate({
|
|
571
|
-
auth: apiKey || process.env.REPLICATE_API_KEY,
|
|
572
|
-
});
|
|
573
|
-
|
|
574
|
-
const allModels: ReplicateModelData[] = [];
|
|
575
|
-
const seenModels = new Set<string>();
|
|
576
|
-
|
|
577
|
-
// Collections to scrape
|
|
578
|
-
const collections = [
|
|
579
|
-
'text-to-image',
|
|
580
|
-
'image-to-text',
|
|
581
|
-
'text-to-speech',
|
|
582
|
-
'speech-to-text',
|
|
583
|
-
'super-resolution',
|
|
584
|
-
'image-editing',
|
|
585
|
-
'ai-face-generator',
|
|
586
|
-
'ai-music-generation',
|
|
587
|
-
'text-recognition-ocr',
|
|
588
|
-
'flux',
|
|
589
|
-
'ai-image-restoration',
|
|
590
|
-
'text-classification',
|
|
591
|
-
'sketch-to-image',
|
|
592
|
-
'embedding-models',
|
|
593
|
-
'vision-models',
|
|
594
|
-
];
|
|
595
|
-
|
|
596
|
-
console.log(`Fetching models from ${collections.length} collections...`);
|
|
597
|
-
|
|
598
|
-
for (const collectionSlug of collections) {
|
|
599
|
-
try {
|
|
600
|
-
console.log(` Fetching collection: ${collectionSlug}...`);
|
|
601
|
-
|
|
602
|
-
const collection = await client.collections.get(collectionSlug);
|
|
603
|
-
|
|
604
|
-
if (collection.models) {
|
|
605
|
-
for (const model of collection.models) {
|
|
606
|
-
const modelId = `${(model as any).owner}/${(model as any).name}`;
|
|
607
|
-
|
|
608
|
-
// Skip duplicates
|
|
609
|
-
if (seenModels.has(modelId)) {
|
|
610
|
-
continue;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
seenModels.add(modelId);
|
|
614
|
-
allModels.push(model as ReplicateModelData);
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
console.log(` ✓ Found ${collection.models.length} models in ${collectionSlug}`);
|
|
618
|
-
}
|
|
619
|
-
} catch (error) {
|
|
620
|
-
console.log(` ⚠ Failed to fetch collection ${collectionSlug}:`, error instanceof Error ? error.message : error);
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
console.log(`\n✓ Fetched ${allModels.length} unique Replicate models`);
|
|
625
|
-
|
|
626
|
-
return allModels;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
/**
|
|
630
|
-
* Fetch model details including schema (for cache)
|
|
631
|
-
*/
|
|
632
|
-
async function fetchModelSchema(
|
|
633
|
-
modelId: string,
|
|
634
|
-
client: Replicate
|
|
635
|
-
): Promise<{
|
|
636
|
-
modelId: string;
|
|
637
|
-
data: ReplicateModelData | null;
|
|
638
|
-
}> {
|
|
639
|
-
try {
|
|
640
|
-
const [owner, name] = modelId.split('/');
|
|
641
|
-
const model = await client.models.get(owner, name);
|
|
642
|
-
return { modelId, data: model as ReplicateModelData };
|
|
643
|
-
} catch (error) {
|
|
644
|
-
console.log(` ⚠ Failed to fetch model ${modelId}:`, error instanceof Error ? error.message : error);
|
|
645
|
-
return { modelId, data: null };
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
/**
|
|
650
|
-
* Fetch schemas in parallel with concurrency control
|
|
651
|
-
*/
|
|
652
|
-
async function fetchSchemasParallel(
|
|
653
|
-
models: ReplicateModelData[],
|
|
654
|
-
apiKey: string,
|
|
655
|
-
concurrency: number = 50
|
|
656
|
-
): Promise<Record<string, ReplicateModelData>> {
|
|
657
|
-
console.log(`\nCaching detailed model schemas (concurrency: ${concurrency})...`);
|
|
658
|
-
|
|
659
|
-
const client = new Replicate({
|
|
660
|
-
auth: apiKey,
|
|
661
|
-
});
|
|
662
|
-
|
|
663
|
-
const schemasCache: Record<string, ReplicateModelData> = {};
|
|
664
|
-
|
|
665
|
-
// First, add models that already have schemas
|
|
666
|
-
for (const model of models) {
|
|
667
|
-
const modelId = `${model.owner}/${model.name}`;
|
|
668
|
-
if (model.latest_version?.openapi_schema) {
|
|
669
|
-
schemasCache[modelId] = model;
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
// Find models that need schema fetching
|
|
674
|
-
const modelsToFetch = models.filter((model) => {
|
|
675
|
-
return !model.latest_version?.openapi_schema;
|
|
676
|
-
});
|
|
677
|
-
|
|
678
|
-
if (modelsToFetch.length === 0) {
|
|
679
|
-
console.log(`✓ All ${models.length} models already have schemas\n`);
|
|
680
|
-
return schemasCache;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
console.log(` ${Object.keys(schemasCache).length - modelsToFetch.length} models already have schemas`);
|
|
684
|
-
console.log(` Fetching schemas for ${modelsToFetch.length} models...\n`);
|
|
685
|
-
|
|
686
|
-
// Process in batches with concurrency control
|
|
687
|
-
const modelIdsToFetch = modelsToFetch.map((m) => `${m.owner}/${m.name}`);
|
|
688
|
-
|
|
689
|
-
for (let i = 0; i < modelIdsToFetch.length; i += concurrency) {
|
|
690
|
-
const batch = modelIdsToFetch.slice(i, i + concurrency);
|
|
691
|
-
console.log(` Processing batch ${Math.floor(i / concurrency) + 1}/${Math.ceil(modelIdsToFetch.length / concurrency)} (${batch.length} models)...`);
|
|
692
|
-
|
|
693
|
-
const batchResults = await Promise.all(
|
|
694
|
-
batch.map((modelId) => fetchModelSchema(modelId, client))
|
|
695
|
-
);
|
|
696
|
-
|
|
697
|
-
// Store results
|
|
698
|
-
for (const { modelId, data } of batchResults) {
|
|
699
|
-
if (data) {
|
|
700
|
-
schemasCache[modelId] = data;
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
console.log(` ✓ Fetched ${batchResults.filter((r) => r.data).length}/${batch.length} schemas`);
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
console.log(`\n✓ Cached ${Object.keys(schemasCache).length} model schemas\n`);
|
|
708
|
-
|
|
709
|
-
return schemasCache;
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
function cleanSchema(model: ReplicateModelData) {
|
|
713
|
-
const schema = model.latest_version?.openapi_schema as any;
|
|
714
|
-
if (schema) {
|
|
715
|
-
// delete schema.components.schemas.Status;
|
|
716
|
-
delete schema.components.schemas.WebhookEvent;
|
|
717
|
-
delete schema.components.schemas.ValidationError;
|
|
718
|
-
delete schema.components.schemas.PredictionRequest;
|
|
719
|
-
delete schema.components.schemas.PredictionResponse;
|
|
720
|
-
delete schema.components.schemas.HTTPValidationError;
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
/**
|
|
725
|
-
* Main scraper function
|
|
726
|
-
*/
|
|
727
|
-
export async function scrapeReplicate(
|
|
728
|
-
outputDir: string,
|
|
729
|
-
cacheDir?: string,
|
|
730
|
-
options: {
|
|
731
|
-
concurrency?: number,
|
|
732
|
-
transformers?: boolean,
|
|
733
|
-
transformerModel: string,
|
|
734
|
-
transformersOnly?: boolean,
|
|
735
|
-
transformConcurrency?: number,
|
|
736
|
-
models?: string[],
|
|
737
|
-
n?: number,
|
|
738
|
-
} = {
|
|
739
|
-
transformerModel: 'google/gemini-2.5-pro',
|
|
740
|
-
}
|
|
741
|
-
): Promise<void> {
|
|
742
|
-
const { concurrency = 50 } = options;
|
|
743
|
-
|
|
744
|
-
const apiKey = process.env.REPLICATE_API_KEY;
|
|
745
|
-
if (!apiKey) {
|
|
746
|
-
console.error('✗ REPLICATE_API_KEY environment variable is required');
|
|
747
|
-
process.exit(1);
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
let models: ReplicateModelData[]
|
|
751
|
-
|
|
752
|
-
if (!options.transformersOnly) {
|
|
753
|
-
console.log('\n=== Replicate Scraper ===\n');
|
|
754
|
-
|
|
755
|
-
// Fetch all models from collections
|
|
756
|
-
models = await fetchAllModels(apiKey);
|
|
757
|
-
|
|
758
|
-
// Create output directory
|
|
759
|
-
await fs.mkdir(outputDir, { recursive: true });
|
|
760
|
-
|
|
761
|
-
// Save raw models data
|
|
762
|
-
await fs.writeFile(
|
|
763
|
-
path.join(outputDir, 'replicate-models.json'),
|
|
764
|
-
JSON.stringify({ data: models }, jsonReplacer, 2)
|
|
765
|
-
);
|
|
766
|
-
|
|
767
|
-
console.log(`✓ Saved raw Replicate models to replicate-models.json`);
|
|
768
|
-
} else {
|
|
769
|
-
const modelsData = await fs.readFile(
|
|
770
|
-
path.join(outputDir, 'replicate-models.json'),
|
|
771
|
-
'utf-8'
|
|
772
|
-
);
|
|
773
|
-
const parsed = JSON.parse(modelsData);
|
|
774
|
-
models = parsed.data as ReplicateModelData[];
|
|
775
|
-
|
|
776
|
-
console.log(`\n✓ Loaded ${models.length} Replicate models from cache\n`);
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
models.forEach(cleanSchema);
|
|
780
|
-
|
|
781
|
-
// Sort models by owner/name
|
|
782
|
-
models.sort((a, b) => `${a.owner}/${a.name}`.localeCompare(`${b.owner}/${b.name}`));
|
|
783
|
-
|
|
784
|
-
// Convert to ModelInfo format
|
|
785
|
-
const modelInfos = models.map(convertReplicateModel);
|
|
786
|
-
|
|
787
|
-
try {
|
|
788
|
-
const modelInfoCache = await fs.readFile(
|
|
789
|
-
path.join(outputDir, 'replicate-modelinfo.json'),
|
|
790
|
-
'utf-8'
|
|
791
|
-
);
|
|
792
|
-
const parsed = JSON.parse(modelInfoCache) as ModelInfo[];
|
|
793
|
-
for (const info of parsed) {
|
|
794
|
-
const existing = modelInfos.findIndex((m) => m.id === info.id);
|
|
795
|
-
if (existing >= 0) {
|
|
796
|
-
modelInfos[existing] = info;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
} catch (e: any) {
|
|
800
|
-
// Ignore if file doesn't exist
|
|
801
|
-
console.error(`⚠ Could not load existing model info cache: ${e.message}`);
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
let schemasCache: Record<string, ReplicateModelData> = {};
|
|
805
|
-
|
|
806
|
-
// Create cache directory if specified
|
|
807
|
-
if (cacheDir) {
|
|
808
|
-
if (!options.transformersOnly) {
|
|
809
|
-
await fs.mkdir(cacheDir, { recursive: true });
|
|
810
|
-
|
|
811
|
-
// Cache detailed model schemas (for transformer generation)
|
|
812
|
-
schemasCache = await fetchSchemasParallel(models, apiKey, concurrency);
|
|
813
|
-
|
|
814
|
-
// Save schemas cache
|
|
815
|
-
await fs.writeFile(
|
|
816
|
-
path.join(cacheDir, 'replicate-schemas.json'),
|
|
817
|
-
JSON.stringify(schemasCache, jsonReplacer, 2)
|
|
818
|
-
);
|
|
819
|
-
|
|
820
|
-
console.log(`✓ Saved ${Object.keys(schemasCache).length} model schemas to ${cacheDir}/replicate-schemas.json`);
|
|
821
|
-
console.log(' (This cache file is for transformer generation and should not be committed)');
|
|
822
|
-
|
|
823
|
-
// Chunk it up to 80,000 character files for easier loading later
|
|
824
|
-
const chunkSize = 80000;
|
|
825
|
-
const schemaEntries = Object.entries(schemasCache);
|
|
826
|
-
let currentChunk: Record<string, ReplicateModelData> = {};
|
|
827
|
-
let currentSize = 0;
|
|
828
|
-
let chunkIndex = 1;
|
|
829
|
-
for (const [modelId, modelData] of schemaEntries) {
|
|
830
|
-
const entryString = JSON.stringify({ [modelId]: modelData });
|
|
831
|
-
if (currentSize + entryString.length > chunkSize && Object.keys(currentChunk).length > 0) {
|
|
832
|
-
// Save current chunk
|
|
833
|
-
await fs.writeFile(
|
|
834
|
-
path.join(cacheDir, `replicate-schemas-chunk-${chunkIndex}.json`),
|
|
835
|
-
JSON.stringify(currentChunk, null, 2)
|
|
836
|
-
);
|
|
837
|
-
console.log(`✓ Saved schema chunk ${chunkIndex} with ${Object.keys(currentChunk).length} models`);
|
|
838
|
-
chunkIndex++;
|
|
839
|
-
currentChunk = {};
|
|
840
|
-
currentSize = 0;
|
|
841
|
-
}
|
|
842
|
-
currentChunk[modelId] = modelData;
|
|
843
|
-
currentSize += entryString.length;
|
|
844
|
-
}
|
|
845
|
-
// Save any remaining chunk
|
|
846
|
-
if (Object.keys(currentChunk).length > 0) {
|
|
847
|
-
await fs.writeFile(
|
|
848
|
-
path.join(cacheDir, `replicate-schemas-chunk-${chunkIndex}.json`),
|
|
849
|
-
JSON.stringify(currentChunk, null, 2)
|
|
850
|
-
);
|
|
851
|
-
console.log(`✓ Saved schema chunk ${chunkIndex} with ${Object.keys(currentChunk).length} models`);
|
|
852
|
-
}
|
|
853
|
-
} else {
|
|
854
|
-
// Load schemas cache from file
|
|
855
|
-
const schemasData = await fs.readFile(
|
|
856
|
-
path.join(cacheDir, 'replicate-schemas.json'),
|
|
857
|
-
'utf-8'
|
|
858
|
-
);
|
|
859
|
-
schemasCache = JSON.parse(schemasData) as Record<string, ReplicateModelData>;
|
|
860
|
-
|
|
861
|
-
console.log(`\n✓ Loaded ${Object.keys(schemasCache).length} model schemas from cache\n`);
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
for (const modelData of Object.values(schemasCache)) {
|
|
865
|
-
cleanSchema(modelData);
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
// Calculate number of unique schemas
|
|
869
|
-
const uniqueSchemas = new Set<string>();
|
|
870
|
-
for (const modelData of Object.values(schemasCache)) {
|
|
871
|
-
if (modelData.latest_version) {
|
|
872
|
-
uniqueSchemas.add(JSON.stringify(modelData.latest_version.openapi_schema.components.schemas));
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
console.log(`\n✓ Found ${uniqueSchemas.size} unique model schemas across ${Object.keys(schemasCache).length} models\n`);
|
|
877
|
-
|
|
878
|
-
// Generate Model Transformers
|
|
879
|
-
if (options.transformers) {
|
|
880
|
-
console.log('=== Generating Model Transformers ===\n');
|
|
881
|
-
|
|
882
|
-
// Create replicate transformers directory
|
|
883
|
-
await fs.mkdir(
|
|
884
|
-
path.join(cacheDir, 'replicate'),
|
|
885
|
-
{ recursive: true }
|
|
886
|
-
);
|
|
887
|
-
|
|
888
|
-
let transformingModels = models;
|
|
889
|
-
let overwrite = false;
|
|
890
|
-
|
|
891
|
-
// Filter to only models with schemas if transformers are desired
|
|
892
|
-
if (options.models && options.models.length > 0) {
|
|
893
|
-
const modelSet = new Set(options.models);
|
|
894
|
-
transformingModels = transformingModels.filter((model) => {
|
|
895
|
-
const modelId = `${model.owner}/${model.name}`;
|
|
896
|
-
return modelSet.has(modelId);
|
|
897
|
-
});
|
|
898
|
-
overwrite = true;
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
// If models were not specified, filter out already transformed models
|
|
902
|
-
if (!overwrite) {
|
|
903
|
-
const alreadyTransformed = await fs.readdir(
|
|
904
|
-
path.resolve(cacheDir, '../src/transformers/replicate'),
|
|
905
|
-
);
|
|
906
|
-
const alreadyTransformedSet = new Set(
|
|
907
|
-
alreadyTransformed
|
|
908
|
-
.filter((filename) => filename.endsWith('.ts') && filename !== 'index.ts')
|
|
909
|
-
.map((filename) => filename.replace('.ts', ''))
|
|
910
|
-
);
|
|
911
|
-
transformingModels = transformingModels.filter((model) => {
|
|
912
|
-
const modelId = `${model.owner}/${model.name}`;
|
|
913
|
-
const transformedFile = modelId.replace(/[^\w]/g, '-');
|
|
914
|
-
|
|
915
|
-
return !alreadyTransformedSet.has(transformedFile);
|
|
916
|
-
});
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
// Only first N models if specified
|
|
920
|
-
if (options.n && options.n > 0) {
|
|
921
|
-
transformingModels = transformingModels.slice(0, options.n);
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
// Call extractor for each model
|
|
925
|
-
console.log(`Generating transformers for ${transformingModels.length} models...\n`);
|
|
926
|
-
|
|
927
|
-
// Use specified concurrency for transformations
|
|
928
|
-
const concurrency = options.transformConcurrency !== undefined && options.transformConcurrency <= 0
|
|
929
|
-
? transformingModels.length
|
|
930
|
-
: options.transformConcurrency ?? 1;
|
|
931
|
-
|
|
932
|
-
let nextModelIndex = 0;
|
|
933
|
-
|
|
934
|
-
const workers: Promise<void>[] = [];
|
|
935
|
-
for (let i = 0; i < concurrency; i++) {
|
|
936
|
-
const worker = (async () => {
|
|
937
|
-
while (nextModelIndex < transformingModels.length) {
|
|
938
|
-
const model = transformingModels[nextModelIndex];
|
|
939
|
-
nextModelIndex++;
|
|
940
|
-
const modelId = `${model.owner}/${model.name}`;
|
|
941
|
-
const transformedFile = modelId.replace(/[^\w]/g, '-') + '.ts';
|
|
942
|
-
const modelData = schemasCache[modelId] || model;
|
|
943
|
-
|
|
944
|
-
console.log(`\n--- Generating transformer for model: ${modelId}, ---`);
|
|
945
|
-
|
|
946
|
-
try {
|
|
947
|
-
const modelTypes = await extractTypes(modelData);
|
|
948
|
-
|
|
949
|
-
const result = await extract.get('result', {
|
|
950
|
-
modelData,
|
|
951
|
-
modelTypes,
|
|
952
|
-
model: options.transformerModel
|
|
953
|
-
});
|
|
954
|
-
if (!result) {
|
|
955
|
-
console.log(` ✗ Failed to generate transformer for model: ${modelId}`);
|
|
956
|
-
continue;
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
const converted = convertReplicateModel(modelData);
|
|
960
|
-
|
|
961
|
-
const translatedModelInfo: ModelInfo<'replicate'> = {
|
|
962
|
-
id: converted.id,
|
|
963
|
-
provider: 'replicate',
|
|
964
|
-
name: converted.name,
|
|
965
|
-
contextWindow: result.modelInfo.contextWindow,
|
|
966
|
-
maxOutputTokens: result.modelInfo.maxOutputTokens,
|
|
967
|
-
pricing: result.modelInfo.pricing,
|
|
968
|
-
tier: result.modelInfo.tier,
|
|
969
|
-
capabilities: new Set(result.modelInfo.capabilities),
|
|
970
|
-
metrics: result.modelInfo.metrics,
|
|
971
|
-
tokenizer: result.modelInfo.tokenizer,
|
|
972
|
-
supportedParameters: new Set(result.modelInfo.supportedParameters),
|
|
973
|
-
metadata: converted.metadata,
|
|
974
|
-
};
|
|
975
|
-
|
|
976
|
-
const replaceIndex = modelInfos.findIndex((m) => m.id === translatedModelInfo.id);
|
|
977
|
-
if (replaceIndex >= 0) {
|
|
978
|
-
modelInfos[replaceIndex] = translatedModelInfo;
|
|
979
|
-
} else {
|
|
980
|
-
console.log(` ⚠ ModelInfo for ${modelId} not found in main list, adding new entry`);
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
let fixedTransformerImplementation = result.transformerImplementation;
|
|
984
|
-
if (fixedTransformerImplementation.startsWith('"')) {
|
|
985
|
-
fixedTransformerImplementation = `{\n ${fixedTransformerImplementation}\n}`;
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
const coreImports = [
|
|
989
|
-
fixedTransformerImplementation.includes('toURL') ? 'toURL' : null,
|
|
990
|
-
fixedTransformerImplementation.includes('toBase64') ? 'toBase64' : null,
|
|
991
|
-
fixedTransformerImplementation.includes('toText') ? 'toText' : null,
|
|
992
|
-
fixedTransformerImplementation.includes('toStream') ? 'toStream' : null,
|
|
993
|
-
fixedTransformerImplementation.includes('toReadableStream') ? 'toReadableStream' : null,
|
|
994
|
-
fixedTransformerImplementation.includes('toFile') ? 'toFile' : null,
|
|
995
|
-
].filter((i) => i !== null) as string[];
|
|
996
|
-
|
|
997
|
-
const validatedFile = path.resolve(cacheDir, '../src/transformers/replicate', transformedFile);
|
|
998
|
-
await fs.writeFile(
|
|
999
|
-
validatedFile,
|
|
1000
|
-
`
|
|
1001
|
-
${coreImports.length > 0 ? `import { ${coreImports.join(', ')} } from '@aeye/core';` : ''}
|
|
1002
|
-
import { ReplicateTransformer } from '@aeye/replicate';
|
|
1003
|
-
|
|
1004
|
-
${modelTypes}
|
|
1005
|
-
|
|
1006
|
-
export default ${fixedTransformerImplementation}
|
|
1007
|
-
`.trim()
|
|
1008
|
-
);
|
|
1009
|
-
|
|
1010
|
-
if (await isValidTypeScript(validatedFile)) {
|
|
1011
|
-
console.log(` ✓ Validated transformer implementation for ${modelId}`);
|
|
1012
|
-
} else {
|
|
1013
|
-
console.log(` ✗ Generated transformer for model ${modelId} is not valid TypeScript, skipping save.`);
|
|
1014
|
-
await fs.rename(validatedFile, validatedFile + '.invalid');
|
|
1015
|
-
continue;
|
|
1016
|
-
}
|
|
1017
|
-
} catch (e: any) {
|
|
1018
|
-
console.log(` ✗ Error generating transformer for model ${modelId}:`, e instanceof Error ? e.message : e);
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
})();
|
|
1022
|
-
workers.push(worker);
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
await Promise.all(workers);
|
|
1026
|
-
|
|
1027
|
-
console.log(`\n✓ Generated transformers for ${transformingModels.length} models in ${path.join(cacheDir, 'replicate')}\n`);
|
|
1028
|
-
|
|
1029
|
-
// Generate index file
|
|
1030
|
-
const transformerTarget = path.join(__dirname, '../../src/transformers/replicate');
|
|
1031
|
-
const transformerFiles = await fs.readdir(transformerTarget);
|
|
1032
|
-
const transformerSet = new Set(
|
|
1033
|
-
transformerFiles
|
|
1034
|
-
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
|
|
1035
|
-
.map((f) => f.replace('.ts', ''))
|
|
1036
|
-
);
|
|
1037
|
-
|
|
1038
|
-
// // For each file
|
|
1039
|
-
// import name from './name.ts';
|
|
1040
|
-
|
|
1041
|
-
// // Final export
|
|
1042
|
-
// export const replicateTransformers: Record<string, ReplicateTransformer> = {
|
|
1043
|
-
// ...name,
|
|
1044
|
-
// };
|
|
1045
|
-
|
|
1046
|
-
await fs.writeFile(
|
|
1047
|
-
path.join(transformerTarget, 'index.ts'),
|
|
1048
|
-
`
|
|
1049
|
-
import { ReplicateTransformer } from '@aeye/replicate';
|
|
1050
|
-
|
|
1051
|
-
${Array.from(transformerSet).map((name) => `import ${name.replace(/-/g, '_')} from './${name}';`).join('\n')}
|
|
1052
|
-
|
|
1053
|
-
export const replicateTransformers: Record<string, ReplicateTransformer> = {
|
|
1054
|
-
${Array.from(transformerSet).map((name) => `...${name.replace(/-/g, '_')},`).join('\n ')}
|
|
1055
|
-
};`.trim()
|
|
1056
|
-
);
|
|
1057
|
-
|
|
1058
|
-
console.log(`✓ Generated Replicate transformers index file\n`);
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
// Save JSON for reference
|
|
1063
|
-
await fs.writeFile(
|
|
1064
|
-
path.join(outputDir, 'replicate-modelinfo.json'),
|
|
1065
|
-
JSON.stringify(modelInfos, jsonReplacer, 2)
|
|
1066
|
-
);
|
|
1067
|
-
console.log(`✓ Saved ${modelInfos.length} models to JSON`);
|
|
1068
|
-
|
|
1069
|
-
// Generate TypeScript file
|
|
1070
|
-
const srcDir = path.join(__dirname, '../../src/models');
|
|
1071
|
-
await writeModelTS(modelInfos, 'replicateModels', path.join(srcDir, 'replicate.ts'));
|
|
1072
|
-
console.log(`✓ Generated TypeScript file: src/models/replicate.ts`);
|
|
1073
|
-
|
|
1074
|
-
console.log('\n✓ Replicate scraping complete\n');
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
function isValidTypeScript(file: string): Promise<boolean> {
|
|
1078
|
-
return new Promise((resolve, reject) => {
|
|
1079
|
-
const tsc = spawn('npx', ['tsc', '--noEmit', '--skipLibCheck', file], {
|
|
1080
|
-
shell: true,
|
|
1081
|
-
});
|
|
1082
|
-
|
|
1083
|
-
tsc.on('close', (code) => {
|
|
1084
|
-
if (code === 0) {
|
|
1085
|
-
resolve(true);
|
|
1086
|
-
} else {
|
|
1087
|
-
resolve(false);
|
|
1088
|
-
}
|
|
1089
|
-
});
|
|
1090
|
-
|
|
1091
|
-
tsc.on('error', (error) => {
|
|
1092
|
-
reject(error);
|
|
1093
|
-
});
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
// CLI execution
|
|
1098
|
-
if (process.argv[1].endsWith('replicate.ts')) {
|
|
1099
|
-
const cleanArg = (a: string) => (/^["'`](.*)["'`]$/.exec(a) || ['', a])[1];
|
|
1100
|
-
|
|
1101
|
-
const args = process.argv.slice(2).map(cleanArg);
|
|
1102
|
-
|
|
1103
|
-
const outputDir = args.find((arg) => !arg.startsWith('--')) || path.join(__dirname, '../../data');
|
|
1104
|
-
const cacheDir = args.find((arg, i) => i > 0 && !arg.startsWith('--') && !args[i - 1].startsWith('--')) || path.join(__dirname, '../../cache');
|
|
1105
|
-
|
|
1106
|
-
const concurrencyArg = args.find((arg) => arg.startsWith('--concurrency='));
|
|
1107
|
-
const concurrency = concurrencyArg
|
|
1108
|
-
? parseInt(concurrencyArg.split('=')[1], 10)
|
|
1109
|
-
: 50;
|
|
1110
|
-
|
|
1111
|
-
const transformers = args.includes('--transformers');
|
|
1112
|
-
|
|
1113
|
-
const transformersOnly = args.includes('--transformers-only');
|
|
1114
|
-
|
|
1115
|
-
const transformerModelArg = args.find((arg) => arg.startsWith('--transformer-model='));
|
|
1116
|
-
const transformerModel = transformerModelArg
|
|
1117
|
-
? cleanArg(transformerModelArg.split('=', 2)[1])
|
|
1118
|
-
: 'google/gemini-2.5-pro';
|
|
1119
|
-
|
|
1120
|
-
const modelsArg = args.find((arg) => arg.startsWith('--models='));
|
|
1121
|
-
let models: string[] | undefined = undefined;
|
|
1122
|
-
if (modelsArg) {
|
|
1123
|
-
models = modelsArg.substring(9).split(',').map((m) => m.trim());
|
|
1124
|
-
models = models.map(cleanArg)
|
|
1125
|
-
models = models.filter((m) => m.length > 0);
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
const nArg = args.find((arg) => arg.startsWith('--n='));;
|
|
1129
|
-
const n = nArg ? parseInt(cleanArg(nArg.split('=')[1]), 10) : undefined;
|
|
1130
|
-
|
|
1131
|
-
const transformConcurrencyArg = args.find((arg) => arg.startsWith('--transform-concurrency='));
|
|
1132
|
-
const transformConcurrency = transformConcurrencyArg
|
|
1133
|
-
? parseInt(transformConcurrencyArg.split('=')[1], 10)
|
|
1134
|
-
: concurrency;
|
|
1135
|
-
|
|
1136
|
-
const params = { concurrency, transformers, transformersOnly, transformerModel, transformConcurrency, models, n };
|
|
1137
|
-
|
|
1138
|
-
console.debug('Scrape parameters:', { outputDir, cacheDir, ...params });
|
|
1139
|
-
|
|
1140
|
-
scrapeReplicate(outputDir, cacheDir, params).catch((error) => {
|
|
1141
|
-
console.error('✗ Replicate scraping failed:', error);
|
|
1142
|
-
process.exit(1);
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Replicate Model Scraper
|
|
3
|
+
*
|
|
4
|
+
* Fetches model information from Replicate API using the Replicate npm module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ModelCapability, ModelInfo } from '@aeye/ai';
|
|
8
|
+
import { AI, detectTier } from '@aeye/ai';
|
|
9
|
+
import { OpenRouterProvider } from '@aeye/openrouter';
|
|
10
|
+
import * as fs from 'fs/promises';
|
|
11
|
+
import openapiTS from 'openapi-typescript';
|
|
12
|
+
import * as path from 'path';
|
|
13
|
+
import Replicate from 'replicate';
|
|
14
|
+
import ts from 'typescript';
|
|
15
|
+
import * as url from 'url';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
import { writeModelTS } from '../codegen';
|
|
18
|
+
import { exec, spawn } from 'child_process';
|
|
19
|
+
|
|
20
|
+
const __filename = url.fileURLToPath(import.meta.url);
|
|
21
|
+
const __dirname = path.dirname(__filename);
|
|
22
|
+
|
|
23
|
+
interface ReplicateModelData {
|
|
24
|
+
url: string;
|
|
25
|
+
owner: string;
|
|
26
|
+
name: string;
|
|
27
|
+
description: string | null;
|
|
28
|
+
visibility: string;
|
|
29
|
+
github_url: string | null;
|
|
30
|
+
paper_url: string | null;
|
|
31
|
+
license_url: string | null;
|
|
32
|
+
run_count: number;
|
|
33
|
+
cover_image_url: string | null;
|
|
34
|
+
default_example: {
|
|
35
|
+
model: string;
|
|
36
|
+
version: string;
|
|
37
|
+
input: Record<string, unknown>;
|
|
38
|
+
output: unknown;
|
|
39
|
+
} | null;
|
|
40
|
+
latest_version: {
|
|
41
|
+
id: string;
|
|
42
|
+
created_at: string;
|
|
43
|
+
cog_version: string;
|
|
44
|
+
openapi_schema: {
|
|
45
|
+
info: {
|
|
46
|
+
title: string;
|
|
47
|
+
version: string;
|
|
48
|
+
};
|
|
49
|
+
paths: Record<string, unknown>;
|
|
50
|
+
components: {
|
|
51
|
+
schemas: {
|
|
52
|
+
Input?: {
|
|
53
|
+
type: string;
|
|
54
|
+
properties: Record<string, unknown>;
|
|
55
|
+
required?: string[];
|
|
56
|
+
};
|
|
57
|
+
Output?: {
|
|
58
|
+
type: string;
|
|
59
|
+
properties?: Record<string, unknown>;
|
|
60
|
+
items?: unknown;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
} | null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Detect capabilities from model name, description, and schema
|
|
70
|
+
*/
|
|
71
|
+
function detectCapabilities(model: ReplicateModelData): Set<ModelCapability> {
|
|
72
|
+
const capabilities = new Set<ModelCapability>();
|
|
73
|
+
|
|
74
|
+
const lowerName = model.name.toLowerCase();
|
|
75
|
+
const lowerDesc = (model.description || '').toLowerCase();
|
|
76
|
+
|
|
77
|
+
// Image generation
|
|
78
|
+
if (
|
|
79
|
+
lowerName.includes('stable-diffusion') ||
|
|
80
|
+
lowerName.includes('sdxl') ||
|
|
81
|
+
lowerName.includes('flux') ||
|
|
82
|
+
lowerName.includes('imagen') ||
|
|
83
|
+
lowerName.includes('midjourney') ||
|
|
84
|
+
lowerName.includes('dalle') ||
|
|
85
|
+
lowerDesc.includes('image generation') ||
|
|
86
|
+
lowerDesc.includes('image edit') ||
|
|
87
|
+
lowerDesc.includes('text-to-image')
|
|
88
|
+
) {
|
|
89
|
+
capabilities.add('image');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Vision/image input
|
|
93
|
+
if (
|
|
94
|
+
lowerName.includes('vision') ||
|
|
95
|
+
lowerName.includes('image-to-text') ||
|
|
96
|
+
lowerDesc.includes('image analysis') ||
|
|
97
|
+
lowerDesc.includes('image understanding') ||
|
|
98
|
+
lowerDesc.includes('image edit')
|
|
99
|
+
) {
|
|
100
|
+
capabilities.add('vision');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Transcription/hearing
|
|
104
|
+
if (
|
|
105
|
+
lowerName.includes('whisper') ||
|
|
106
|
+
lowerName.includes('transcribe') ||
|
|
107
|
+
lowerDesc.includes('speech-to-text') ||
|
|
108
|
+
lowerDesc.includes('transcription')
|
|
109
|
+
) {
|
|
110
|
+
capabilities.add('hearing');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Speech/audio output
|
|
114
|
+
if (
|
|
115
|
+
lowerName.includes('tts') ||
|
|
116
|
+
lowerName.includes('speech') ||
|
|
117
|
+
lowerName.includes('voice') ||
|
|
118
|
+
lowerDesc.includes('text-to-speech')
|
|
119
|
+
) {
|
|
120
|
+
capabilities.add('audio');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Embeddings
|
|
124
|
+
if (lowerName.includes('embed') || lowerDesc.includes('embedding')) {
|
|
125
|
+
capabilities.add('embedding');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Chat/language models
|
|
129
|
+
if (
|
|
130
|
+
lowerName.includes('llm') ||
|
|
131
|
+
lowerName.includes('chat') ||
|
|
132
|
+
lowerName.includes('gpt') ||
|
|
133
|
+
lowerName.includes('llama') ||
|
|
134
|
+
lowerName.includes('mistral') ||
|
|
135
|
+
lowerName.includes('gemma') ||
|
|
136
|
+
lowerName.includes('vicuna') ||
|
|
137
|
+
lowerDesc.includes('language model') ||
|
|
138
|
+
lowerDesc.includes('conversational')
|
|
139
|
+
) {
|
|
140
|
+
capabilities.add('chat');
|
|
141
|
+
capabilities.add('streaming');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// If no capabilities detected but has a schema, add chat as default
|
|
145
|
+
if (capabilities.size === 0 && model.latest_version?.openapi_schema) {
|
|
146
|
+
capabilities.add('chat');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return capabilities;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Convert Replicate model to ModelInfo
|
|
154
|
+
*/
|
|
155
|
+
function convertReplicateModel(model: ReplicateModelData): ModelInfo {
|
|
156
|
+
const modelId = `${model.owner}/${model.name}`;
|
|
157
|
+
const capabilities = detectCapabilities(model);
|
|
158
|
+
const tier = detectTier(model.name);
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
provider: 'replicate',
|
|
162
|
+
id: modelId,
|
|
163
|
+
name: model.name,
|
|
164
|
+
capabilities: capabilities, // Already an array
|
|
165
|
+
tier,
|
|
166
|
+
pricing: {},
|
|
167
|
+
contextWindow: 0, // Not consistently available in Replicate API
|
|
168
|
+
maxOutputTokens: undefined,
|
|
169
|
+
metadata: {
|
|
170
|
+
owner: model.owner,
|
|
171
|
+
description: model.description,
|
|
172
|
+
runCount: model.run_count,
|
|
173
|
+
githubUrl: model.github_url,
|
|
174
|
+
// paperUrl: model.paper_url,
|
|
175
|
+
// coverImageUrl: model.cover_image_url,
|
|
176
|
+
visibility: model.visibility,
|
|
177
|
+
source: 'replicate',
|
|
178
|
+
latestVersionId: model.latest_version?.id,
|
|
179
|
+
cogVersion: model.latest_version?.cog_version,
|
|
180
|
+
// schema: model.latest_version?.openapi_schema,
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const ai = AI
|
|
186
|
+
.with()
|
|
187
|
+
.providers({
|
|
188
|
+
openrouter: new OpenRouterProvider({
|
|
189
|
+
apiKey: process.env.OPENROUTER_API_KEY!,
|
|
190
|
+
hooks: {
|
|
191
|
+
chat: {
|
|
192
|
+
beforeRequest: (a, b, c, d) => {
|
|
193
|
+
const now = Date.now().toString();
|
|
194
|
+
|
|
195
|
+
const requestResolved = path.resolve(__dirname, '../../cache/replicate', now + '-request.json');
|
|
196
|
+
fs.writeFile(requestResolved, JSON.stringify(b, null, 2));
|
|
197
|
+
|
|
198
|
+
const content = a.messages.map((m) => m.content).join('\n---\n');
|
|
199
|
+
const contentResolved = path.resolve(__dirname, '../../cache/replicate', now + '-content.txt');
|
|
200
|
+
fs.writeFile(contentResolved, content);
|
|
201
|
+
},
|
|
202
|
+
afterRequest: (a, b, c, d) => {
|
|
203
|
+
const now = Date.now().toString();
|
|
204
|
+
|
|
205
|
+
const responseResolved = path.resolve(__dirname, '../../cache/replicate', now + '-response.json');
|
|
206
|
+
fs.writeFile(responseResolved, JSON.stringify(c, null, 2));
|
|
207
|
+
|
|
208
|
+
const content = c.content;
|
|
209
|
+
const contentResolved = path.resolve(__dirname, '../../cache/replicate', now + '-response.txt');
|
|
210
|
+
fs.writeFile(contentResolved, content);
|
|
211
|
+
},
|
|
212
|
+
onError: (a, b, e, d) => {
|
|
213
|
+
const now = Date.now().toString();
|
|
214
|
+
|
|
215
|
+
const errorResolved = path.resolve(__dirname, '../../cache/replicate', now + '-error.txt');
|
|
216
|
+
fs.writeFile(errorResolved, String(e));
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
}),
|
|
221
|
+
})
|
|
222
|
+
.create({})
|
|
223
|
+
;
|
|
224
|
+
|
|
225
|
+
const jsonReplacer = (key: string, value: any) => {
|
|
226
|
+
if (value instanceof Set) {
|
|
227
|
+
return Array.from(value);
|
|
228
|
+
}
|
|
229
|
+
return value;
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const typeInfo = await fs.readFile(path.join(__dirname, 'extract.md'), 'utf-8');
|
|
233
|
+
|
|
234
|
+
const optionalTransform = (val: any) =>
|
|
235
|
+
!val || Object.values(val).every((v) => v === null || v === undefined)
|
|
236
|
+
? undefined
|
|
237
|
+
: Object.fromEntries(Object.entries(val).filter(([_, v]) => v !== null && v !== undefined));
|
|
238
|
+
|
|
239
|
+
const extract = ai.prompt({
|
|
240
|
+
name: 'extract',
|
|
241
|
+
description: 'Extract model information & a transformer definition from Replicate model data',
|
|
242
|
+
content: `Extract model information & a transformer definition from the following data.
|
|
243
|
+
|
|
244
|
+
<modelData>
|
|
245
|
+
{{modelData}}
|
|
246
|
+
</modelData>
|
|
247
|
+
|
|
248
|
+
{{#if modelTypes}}
|
|
249
|
+
Here are the types for the model based on the OpenAPI schema:
|
|
250
|
+
\`\`\`ts
|
|
251
|
+
{{modelTypes}}
|
|
252
|
+
\`\`\`
|
|
253
|
+
|
|
254
|
+
Schemas["Input"] is what convertRequest should return.
|
|
255
|
+
Schemas["Output"] is what parseResponse is given as the first argument.
|
|
256
|
+
|
|
257
|
+
These types will be available and can be referenced like above to ensure type safety.
|
|
258
|
+
{{/if}}
|
|
259
|
+
|
|
260
|
+
Create a TypeScript implementation of a ReplicateTransformer for the model.
|
|
261
|
+
Here's an example transformer implementation for reference. This is the exact format to follow:
|
|
262
|
+
<exampleTransformerImplementation>
|
|
263
|
+
{
|
|
264
|
+
// this key comes from modelData.owner/modelData.name
|
|
265
|
+
// // The definition is wrapped in an immediately-invoked function expression so any cached or reusable functions can be defined here.
|
|
266
|
+
"google/nano-banana": (() => {
|
|
267
|
+
// you must use this ReplicateTransformer type to avoid TypeScript errors
|
|
268
|
+
const transformer: ReplicateTransformer = {
|
|
269
|
+
imageGenerate: {
|
|
270
|
+
// only use variable known to be in this request type based on the types below
|
|
271
|
+
convertRequest: async (request, ctx){{#if modelTypes}}: Promise<Schemas["Input"]>{{/if}} => ({
|
|
272
|
+
prompt: request.prompt,
|
|
273
|
+
...request.extra, // always spread extra to allow for additional parameters
|
|
274
|
+
}),
|
|
275
|
+
// only use known output schema from the model and only use properties expected on the response type based on the types below
|
|
276
|
+
parseResponse: async (response{{#if modelTypes}}: Schemas["Output"]{{/if}}, ctx) => ({
|
|
277
|
+
images: [{ url: await toURL(response) }],
|
|
278
|
+
extra: { response }, // include full response in extra object
|
|
279
|
+
}),
|
|
280
|
+
},
|
|
281
|
+
imageEdit: {
|
|
282
|
+
convertRequest: async (request, ctx){{#if modelTypes}}: Promise<Schemas["Input"]>{{/if}} => ({
|
|
283
|
+
prompt: request.prompt,
|
|
284
|
+
image_input: [await toURL(request.image)],
|
|
285
|
+
...request.extra, // always spread extra to allow for additional parameters
|
|
286
|
+
}),
|
|
287
|
+
parseResponse: async (response{{#if modelTypes}}: Schemas["Output"]{{/if}}, ctx) => ({
|
|
288
|
+
images: [{ url: await toURL(response) }],
|
|
289
|
+
extra: { response }, // include full response in extra object
|
|
290
|
+
}),
|
|
291
|
+
},
|
|
292
|
+
};
|
|
293
|
+
return transformer;
|
|
294
|
+
})(), // immediately invoke the function to return the typed transformer
|
|
295
|
+
}
|
|
296
|
+
</exampleTransformerImplementation>
|
|
297
|
+
|
|
298
|
+
The transformer code you return should match EXACTLY the format above. It will be injected in code like so by the developer:
|
|
299
|
+
<transformerResult>
|
|
300
|
+
import { toURL, toBase64, toText, toStream, toReadableStream, toFile } from '@aeye/core';
|
|
301
|
+
import { ReplicateTransformer } from '@aeye/replicate';
|
|
302
|
+
|
|
303
|
+
const transformer: Record<string, ReplicateTransformer> = <transformerImplementation>;
|
|
304
|
+
</transformerResult>
|
|
305
|
+
|
|
306
|
+
<availableFunctions>
|
|
307
|
+
- \`toURL(resource, mimeType?: string, fallback?: string): Promise<string>\` converts to URL string
|
|
308
|
+
- \`toBase64(resource, mimeType?: string, fallback?: string): Promise<string>\`
|
|
309
|
+
- \`toText(resource, fallback?: string): Promise<string>\`
|
|
310
|
+
- \`toStream(resource, fallback?: Readable): Promise<Readable>\`
|
|
311
|
+
- \`toReadableStream(resource, fallback?: ReadableStream): Promise<ReadableStream>\`
|
|
312
|
+
- \`toFile(resource, mimeType?: string, filename?: string): Promise<File>\`
|
|
313
|
+
</availableFunctions>
|
|
314
|
+
|
|
315
|
+
Here's how the replicate code looks around the transformer: This is an example to illustrate how the transformer you generate is used.
|
|
316
|
+
<replicateCode>
|
|
317
|
+
// =============================================================
|
|
318
|
+
// Execute
|
|
319
|
+
// =============================================================
|
|
320
|
+
const { convertRequest, parseResponse } = transformer;
|
|
321
|
+
const client = new Replicate({ /* config */ });
|
|
322
|
+
const input = await convertRequest(request, ctx);
|
|
323
|
+
const output = await client.run(modelId, { input, signal });
|
|
324
|
+
const response = await parseResponse(output, ctx);
|
|
325
|
+
|
|
326
|
+
// =============================================================
|
|
327
|
+
// Stream
|
|
328
|
+
// =============================================================
|
|
329
|
+
const { convertRequest, parseChunk } = transformer;
|
|
330
|
+
const client = new Replicate({ /* config */ });
|
|
331
|
+
const input = await convertRequest(request, ctx);
|
|
332
|
+
for await (const event of client.stream(modelId, { input, signal })) {
|
|
333
|
+
if (signal?.aborted) {
|
|
334
|
+
throw new Error('Request aborted');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Parse chunk using transformer
|
|
338
|
+
const chunk = await parseChunk(event, ctx);
|
|
339
|
+
yield chunk;
|
|
340
|
+
}
|
|
341
|
+
</replicateCode>
|
|
342
|
+
|
|
343
|
+
Here is type information you need to use to understand the shape of all the types:
|
|
344
|
+
It is EXTREMELY important you only use properties that are guaranteed to be present based on the types below when it comes to transformer, request, response, and chunk types.
|
|
345
|
+
The request parameters in the converted request should only be the properties that are known to be in the input schema for the model. The rest may be passed in via \`extra\` property.
|
|
346
|
+
<typeInfo>
|
|
347
|
+
{{typeInfo}}
|
|
348
|
+
</typeInfo>
|
|
349
|
+
`,
|
|
350
|
+
strict: true,
|
|
351
|
+
outputRetries: 3,
|
|
352
|
+
schema: z.object({
|
|
353
|
+
transformerImplementation: z.string()
|
|
354
|
+
// .regex(/^\{\n\s+"[^"]+\/[^"]+": \(\(\) => \{(.|\r|\n)*\}\)\(\),\n\}$/)
|
|
355
|
+
.describe(`The TypeScript implementation of the model handler (without imports or \`\`\` marks) - described BETWEEN the <exampleTransformerImplementation> tags. Follow the rules outlined.`),
|
|
356
|
+
modelInfo: z.object({
|
|
357
|
+
capabilities: z.array(z.enum([
|
|
358
|
+
'chat',
|
|
359
|
+
'tools',
|
|
360
|
+
'vision',
|
|
361
|
+
'json',
|
|
362
|
+
'structured',
|
|
363
|
+
'streaming',
|
|
364
|
+
'reasoning',
|
|
365
|
+
'image',
|
|
366
|
+
'audio',
|
|
367
|
+
'hearing',
|
|
368
|
+
'embedding',
|
|
369
|
+
'zdr'
|
|
370
|
+
])).describe(`Set of capabilities this model supports:
|
|
371
|
+
|
|
372
|
+
- chat: Text input & output
|
|
373
|
+
- tools: Ability to make tool calls
|
|
374
|
+
- vision: Image inputs
|
|
375
|
+
- json: Supports JSON response format
|
|
376
|
+
- structured: Supports structured output (strict JSON response format)
|
|
377
|
+
- streaming: Supports streaming responses
|
|
378
|
+
- reasoning: Enhanced reasoning capabilities
|
|
379
|
+
- image: Image output
|
|
380
|
+
- audio: Audio output
|
|
381
|
+
- hearing: Audio input
|
|
382
|
+
- embedding: Text -> embedding generation
|
|
383
|
+
- zdr: Supports zero-data-retention through a parameter`),
|
|
384
|
+
tier: z.enum(['flagship', 'efficient', 'legacy', 'experimental']).describe(`Model performance and quality tiers.
|
|
385
|
+
Used for categorizing models by their capabilities and cost.
|
|
386
|
+
|
|
387
|
+
- flagship: Top-tier models with best performance
|
|
388
|
+
- efficient: Smaller, faster, more cost-effective models
|
|
389
|
+
- legacy: Older models, may be deprecated
|
|
390
|
+
- experimental: Preview/beta models`),
|
|
391
|
+
pricing: z.object({
|
|
392
|
+
text: z.object({
|
|
393
|
+
input: z.number().optional(),
|
|
394
|
+
output: z.number().optional(),
|
|
395
|
+
cached: z.number().optional(),
|
|
396
|
+
}).optional()
|
|
397
|
+
.transform(optionalTransform),
|
|
398
|
+
audio: z.object({
|
|
399
|
+
input: z.number().optional(),
|
|
400
|
+
output: z.number().optional(),
|
|
401
|
+
perSecond: z.number().optional(),
|
|
402
|
+
}).optional()
|
|
403
|
+
.transform(optionalTransform),
|
|
404
|
+
image: z.object({
|
|
405
|
+
input: z.number().optional(),
|
|
406
|
+
output: z.array(z.object({
|
|
407
|
+
quality: z.string().describe('Quality level - like low, medium, high'),
|
|
408
|
+
sizes: z.array(z.object({
|
|
409
|
+
width: z.number(),
|
|
410
|
+
height: z.number(),
|
|
411
|
+
cost: z.number().describe('Cost per image in USD'),
|
|
412
|
+
})).describe('Supported image sizes and their costs'),
|
|
413
|
+
})).optional()
|
|
414
|
+
.transform(optionalTransform),
|
|
415
|
+
}).optional()
|
|
416
|
+
.transform(optionalTransform),
|
|
417
|
+
reasoning: z.object({
|
|
418
|
+
input: z.number().optional(),
|
|
419
|
+
output: z.number().optional(),
|
|
420
|
+
cached: z.number().optional(),
|
|
421
|
+
}).optional()
|
|
422
|
+
.transform(optionalTransform),
|
|
423
|
+
embeddings: z.object({
|
|
424
|
+
cost: z.number().optional(),
|
|
425
|
+
}).optional()
|
|
426
|
+
.transform(optionalTransform),
|
|
427
|
+
perRequest: z.number().optional().describe('Flat cost per request in USD'),
|
|
428
|
+
}).describe('Pricing information. input/output/cached are per 1 million tokens unless otherwise specified. Leave null/undefined if unknown - 0 is free. Do not specify 0 unless it is free.'),
|
|
429
|
+
contextWindow: z.number(),
|
|
430
|
+
maxOutputTokens: z.number().optional(),
|
|
431
|
+
metrics: z.object({
|
|
432
|
+
tokensPerSecond: z.number().optional().describe('Processing speed in tokens per second'),
|
|
433
|
+
timeToFirstToken: z.number().optional().describe('Time to first token in milliseconds'),
|
|
434
|
+
averageRequestDuration: z.number().optional().describe('Average request duration in milliseconds'),
|
|
435
|
+
accuracyScore: z.number().optional().describe('Accuracy score based on benchmark tests 0-1'),
|
|
436
|
+
}).optional()
|
|
437
|
+
.transform(optionalTransform)
|
|
438
|
+
.describe('Performance metrics if available'),
|
|
439
|
+
tokenizer: z.enum(([
|
|
440
|
+
'Other', 'GPT', 'Mistral', 'Llama3', 'Qwen3', 'Qwen', 'Gemini', 'DeepSeek', 'Claude', 'Grok', 'Llama4', 'Llama2', 'Cohere', 'Nova', 'Router'
|
|
441
|
+
])).optional().describe('The tokenizer type used by this model if known, otherwise leave undefined'),
|
|
442
|
+
supportedParameters: z.array(z.enum([
|
|
443
|
+
// Chat Request
|
|
444
|
+
'maxTokens', // max_tokens / max_completion_tokens
|
|
445
|
+
'temperature', // temperature
|
|
446
|
+
'topP', // top_p
|
|
447
|
+
'frequencyPenalty', // frequency_penalty
|
|
448
|
+
'presencePenalty', // presence_penalty
|
|
449
|
+
'stop', // stop
|
|
450
|
+
'seed', // seed
|
|
451
|
+
'responseFormat', // response_format
|
|
452
|
+
'structuredOutput', // structured_outputs
|
|
453
|
+
'tools', // tools
|
|
454
|
+
'toolChoice', // tool_choice
|
|
455
|
+
'logitBias', // logit_bias
|
|
456
|
+
'logProbabilities', // logprobs
|
|
457
|
+
'reason', // reasoning
|
|
458
|
+
// Image
|
|
459
|
+
'imageBackground', // background
|
|
460
|
+
'imageMultiple', // n
|
|
461
|
+
'imageFormat', // output_format ()
|
|
462
|
+
'imageStream', // stream / partial_images
|
|
463
|
+
'imageStyle',
|
|
464
|
+
// Embedding
|
|
465
|
+
'embeddingDimensions', // dimensions
|
|
466
|
+
// Transcription
|
|
467
|
+
'transcribeStream', // stream
|
|
468
|
+
'transcribePrompt', // prompt
|
|
469
|
+
// Speech
|
|
470
|
+
'speechInstructions', // instructions
|
|
471
|
+
])).optional().describe('The supported parameters for this model'),
|
|
472
|
+
}).describe('The extracted model information'),
|
|
473
|
+
}),
|
|
474
|
+
input: async ({ modelData, modelTypes }: { model: string, modelData: ReplicateModelData, modelTypes: string }) => {
|
|
475
|
+
return {
|
|
476
|
+
modelData: JSON.stringify(modelData, (k, v) => {
|
|
477
|
+
if (k === "embeddings" && Array.isArray(v) && v.length > 20) {
|
|
478
|
+
return [`...${v.length} ${typeof v[0]}s...`];
|
|
479
|
+
}
|
|
480
|
+
if (Array.isArray(v) && v.length > 20) {
|
|
481
|
+
return [`...${v.length} ${typeof v[0]}s...`];
|
|
482
|
+
}
|
|
483
|
+
return v;
|
|
484
|
+
}, 2),
|
|
485
|
+
typeInfo,
|
|
486
|
+
modelTypes,
|
|
487
|
+
};
|
|
488
|
+
},
|
|
489
|
+
config: (input) => ({
|
|
490
|
+
model: input?.model,
|
|
491
|
+
temperature: 0,
|
|
492
|
+
topP: 1,
|
|
493
|
+
}),
|
|
494
|
+
})
|
|
495
|
+
|
|
496
|
+
async function extractTypes(model: ReplicateModelData): Promise<string> {
|
|
497
|
+
if (!model.latest_version?.openapi_schema) {
|
|
498
|
+
return '';
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
let extracted = await extractSchemasString(model.latest_version.openapi_schema as any);
|
|
502
|
+
if (!extracted) {
|
|
503
|
+
return '';
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
return extracted.replaceAll('components["schemas"]', 'Schemas').replaceAll(' ', ' ');
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async function extractSchemasString(schemaObject: any): Promise<string> {
|
|
510
|
+
try {
|
|
511
|
+
const ast = await openapiTS(schemaObject, {
|
|
512
|
+
propertiesRequiredByDefault: false,
|
|
513
|
+
defaultNonNullable: false,
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
const printer = ts.createPrinter({
|
|
517
|
+
newLine: ts.NewLineKind.LineFeed,
|
|
518
|
+
removeComments: true,
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
const dummySourceFile = ts.createSourceFile("temp.ts", "", ts.ScriptTarget.ESNext, true);
|
|
522
|
+
|
|
523
|
+
const componentsNode = ast.find(node => {
|
|
524
|
+
if (ts.isInterfaceDeclaration(node)) {
|
|
525
|
+
const name = printer.printNode(ts.EmitHint.Unspecified, node.name, dummySourceFile);
|
|
526
|
+
return name === 'components';
|
|
527
|
+
}
|
|
528
|
+
return false;
|
|
529
|
+
}) as ts.InterfaceDeclaration | undefined;
|
|
530
|
+
|
|
531
|
+
if (!componentsNode) {
|
|
532
|
+
console.error("Error: Could not find the 'components' node in the generated AST.");
|
|
533
|
+
return "";
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
let extractedMembersString = "";
|
|
537
|
+
|
|
538
|
+
// Get the inner content of the 'schemas' property
|
|
539
|
+
for (const member of componentsNode.members) {
|
|
540
|
+
if (ts.isPropertySignature(member)) {
|
|
541
|
+
const propName = printer.printNode(ts.EmitHint.Unspecified, member.name, dummySourceFile);
|
|
542
|
+
|
|
543
|
+
if (propName === 'schemas' && member.type && ts.isTypeLiteralNode(member.type)) {
|
|
544
|
+
member.type.members.forEach(schemaMember => {
|
|
545
|
+
extractedMembersString += printer.printNode(ts.EmitHint.Unspecified, schemaMember, dummySourceFile) + "\n";
|
|
546
|
+
});
|
|
547
|
+
break;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (!extractedMembersString.trim()) {
|
|
553
|
+
console.error("Error: Found no user-defined schema types within the 'components.schemas' structure.");
|
|
554
|
+
return "";
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
return `type Schemas = {\n ${extractedMembersString.replaceAll('\n', '\n ').trim()}\n};`;
|
|
558
|
+
} catch (error) {
|
|
559
|
+
console.error("An unexpected error occurred during schema extraction:", error);
|
|
560
|
+
return "";
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Fetch all models from Replicate collections
|
|
566
|
+
*/
|
|
567
|
+
async function fetchAllModels(apiKey?: string): Promise<ReplicateModelData[]> {
|
|
568
|
+
console.log('Fetching Replicate models...');
|
|
569
|
+
|
|
570
|
+
const client = new Replicate({
|
|
571
|
+
auth: apiKey || process.env.REPLICATE_API_KEY,
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
const allModels: ReplicateModelData[] = [];
|
|
575
|
+
const seenModels = new Set<string>();
|
|
576
|
+
|
|
577
|
+
// Collections to scrape
|
|
578
|
+
const collections = [
|
|
579
|
+
'text-to-image',
|
|
580
|
+
'image-to-text',
|
|
581
|
+
'text-to-speech',
|
|
582
|
+
'speech-to-text',
|
|
583
|
+
'super-resolution',
|
|
584
|
+
'image-editing',
|
|
585
|
+
'ai-face-generator',
|
|
586
|
+
'ai-music-generation',
|
|
587
|
+
'text-recognition-ocr',
|
|
588
|
+
'flux',
|
|
589
|
+
'ai-image-restoration',
|
|
590
|
+
'text-classification',
|
|
591
|
+
'sketch-to-image',
|
|
592
|
+
'embedding-models',
|
|
593
|
+
'vision-models',
|
|
594
|
+
];
|
|
595
|
+
|
|
596
|
+
console.log(`Fetching models from ${collections.length} collections...`);
|
|
597
|
+
|
|
598
|
+
for (const collectionSlug of collections) {
|
|
599
|
+
try {
|
|
600
|
+
console.log(` Fetching collection: ${collectionSlug}...`);
|
|
601
|
+
|
|
602
|
+
const collection = await client.collections.get(collectionSlug);
|
|
603
|
+
|
|
604
|
+
if (collection.models) {
|
|
605
|
+
for (const model of collection.models) {
|
|
606
|
+
const modelId = `${(model as any).owner}/${(model as any).name}`;
|
|
607
|
+
|
|
608
|
+
// Skip duplicates
|
|
609
|
+
if (seenModels.has(modelId)) {
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
seenModels.add(modelId);
|
|
614
|
+
allModels.push(model as ReplicateModelData);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
console.log(` ✓ Found ${collection.models.length} models in ${collectionSlug}`);
|
|
618
|
+
}
|
|
619
|
+
} catch (error) {
|
|
620
|
+
console.log(` ⚠ Failed to fetch collection ${collectionSlug}:`, error instanceof Error ? error.message : error);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
console.log(`\n✓ Fetched ${allModels.length} unique Replicate models`);
|
|
625
|
+
|
|
626
|
+
return allModels;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Fetch model details including schema (for cache)
|
|
631
|
+
*/
|
|
632
|
+
async function fetchModelSchema(
|
|
633
|
+
modelId: string,
|
|
634
|
+
client: Replicate
|
|
635
|
+
): Promise<{
|
|
636
|
+
modelId: string;
|
|
637
|
+
data: ReplicateModelData | null;
|
|
638
|
+
}> {
|
|
639
|
+
try {
|
|
640
|
+
const [owner, name] = modelId.split('/');
|
|
641
|
+
const model = await client.models.get(owner, name);
|
|
642
|
+
return { modelId, data: model as ReplicateModelData };
|
|
643
|
+
} catch (error) {
|
|
644
|
+
console.log(` ⚠ Failed to fetch model ${modelId}:`, error instanceof Error ? error.message : error);
|
|
645
|
+
return { modelId, data: null };
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Fetch schemas in parallel with concurrency control
|
|
651
|
+
*/
|
|
652
|
+
async function fetchSchemasParallel(
|
|
653
|
+
models: ReplicateModelData[],
|
|
654
|
+
apiKey: string,
|
|
655
|
+
concurrency: number = 50
|
|
656
|
+
): Promise<Record<string, ReplicateModelData>> {
|
|
657
|
+
console.log(`\nCaching detailed model schemas (concurrency: ${concurrency})...`);
|
|
658
|
+
|
|
659
|
+
const client = new Replicate({
|
|
660
|
+
auth: apiKey,
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
const schemasCache: Record<string, ReplicateModelData> = {};
|
|
664
|
+
|
|
665
|
+
// First, add models that already have schemas
|
|
666
|
+
for (const model of models) {
|
|
667
|
+
const modelId = `${model.owner}/${model.name}`;
|
|
668
|
+
if (model.latest_version?.openapi_schema) {
|
|
669
|
+
schemasCache[modelId] = model;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Find models that need schema fetching
|
|
674
|
+
const modelsToFetch = models.filter((model) => {
|
|
675
|
+
return !model.latest_version?.openapi_schema;
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
if (modelsToFetch.length === 0) {
|
|
679
|
+
console.log(`✓ All ${models.length} models already have schemas\n`);
|
|
680
|
+
return schemasCache;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
console.log(` ${Object.keys(schemasCache).length - modelsToFetch.length} models already have schemas`);
|
|
684
|
+
console.log(` Fetching schemas for ${modelsToFetch.length} models...\n`);
|
|
685
|
+
|
|
686
|
+
// Process in batches with concurrency control
|
|
687
|
+
const modelIdsToFetch = modelsToFetch.map((m) => `${m.owner}/${m.name}`);
|
|
688
|
+
|
|
689
|
+
for (let i = 0; i < modelIdsToFetch.length; i += concurrency) {
|
|
690
|
+
const batch = modelIdsToFetch.slice(i, i + concurrency);
|
|
691
|
+
console.log(` Processing batch ${Math.floor(i / concurrency) + 1}/${Math.ceil(modelIdsToFetch.length / concurrency)} (${batch.length} models)...`);
|
|
692
|
+
|
|
693
|
+
const batchResults = await Promise.all(
|
|
694
|
+
batch.map((modelId) => fetchModelSchema(modelId, client))
|
|
695
|
+
);
|
|
696
|
+
|
|
697
|
+
// Store results
|
|
698
|
+
for (const { modelId, data } of batchResults) {
|
|
699
|
+
if (data) {
|
|
700
|
+
schemasCache[modelId] = data;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
console.log(` ✓ Fetched ${batchResults.filter((r) => r.data).length}/${batch.length} schemas`);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
console.log(`\n✓ Cached ${Object.keys(schemasCache).length} model schemas\n`);
|
|
708
|
+
|
|
709
|
+
return schemasCache;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function cleanSchema(model: ReplicateModelData) {
|
|
713
|
+
const schema = model.latest_version?.openapi_schema as any;
|
|
714
|
+
if (schema) {
|
|
715
|
+
// delete schema.components.schemas.Status;
|
|
716
|
+
delete schema.components.schemas.WebhookEvent;
|
|
717
|
+
delete schema.components.schemas.ValidationError;
|
|
718
|
+
delete schema.components.schemas.PredictionRequest;
|
|
719
|
+
delete schema.components.schemas.PredictionResponse;
|
|
720
|
+
delete schema.components.schemas.HTTPValidationError;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Main scraper function
|
|
726
|
+
*/
|
|
727
|
+
export async function scrapeReplicate(
|
|
728
|
+
outputDir: string,
|
|
729
|
+
cacheDir?: string,
|
|
730
|
+
options: {
|
|
731
|
+
concurrency?: number,
|
|
732
|
+
transformers?: boolean,
|
|
733
|
+
transformerModel: string,
|
|
734
|
+
transformersOnly?: boolean,
|
|
735
|
+
transformConcurrency?: number,
|
|
736
|
+
models?: string[],
|
|
737
|
+
n?: number,
|
|
738
|
+
} = {
|
|
739
|
+
transformerModel: 'google/gemini-2.5-pro',
|
|
740
|
+
}
|
|
741
|
+
): Promise<void> {
|
|
742
|
+
const { concurrency = 50 } = options;
|
|
743
|
+
|
|
744
|
+
const apiKey = process.env.REPLICATE_API_KEY;
|
|
745
|
+
if (!apiKey) {
|
|
746
|
+
console.error('✗ REPLICATE_API_KEY environment variable is required');
|
|
747
|
+
process.exit(1);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
let models: ReplicateModelData[]
|
|
751
|
+
|
|
752
|
+
if (!options.transformersOnly) {
|
|
753
|
+
console.log('\n=== Replicate Scraper ===\n');
|
|
754
|
+
|
|
755
|
+
// Fetch all models from collections
|
|
756
|
+
models = await fetchAllModels(apiKey);
|
|
757
|
+
|
|
758
|
+
// Create output directory
|
|
759
|
+
await fs.mkdir(outputDir, { recursive: true });
|
|
760
|
+
|
|
761
|
+
// Save raw models data
|
|
762
|
+
await fs.writeFile(
|
|
763
|
+
path.join(outputDir, 'replicate-models.json'),
|
|
764
|
+
JSON.stringify({ data: models }, jsonReplacer, 2)
|
|
765
|
+
);
|
|
766
|
+
|
|
767
|
+
console.log(`✓ Saved raw Replicate models to replicate-models.json`);
|
|
768
|
+
} else {
|
|
769
|
+
const modelsData = await fs.readFile(
|
|
770
|
+
path.join(outputDir, 'replicate-models.json'),
|
|
771
|
+
'utf-8'
|
|
772
|
+
);
|
|
773
|
+
const parsed = JSON.parse(modelsData);
|
|
774
|
+
models = parsed.data as ReplicateModelData[];
|
|
775
|
+
|
|
776
|
+
console.log(`\n✓ Loaded ${models.length} Replicate models from cache\n`);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
models.forEach(cleanSchema);
|
|
780
|
+
|
|
781
|
+
// Sort models by owner/name
|
|
782
|
+
models.sort((a, b) => `${a.owner}/${a.name}`.localeCompare(`${b.owner}/${b.name}`));
|
|
783
|
+
|
|
784
|
+
// Convert to ModelInfo format
|
|
785
|
+
const modelInfos = models.map(convertReplicateModel);
|
|
786
|
+
|
|
787
|
+
try {
|
|
788
|
+
const modelInfoCache = await fs.readFile(
|
|
789
|
+
path.join(outputDir, 'replicate-modelinfo.json'),
|
|
790
|
+
'utf-8'
|
|
791
|
+
);
|
|
792
|
+
const parsed = JSON.parse(modelInfoCache) as ModelInfo[];
|
|
793
|
+
for (const info of parsed) {
|
|
794
|
+
const existing = modelInfos.findIndex((m) => m.id === info.id);
|
|
795
|
+
if (existing >= 0) {
|
|
796
|
+
modelInfos[existing] = info;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
} catch (e: any) {
|
|
800
|
+
// Ignore if file doesn't exist
|
|
801
|
+
console.error(`⚠ Could not load existing model info cache: ${e.message}`);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
let schemasCache: Record<string, ReplicateModelData> = {};
|
|
805
|
+
|
|
806
|
+
// Create cache directory if specified
|
|
807
|
+
if (cacheDir) {
|
|
808
|
+
if (!options.transformersOnly) {
|
|
809
|
+
await fs.mkdir(cacheDir, { recursive: true });
|
|
810
|
+
|
|
811
|
+
// Cache detailed model schemas (for transformer generation)
|
|
812
|
+
schemasCache = await fetchSchemasParallel(models, apiKey, concurrency);
|
|
813
|
+
|
|
814
|
+
// Save schemas cache
|
|
815
|
+
await fs.writeFile(
|
|
816
|
+
path.join(cacheDir, 'replicate-schemas.json'),
|
|
817
|
+
JSON.stringify(schemasCache, jsonReplacer, 2)
|
|
818
|
+
);
|
|
819
|
+
|
|
820
|
+
console.log(`✓ Saved ${Object.keys(schemasCache).length} model schemas to ${cacheDir}/replicate-schemas.json`);
|
|
821
|
+
console.log(' (This cache file is for transformer generation and should not be committed)');
|
|
822
|
+
|
|
823
|
+
// Chunk it up to 80,000 character files for easier loading later
|
|
824
|
+
const chunkSize = 80000;
|
|
825
|
+
const schemaEntries = Object.entries(schemasCache);
|
|
826
|
+
let currentChunk: Record<string, ReplicateModelData> = {};
|
|
827
|
+
let currentSize = 0;
|
|
828
|
+
let chunkIndex = 1;
|
|
829
|
+
for (const [modelId, modelData] of schemaEntries) {
|
|
830
|
+
const entryString = JSON.stringify({ [modelId]: modelData });
|
|
831
|
+
if (currentSize + entryString.length > chunkSize && Object.keys(currentChunk).length > 0) {
|
|
832
|
+
// Save current chunk
|
|
833
|
+
await fs.writeFile(
|
|
834
|
+
path.join(cacheDir, `replicate-schemas-chunk-${chunkIndex}.json`),
|
|
835
|
+
JSON.stringify(currentChunk, null, 2)
|
|
836
|
+
);
|
|
837
|
+
console.log(`✓ Saved schema chunk ${chunkIndex} with ${Object.keys(currentChunk).length} models`);
|
|
838
|
+
chunkIndex++;
|
|
839
|
+
currentChunk = {};
|
|
840
|
+
currentSize = 0;
|
|
841
|
+
}
|
|
842
|
+
currentChunk[modelId] = modelData;
|
|
843
|
+
currentSize += entryString.length;
|
|
844
|
+
}
|
|
845
|
+
// Save any remaining chunk
|
|
846
|
+
if (Object.keys(currentChunk).length > 0) {
|
|
847
|
+
await fs.writeFile(
|
|
848
|
+
path.join(cacheDir, `replicate-schemas-chunk-${chunkIndex}.json`),
|
|
849
|
+
JSON.stringify(currentChunk, null, 2)
|
|
850
|
+
);
|
|
851
|
+
console.log(`✓ Saved schema chunk ${chunkIndex} with ${Object.keys(currentChunk).length} models`);
|
|
852
|
+
}
|
|
853
|
+
} else {
|
|
854
|
+
// Load schemas cache from file
|
|
855
|
+
const schemasData = await fs.readFile(
|
|
856
|
+
path.join(cacheDir, 'replicate-schemas.json'),
|
|
857
|
+
'utf-8'
|
|
858
|
+
);
|
|
859
|
+
schemasCache = JSON.parse(schemasData) as Record<string, ReplicateModelData>;
|
|
860
|
+
|
|
861
|
+
console.log(`\n✓ Loaded ${Object.keys(schemasCache).length} model schemas from cache\n`);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
for (const modelData of Object.values(schemasCache)) {
|
|
865
|
+
cleanSchema(modelData);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Calculate number of unique schemas
|
|
869
|
+
const uniqueSchemas = new Set<string>();
|
|
870
|
+
for (const modelData of Object.values(schemasCache)) {
|
|
871
|
+
if (modelData.latest_version) {
|
|
872
|
+
uniqueSchemas.add(JSON.stringify(modelData.latest_version.openapi_schema.components.schemas));
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
console.log(`\n✓ Found ${uniqueSchemas.size} unique model schemas across ${Object.keys(schemasCache).length} models\n`);
|
|
877
|
+
|
|
878
|
+
// Generate Model Transformers
|
|
879
|
+
if (options.transformers) {
|
|
880
|
+
console.log('=== Generating Model Transformers ===\n');
|
|
881
|
+
|
|
882
|
+
// Create replicate transformers directory
|
|
883
|
+
await fs.mkdir(
|
|
884
|
+
path.join(cacheDir, 'replicate'),
|
|
885
|
+
{ recursive: true }
|
|
886
|
+
);
|
|
887
|
+
|
|
888
|
+
let transformingModels = models;
|
|
889
|
+
let overwrite = false;
|
|
890
|
+
|
|
891
|
+
// Filter to only models with schemas if transformers are desired
|
|
892
|
+
if (options.models && options.models.length > 0) {
|
|
893
|
+
const modelSet = new Set(options.models);
|
|
894
|
+
transformingModels = transformingModels.filter((model) => {
|
|
895
|
+
const modelId = `${model.owner}/${model.name}`;
|
|
896
|
+
return modelSet.has(modelId);
|
|
897
|
+
});
|
|
898
|
+
overwrite = true;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// If models were not specified, filter out already transformed models
|
|
902
|
+
if (!overwrite) {
|
|
903
|
+
const alreadyTransformed = await fs.readdir(
|
|
904
|
+
path.resolve(cacheDir, '../src/transformers/replicate'),
|
|
905
|
+
);
|
|
906
|
+
const alreadyTransformedSet = new Set(
|
|
907
|
+
alreadyTransformed
|
|
908
|
+
.filter((filename) => filename.endsWith('.ts') && filename !== 'index.ts')
|
|
909
|
+
.map((filename) => filename.replace('.ts', ''))
|
|
910
|
+
);
|
|
911
|
+
transformingModels = transformingModels.filter((model) => {
|
|
912
|
+
const modelId = `${model.owner}/${model.name}`;
|
|
913
|
+
const transformedFile = modelId.replace(/[^\w]/g, '-');
|
|
914
|
+
|
|
915
|
+
return !alreadyTransformedSet.has(transformedFile);
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// Only first N models if specified
|
|
920
|
+
if (options.n && options.n > 0) {
|
|
921
|
+
transformingModels = transformingModels.slice(0, options.n);
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// Call extractor for each model
|
|
925
|
+
console.log(`Generating transformers for ${transformingModels.length} models...\n`);
|
|
926
|
+
|
|
927
|
+
// Use specified concurrency for transformations
|
|
928
|
+
const concurrency = options.transformConcurrency !== undefined && options.transformConcurrency <= 0
|
|
929
|
+
? transformingModels.length
|
|
930
|
+
: options.transformConcurrency ?? 1;
|
|
931
|
+
|
|
932
|
+
let nextModelIndex = 0;
|
|
933
|
+
|
|
934
|
+
const workers: Promise<void>[] = [];
|
|
935
|
+
for (let i = 0; i < concurrency; i++) {
|
|
936
|
+
const worker = (async () => {
|
|
937
|
+
while (nextModelIndex < transformingModels.length) {
|
|
938
|
+
const model = transformingModels[nextModelIndex];
|
|
939
|
+
nextModelIndex++;
|
|
940
|
+
const modelId = `${model.owner}/${model.name}`;
|
|
941
|
+
const transformedFile = modelId.replace(/[^\w]/g, '-') + '.ts';
|
|
942
|
+
const modelData = schemasCache[modelId] || model;
|
|
943
|
+
|
|
944
|
+
console.log(`\n--- Generating transformer for model: ${modelId}, ---`);
|
|
945
|
+
|
|
946
|
+
try {
|
|
947
|
+
const modelTypes = await extractTypes(modelData);
|
|
948
|
+
|
|
949
|
+
const result = await extract.get('result', {
|
|
950
|
+
modelData,
|
|
951
|
+
modelTypes,
|
|
952
|
+
model: options.transformerModel
|
|
953
|
+
});
|
|
954
|
+
if (!result) {
|
|
955
|
+
console.log(` ✗ Failed to generate transformer for model: ${modelId}`);
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
const converted = convertReplicateModel(modelData);
|
|
960
|
+
|
|
961
|
+
const translatedModelInfo: ModelInfo<'replicate'> = {
|
|
962
|
+
id: converted.id,
|
|
963
|
+
provider: 'replicate',
|
|
964
|
+
name: converted.name,
|
|
965
|
+
contextWindow: result.modelInfo.contextWindow,
|
|
966
|
+
maxOutputTokens: result.modelInfo.maxOutputTokens,
|
|
967
|
+
pricing: result.modelInfo.pricing,
|
|
968
|
+
tier: result.modelInfo.tier,
|
|
969
|
+
capabilities: new Set(result.modelInfo.capabilities),
|
|
970
|
+
metrics: result.modelInfo.metrics,
|
|
971
|
+
tokenizer: result.modelInfo.tokenizer,
|
|
972
|
+
supportedParameters: new Set(result.modelInfo.supportedParameters),
|
|
973
|
+
metadata: converted.metadata,
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
const replaceIndex = modelInfos.findIndex((m) => m.id === translatedModelInfo.id);
|
|
977
|
+
if (replaceIndex >= 0) {
|
|
978
|
+
modelInfos[replaceIndex] = translatedModelInfo;
|
|
979
|
+
} else {
|
|
980
|
+
console.log(` ⚠ ModelInfo for ${modelId} not found in main list, adding new entry`);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
let fixedTransformerImplementation = result.transformerImplementation;
|
|
984
|
+
if (fixedTransformerImplementation.startsWith('"')) {
|
|
985
|
+
fixedTransformerImplementation = `{\n ${fixedTransformerImplementation}\n}`;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
const coreImports = [
|
|
989
|
+
fixedTransformerImplementation.includes('toURL') ? 'toURL' : null,
|
|
990
|
+
fixedTransformerImplementation.includes('toBase64') ? 'toBase64' : null,
|
|
991
|
+
fixedTransformerImplementation.includes('toText') ? 'toText' : null,
|
|
992
|
+
fixedTransformerImplementation.includes('toStream') ? 'toStream' : null,
|
|
993
|
+
fixedTransformerImplementation.includes('toReadableStream') ? 'toReadableStream' : null,
|
|
994
|
+
fixedTransformerImplementation.includes('toFile') ? 'toFile' : null,
|
|
995
|
+
].filter((i) => i !== null) as string[];
|
|
996
|
+
|
|
997
|
+
const validatedFile = path.resolve(cacheDir, '../src/transformers/replicate', transformedFile);
|
|
998
|
+
await fs.writeFile(
|
|
999
|
+
validatedFile,
|
|
1000
|
+
`
|
|
1001
|
+
${coreImports.length > 0 ? `import { ${coreImports.join(', ')} } from '@aeye/core';` : ''}
|
|
1002
|
+
import { ReplicateTransformer } from '@aeye/replicate';
|
|
1003
|
+
|
|
1004
|
+
${modelTypes}
|
|
1005
|
+
|
|
1006
|
+
export default ${fixedTransformerImplementation}
|
|
1007
|
+
`.trim()
|
|
1008
|
+
);
|
|
1009
|
+
|
|
1010
|
+
if (await isValidTypeScript(validatedFile)) {
|
|
1011
|
+
console.log(` ✓ Validated transformer implementation for ${modelId}`);
|
|
1012
|
+
} else {
|
|
1013
|
+
console.log(` ✗ Generated transformer for model ${modelId} is not valid TypeScript, skipping save.`);
|
|
1014
|
+
await fs.rename(validatedFile, validatedFile + '.invalid');
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
} catch (e: any) {
|
|
1018
|
+
console.log(` ✗ Error generating transformer for model ${modelId}:`, e instanceof Error ? e.message : e);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
})();
|
|
1022
|
+
workers.push(worker);
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
await Promise.all(workers);
|
|
1026
|
+
|
|
1027
|
+
console.log(`\n✓ Generated transformers for ${transformingModels.length} models in ${path.join(cacheDir, 'replicate')}\n`);
|
|
1028
|
+
|
|
1029
|
+
// Generate index file
|
|
1030
|
+
const transformerTarget = path.join(__dirname, '../../src/transformers/replicate');
|
|
1031
|
+
const transformerFiles = await fs.readdir(transformerTarget);
|
|
1032
|
+
const transformerSet = new Set(
|
|
1033
|
+
transformerFiles
|
|
1034
|
+
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
|
|
1035
|
+
.map((f) => f.replace('.ts', ''))
|
|
1036
|
+
);
|
|
1037
|
+
|
|
1038
|
+
// // For each file
|
|
1039
|
+
// import name from './name.ts';
|
|
1040
|
+
|
|
1041
|
+
// // Final export
|
|
1042
|
+
// export const replicateTransformers: Record<string, ReplicateTransformer> = {
|
|
1043
|
+
// ...name,
|
|
1044
|
+
// };
|
|
1045
|
+
|
|
1046
|
+
await fs.writeFile(
|
|
1047
|
+
path.join(transformerTarget, 'index.ts'),
|
|
1048
|
+
`
|
|
1049
|
+
import { ReplicateTransformer } from '@aeye/replicate';
|
|
1050
|
+
|
|
1051
|
+
${Array.from(transformerSet).map((name) => `import ${name.replace(/-/g, '_')} from './${name}';`).join('\n')}
|
|
1052
|
+
|
|
1053
|
+
export const replicateTransformers: Record<string, ReplicateTransformer> = {
|
|
1054
|
+
${Array.from(transformerSet).map((name) => `...${name.replace(/-/g, '_')},`).join('\n ')}
|
|
1055
|
+
};`.trim()
|
|
1056
|
+
);
|
|
1057
|
+
|
|
1058
|
+
console.log(`✓ Generated Replicate transformers index file\n`);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// Save JSON for reference
|
|
1063
|
+
await fs.writeFile(
|
|
1064
|
+
path.join(outputDir, 'replicate-modelinfo.json'),
|
|
1065
|
+
JSON.stringify(modelInfos, jsonReplacer, 2)
|
|
1066
|
+
);
|
|
1067
|
+
console.log(`✓ Saved ${modelInfos.length} models to JSON`);
|
|
1068
|
+
|
|
1069
|
+
// Generate TypeScript file
|
|
1070
|
+
const srcDir = path.join(__dirname, '../../src/models');
|
|
1071
|
+
await writeModelTS(modelInfos, 'replicateModels', path.join(srcDir, 'replicate.ts'));
|
|
1072
|
+
console.log(`✓ Generated TypeScript file: src/models/replicate.ts`);
|
|
1073
|
+
|
|
1074
|
+
console.log('\n✓ Replicate scraping complete\n');
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function isValidTypeScript(file: string): Promise<boolean> {
|
|
1078
|
+
return new Promise((resolve, reject) => {
|
|
1079
|
+
const tsc = spawn('npx', ['tsc', '--noEmit', '--skipLibCheck', file], {
|
|
1080
|
+
shell: true,
|
|
1081
|
+
});
|
|
1082
|
+
|
|
1083
|
+
tsc.on('close', (code) => {
|
|
1084
|
+
if (code === 0) {
|
|
1085
|
+
resolve(true);
|
|
1086
|
+
} else {
|
|
1087
|
+
resolve(false);
|
|
1088
|
+
}
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
tsc.on('error', (error) => {
|
|
1092
|
+
reject(error);
|
|
1093
|
+
});
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// CLI execution
|
|
1098
|
+
if (process.argv[1].endsWith('replicate.ts')) {
|
|
1099
|
+
const cleanArg = (a: string) => (/^["'`](.*)["'`]$/.exec(a) || ['', a])[1];
|
|
1100
|
+
|
|
1101
|
+
const args = process.argv.slice(2).map(cleanArg);
|
|
1102
|
+
|
|
1103
|
+
const outputDir = args.find((arg) => !arg.startsWith('--')) || path.join(__dirname, '../../data');
|
|
1104
|
+
const cacheDir = args.find((arg, i) => i > 0 && !arg.startsWith('--') && !args[i - 1].startsWith('--')) || path.join(__dirname, '../../cache');
|
|
1105
|
+
|
|
1106
|
+
const concurrencyArg = args.find((arg) => arg.startsWith('--concurrency='));
|
|
1107
|
+
const concurrency = concurrencyArg
|
|
1108
|
+
? parseInt(concurrencyArg.split('=')[1], 10)
|
|
1109
|
+
: 50;
|
|
1110
|
+
|
|
1111
|
+
const transformers = args.includes('--transformers');
|
|
1112
|
+
|
|
1113
|
+
const transformersOnly = args.includes('--transformers-only');
|
|
1114
|
+
|
|
1115
|
+
const transformerModelArg = args.find((arg) => arg.startsWith('--transformer-model='));
|
|
1116
|
+
const transformerModel = transformerModelArg
|
|
1117
|
+
? cleanArg(transformerModelArg.split('=', 2)[1])
|
|
1118
|
+
: 'google/gemini-2.5-pro';
|
|
1119
|
+
|
|
1120
|
+
const modelsArg = args.find((arg) => arg.startsWith('--models='));
|
|
1121
|
+
let models: string[] | undefined = undefined;
|
|
1122
|
+
if (modelsArg) {
|
|
1123
|
+
models = modelsArg.substring(9).split(',').map((m) => m.trim());
|
|
1124
|
+
models = models.map(cleanArg)
|
|
1125
|
+
models = models.filter((m) => m.length > 0);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
const nArg = args.find((arg) => arg.startsWith('--n='));;
|
|
1129
|
+
const n = nArg ? parseInt(cleanArg(nArg.split('=')[1]), 10) : undefined;
|
|
1130
|
+
|
|
1131
|
+
const transformConcurrencyArg = args.find((arg) => arg.startsWith('--transform-concurrency='));
|
|
1132
|
+
const transformConcurrency = transformConcurrencyArg
|
|
1133
|
+
? parseInt(transformConcurrencyArg.split('=')[1], 10)
|
|
1134
|
+
: concurrency;
|
|
1135
|
+
|
|
1136
|
+
const params = { concurrency, transformers, transformersOnly, transformerModel, transformConcurrency, models, n };
|
|
1137
|
+
|
|
1138
|
+
console.debug('Scrape parameters:', { outputDir, cacheDir, ...params });
|
|
1139
|
+
|
|
1140
|
+
scrapeReplicate(outputDir, cacheDir, params).catch((error) => {
|
|
1141
|
+
console.error('✗ Replicate scraping failed:', error);
|
|
1142
|
+
process.exit(1);
|
|
1143
|
+
});
|
|
1144
|
+
}
|