Spaces:
Running
Running
machine
#62
by
bartdevelop3r
- opened
This view is limited to 50 files because it contains too many changes.
See the raw diff here.
- .gitattributes +35 -1
- .gitignore +101 -20
- .pre-commit-config.yaml +32 -0
- .python-version +1 -0
- .vscode/extensions.json +8 -0
- .vscode/settings.json +16 -0
- README.md +3 -133
- anycoder_app/__init__.py +0 -27
- anycoder_app/agent.py +0 -234
- anycoder_app/config.py +0 -175
- anycoder_app/deploy.py +0 -0
- anycoder_app/docs_manager.py +0 -1484
- anycoder_app/models.py +0 -338
- anycoder_app/parsers.py +0 -1111
- anycoder_app/prompts.py +0 -817
- anycoder_app/themes.py +0 -257
- anycoder_app/ui.py +0 -0
- app.py +51 -28
- app.py.backup +0 -0
- app_allenai.py +67 -0
- app_cerebras.py +19 -0
- app_claude.py +21 -0
- app_cohere.py +21 -0
- app_compare.py +210 -0
- app_crew.py +8 -0
- app_deepseek.py +23 -0
- app_experimental.py +300 -0
- app_fal.py +16 -0
- app_fireworks.py +19 -0
- app_gemini.py +22 -0
- app_gemini_camera.py +23 -0
- app_gemini_coder.py +23 -0
- app_gemini_voice.py +23 -0
- app_groq.py +21 -0
- app_groq_coder.py +23 -0
- app_hf.py +17 -0
- app_huggingface.py +22 -0
- app_hyperbolic.py +19 -0
- app_hyperbolic_coder.py +20 -0
- app_langchain.py +23 -0
- app_lumaai.py +7 -0
- app_marco_o1.py +12 -0
- app_meta.py +6 -0
- app_mindsearch.py +12 -0
- app_minimax.py +22 -0
- app_minimax_coder.py +23 -0
- app_mistral.py +23 -0
- app_moondream.py +13 -0
- app_nvidia.py +22 -0
- app_nvidia_coder.py +23 -0
.gitattributes
CHANGED
|
@@ -1 +1,35 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
# Byte-compiled / optimized / DLL files
|
| 2 |
__pycache__/
|
| 3 |
*.py[cod]
|
|
@@ -19,18 +21,16 @@ lib64/
|
|
| 19 |
parts/
|
| 20 |
sdist/
|
| 21 |
var/
|
|
|
|
|
|
|
| 22 |
*.egg-info/
|
| 23 |
.installed.cfg
|
| 24 |
*.egg
|
| 25 |
MANIFEST
|
| 26 |
|
| 27 |
-
# Virtual environments
|
| 28 |
-
venv/
|
| 29 |
-
env/
|
| 30 |
-
ENV/
|
| 31 |
-
.venv/
|
| 32 |
-
|
| 33 |
# PyInstaller
|
|
|
|
|
|
|
| 34 |
*.manifest
|
| 35 |
*.spec
|
| 36 |
|
|
@@ -48,34 +48,115 @@ htmlcov/
|
|
| 48 |
nosetests.xml
|
| 49 |
coverage.xml
|
| 50 |
*.cover
|
|
|
|
| 51 |
.hypothesis/
|
| 52 |
.pytest_cache/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
# Jupyter Notebook
|
| 55 |
.ipynb_checkpoints
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# pyenv
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# mypy
|
| 61 |
.mypy_cache/
|
| 62 |
.dmypy.json
|
|
|
|
| 63 |
|
| 64 |
# Pyre type checker
|
| 65 |
.pyre/
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
logs/
|
| 70 |
-
|
| 71 |
-
# System files
|
| 72 |
-
.DS_Store
|
| 73 |
-
Thumbs.db
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
|
| 77 |
-
poetry.lock
|
| 78 |
-
Pipfile.lock
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.gradio/
|
| 2 |
+
|
| 3 |
# Byte-compiled / optimized / DLL files
|
| 4 |
__pycache__/
|
| 5 |
*.py[cod]
|
|
|
|
| 21 |
parts/
|
| 22 |
sdist/
|
| 23 |
var/
|
| 24 |
+
wheels/
|
| 25 |
+
share/python-wheels/
|
| 26 |
*.egg-info/
|
| 27 |
.installed.cfg
|
| 28 |
*.egg
|
| 29 |
MANIFEST
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# PyInstaller
|
| 32 |
+
# Usually these files are written by a python script from a template
|
| 33 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 34 |
*.manifest
|
| 35 |
*.spec
|
| 36 |
|
|
|
|
| 48 |
nosetests.xml
|
| 49 |
coverage.xml
|
| 50 |
*.cover
|
| 51 |
+
*.py,cover
|
| 52 |
.hypothesis/
|
| 53 |
.pytest_cache/
|
| 54 |
+
cover/
|
| 55 |
+
|
| 56 |
+
# Translations
|
| 57 |
+
*.mo
|
| 58 |
+
*.pot
|
| 59 |
+
|
| 60 |
+
# Django stuff:
|
| 61 |
+
*.log
|
| 62 |
+
local_settings.py
|
| 63 |
+
db.sqlite3
|
| 64 |
+
db.sqlite3-journal
|
| 65 |
+
|
| 66 |
+
# Flask stuff:
|
| 67 |
+
instance/
|
| 68 |
+
.webassets-cache
|
| 69 |
+
|
| 70 |
+
# Scrapy stuff:
|
| 71 |
+
.scrapy
|
| 72 |
+
|
| 73 |
+
# Sphinx documentation
|
| 74 |
+
docs/_build/
|
| 75 |
+
|
| 76 |
+
# PyBuilder
|
| 77 |
+
.pybuilder/
|
| 78 |
+
target/
|
| 79 |
|
| 80 |
# Jupyter Notebook
|
| 81 |
.ipynb_checkpoints
|
| 82 |
|
| 83 |
+
# IPython
|
| 84 |
+
profile_default/
|
| 85 |
+
ipython_config.py
|
| 86 |
+
|
| 87 |
# pyenv
|
| 88 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 89 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 90 |
+
# .python-version
|
| 91 |
+
|
| 92 |
+
# pipenv
|
| 93 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 94 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 95 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 96 |
+
# install all needed dependencies.
|
| 97 |
+
#Pipfile.lock
|
| 98 |
+
|
| 99 |
+
# poetry
|
| 100 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 101 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 102 |
+
# commonly ignored for libraries.
|
| 103 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 104 |
+
#poetry.lock
|
| 105 |
+
|
| 106 |
+
# pdm
|
| 107 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 108 |
+
#pdm.lock
|
| 109 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
| 110 |
+
# in version control.
|
| 111 |
+
# https://pdm.fming.dev/#use-with-ide
|
| 112 |
+
.pdm.toml
|
| 113 |
+
|
| 114 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 115 |
+
__pypackages__/
|
| 116 |
+
|
| 117 |
+
# Celery stuff
|
| 118 |
+
celerybeat-schedule
|
| 119 |
+
celerybeat.pid
|
| 120 |
+
|
| 121 |
+
# SageMath parsed files
|
| 122 |
+
*.sage.py
|
| 123 |
+
|
| 124 |
+
# Environments
|
| 125 |
+
.env
|
| 126 |
+
.venv
|
| 127 |
+
env/
|
| 128 |
+
venv/
|
| 129 |
+
ENV/
|
| 130 |
+
env.bak/
|
| 131 |
+
venv.bak/
|
| 132 |
+
|
| 133 |
+
# Spyder project settings
|
| 134 |
+
.spyderproject
|
| 135 |
+
.spyproject
|
| 136 |
+
|
| 137 |
+
# Rope project settings
|
| 138 |
+
.ropeproject
|
| 139 |
+
|
| 140 |
+
# mkdocs documentation
|
| 141 |
+
/site
|
| 142 |
|
| 143 |
# mypy
|
| 144 |
.mypy_cache/
|
| 145 |
.dmypy.json
|
| 146 |
+
dmypy.json
|
| 147 |
|
| 148 |
# Pyre type checker
|
| 149 |
.pyre/
|
| 150 |
|
| 151 |
+
# pytype static type analyzer
|
| 152 |
+
.pytype/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
# Cython debug symbols
|
| 155 |
+
cython_debug/
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
# PyCharm
|
| 158 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 159 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 160 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 161 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 162 |
+
#.idea/
|
.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
repos:
|
| 2 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 3 |
+
rev: v5.0.0
|
| 4 |
+
hooks:
|
| 5 |
+
- id: check-executables-have-shebangs
|
| 6 |
+
- id: check-json
|
| 7 |
+
- id: check-merge-conflict
|
| 8 |
+
- id: check-shebang-scripts-are-executable
|
| 9 |
+
- id: check-toml
|
| 10 |
+
- id: check-yaml
|
| 11 |
+
- id: end-of-file-fixer
|
| 12 |
+
- id: mixed-line-ending
|
| 13 |
+
args: ["--fix=lf"]
|
| 14 |
+
- id: requirements-txt-fixer
|
| 15 |
+
- id: trailing-whitespace
|
| 16 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 17 |
+
rev: v0.8.6
|
| 18 |
+
hooks:
|
| 19 |
+
- id: ruff
|
| 20 |
+
args: ["--fix"]
|
| 21 |
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
| 22 |
+
rev: v1.14.1
|
| 23 |
+
hooks:
|
| 24 |
+
- id: mypy
|
| 25 |
+
args: ["--ignore-missing-imports"]
|
| 26 |
+
additional_dependencies:
|
| 27 |
+
[
|
| 28 |
+
"types-python-slugify",
|
| 29 |
+
"types-requests",
|
| 30 |
+
"types-PyYAML",
|
| 31 |
+
"types-pytz",
|
| 32 |
+
]
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.10
|
.vscode/extensions.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"recommendations": [
|
| 3 |
+
"ms-python.python",
|
| 4 |
+
"charliermarsh.ruff",
|
| 5 |
+
"streetsidesoftware.code-spell-checker",
|
| 6 |
+
"tamasfe.even-better-toml"
|
| 7 |
+
]
|
| 8 |
+
}
|
.vscode/settings.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"editor.formatOnSave": true,
|
| 3 |
+
"files.insertFinalNewline": false,
|
| 4 |
+
"[python]": {
|
| 5 |
+
"editor.defaultFormatter": "charliermarsh.ruff",
|
| 6 |
+
"editor.formatOnType": true,
|
| 7 |
+
"editor.codeActionsOnSave": {
|
| 8 |
+
"source.fixAll.ruff": "explicit"
|
| 9 |
+
}
|
| 10 |
+
},
|
| 11 |
+
"[jupyter]": {
|
| 12 |
+
"files.insertFinalNewline": false
|
| 13 |
+
},
|
| 14 |
+
"notebook.output.scrolling": true,
|
| 15 |
+
"notebook.formatOnSave.enabled": true
|
| 16 |
+
}
|
README.md
CHANGED
|
@@ -1,143 +1,13 @@
|
|
| 1 |
---
|
| 2 |
title: Anycoder
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
disable_embedding: true
|
| 11 |
-
hf_oauth: true
|
| 12 |
-
hf_oauth_scopes:
|
| 13 |
-
- manage-repos
|
| 14 |
---
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
AnyCoder is an AI-powered code generator that helps you create applications by describing them in plain English. It supports multiple AI models, multimodal input, website redesign, and one-click deployment to Hugging Face Spaces. The UI is built with Gradio theming for a minimal, modern experience.
|
| 19 |
-
|
| 20 |
-
## Features
|
| 21 |
-
|
| 22 |
-
- **Multi-Model Support**: Choose from Moonshot Kimi-K2, Kimi K2 Turbo (Preview), Kimi K2 Thinking, DeepSeek V3, DeepSeek R1, ERNIE-4.5-VL, MiniMax M2, Qwen3-235B-A22B, Qwen3-30B-A3B-Instruct-2507, Qwen3-30B-A3B-Thinking-2507, SmolLM3-3B, GLM-4.1V-9B-Thinking, Gemini 2.5 Flash and Gemini 2.5 Pro (OpenAI-compatible)
|
| 23 |
-
- Claude-Opus-4.1 (via Poe)
|
| 24 |
-
- **Flexible Input**: Describe your app in text, upload a UI design image (for multimodal models), provide a reference file (PDF, TXT, MD, CSV, DOCX, or image), or enter a website URL for redesign
|
| 25 |
-
- **Web Search Integration**: Enable real-time web search (Tavily, with advanced search depth) to enhance code generation with up-to-date information and best practices
|
| 26 |
-
- **Code Generation**: Generate code in HTML, Python, JS, and more. Special support for transformers.js apps (outputs index.html, index.js, style.css)
|
| 27 |
-
- **Live Preview**: Instantly preview generated HTML in a sandboxed iframe
|
| 28 |
-
- **Modify Existing Code**: Use search/replace block format to update generated HTML
|
| 29 |
-
- **One-Click Deployment**: Deploy your app to Hugging Face Spaces (Gradio, Streamlit, Static HTML, or Transformers.js) with OAuth login
|
| 30 |
-
- **History & Examples**: Chat-like history of all interactions and quick example prompts for fast prototyping
|
| 31 |
-
- **Minimal, Modern UI**: Built with Gradio 5.x, using only built-in theming and styling (no custom CSS)
|
| 32 |
-
|
| 33 |
-
## Installation
|
| 34 |
-
|
| 35 |
-
1. Clone the repository:
|
| 36 |
-
```bash
|
| 37 |
-
git clone <repository-url>
|
| 38 |
-
cd anycoder
|
| 39 |
-
```
|
| 40 |
-
2. Install dependencies:
|
| 41 |
-
```bash
|
| 42 |
-
pip install -r requirements.txt
|
| 43 |
-
```
|
| 44 |
-
3. Set up environment variables:
|
| 45 |
-
```bash
|
| 46 |
-
export HF_TOKEN="your_huggingface_token"
|
| 47 |
-
export DASHSCOPE_API_KEY="your_dashscope_api_key" # Required for Qwen3-30B models via DashScope
|
| 48 |
-
export POE_API_KEY="your_poe_api_key" # Required for GPT-5, Grok-4, and Grok-Code-Fast-1 via Poe
|
| 49 |
-
export GEMINI_API_KEY="your_gemini_api_key" # Required for Gemini models
|
| 50 |
-
export MOONSHOT_API_KEY="your_moonshot_api_key" # Required for Kimi models
|
| 51 |
-
export MINIMAX_API_KEY="your_minimax_api_key" # Required for MiniMax M2 model
|
| 52 |
-
```
|
| 53 |
-
|
| 54 |
-
## Usage
|
| 55 |
-
|
| 56 |
-
1. Run the application:
|
| 57 |
-
```bash
|
| 58 |
-
python app.py
|
| 59 |
-
```
|
| 60 |
-
2. Open your browser and navigate to the provided URL
|
| 61 |
-
3. Describe your application in the text input field, or:
|
| 62 |
-
- Upload a UI design image (for multimodal models)
|
| 63 |
-
- Upload a reference file (PDF, TXT, MD, CSV, DOCX, or image)
|
| 64 |
-
- Enter a website URL for redesign (the app will extract and analyze the HTML and content)
|
| 65 |
-
- Enable web search for up-to-date information
|
| 66 |
-
- Choose a different AI model or code language
|
| 67 |
-
4. Click "Generate" to create your code
|
| 68 |
-
5. View the generated code in the Code tab or see it in action in the Preview tab
|
| 69 |
-
6. Use the History tab to review previous generations
|
| 70 |
-
7. **Deploy to Space**: Enter a title and click "🚀 Deploy App" to publish your application (OAuth login required) - the SDK is automatically matched to your selected code language
|
| 71 |
-
|
| 72 |
-
## Supported Models
|
| 73 |
-
|
| 74 |
-
- Moonshot Kimi-K2
|
| 75 |
-
- Kimi K2 Turbo (Preview)
|
| 76 |
-
- Kimi K2 Thinking
|
| 77 |
-
- DeepSeek V3
|
| 78 |
-
- DeepSeek V3.1
|
| 79 |
-
- DeepSeek V3.1 Terminus
|
| 80 |
-
- DeepSeek V3.2-Exp
|
| 81 |
-
- DeepSeek R1
|
| 82 |
-
- MiniMax M2
|
| 83 |
-
- Qwen3-235B-A22B
|
| 84 |
-
- Qwen3-4B-Instruct-2507
|
| 85 |
-
- Qwen3-4B-Thinking-2507
|
| 86 |
-
- Qwen3-30B-A3B-Instruct-2507 (via DashScope)
|
| 87 |
-
- Qwen3-30B-A3B-Thinking-2507 (via DashScope)
|
| 88 |
-
- GPT-5 (via Poe)
|
| 89 |
-
- Grok-4 (via Poe)
|
| 90 |
-
- Claude-Opus-4.1 (via Poe)
|
| 91 |
-
- Gemini 2.5 Flash (OpenAI-compatible)
|
| 92 |
-
- Gemini 2.5 Pro (OpenAI-compatible)
|
| 93 |
-
|
| 94 |
-
## Input Options
|
| 95 |
-
|
| 96 |
-
- **Text Prompt**: Describe your app or code requirements
|
| 97 |
-
- **Image Upload**: For multimodal models, upload a UI design image to generate code from visuals
|
| 98 |
-
- **File Upload**: Provide a reference file (PDF, TXT, MD, CSV, DOCX, or image) for code generation or text extraction (OCR for images)
|
| 99 |
-
- **Website URL**: Enter a URL to extract and redesign the website (HTML and content are analyzed and modernized)
|
| 100 |
-
|
| 101 |
-
## Code Generation & Modification
|
| 102 |
-
|
| 103 |
-
- Generates code in HTML, Python, JS, and more (selectable via dropdown)
|
| 104 |
-
- Special support for transformers.js apps (outputs index.html, index.js, style.css)
|
| 105 |
-
- Svelte apps
|
| 106 |
-
- For HTML, provides a live preview in a sandboxed iframe
|
| 107 |
-
- For modification requests, uses a search/replace block format to update existing HTML
|
| 108 |
-
|
| 109 |
-
## Deployment
|
| 110 |
-
|
| 111 |
-
- Deploy generated apps to Hugging Face Spaces directly from the UI
|
| 112 |
-
- Supported SDKs: Gradio (Python), Streamlit (Python), Static (HTML), Transformers.js
|
| 113 |
-
- OAuth login with Hugging Face is required for deployment to user-owned Spaces
|
| 114 |
-
|
| 115 |
-
## History & Examples
|
| 116 |
-
|
| 117 |
-
- Maintains a chat-like history of user/assistant interactions
|
| 118 |
-
- Quick example prompts are available in the sidebar for fast prototyping
|
| 119 |
-
|
| 120 |
-
## UI/UX
|
| 121 |
-
|
| 122 |
-
- Built with Gradio 5.x, using only Gradio's built-in theming and styling (no custom CSS)
|
| 123 |
-
- Minimal, uncluttered sidebar and interface
|
| 124 |
-
|
| 125 |
-
## Environment Variables
|
| 126 |
-
|
| 127 |
-
- `HF_TOKEN`: Your Hugging Face API token (required)
|
| 128 |
-
- `GEMINI_API_KEY`: Your Google Gemini API key (required to use Gemini models)
|
| 129 |
-
- `MOONSHOT_API_KEY`: Your Moonshot AI API key (required to use Kimi models)
|
| 130 |
-
- `MINIMAX_API_KEY`: Your MiniMax API key (required to use MiniMax M2 model)
|
| 131 |
-
|
| 132 |
-
## Project Structure
|
| 133 |
-
|
| 134 |
-
```
|
| 135 |
-
anycoder/
|
| 136 |
-
├── app.py # Main application (all logic and UI)
|
| 137 |
-
├── requirements.txt
|
| 138 |
-
├── README.md # This file
|
| 139 |
-
```
|
| 140 |
-
|
| 141 |
-
## License
|
| 142 |
-
|
| 143 |
-
[Add your license information here]
|
|
|
|
| 1 |
---
|
| 2 |
title: Anycoder
|
| 3 |
+
emoji: 🏢
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.23.3
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
disable_embedding: true
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/__init__.py
DELETED
|
@@ -1,27 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
AnyCoder - AI Code Generator Package
|
| 3 |
-
Modular structure for better code organization and maintainability.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
__version__ = "1.0.0"
|
| 7 |
-
|
| 8 |
-
from . import config
|
| 9 |
-
from . import prompts
|
| 10 |
-
from . import docs_manager
|
| 11 |
-
from . import models
|
| 12 |
-
from . import parsers
|
| 13 |
-
from . import deploy
|
| 14 |
-
from . import themes
|
| 15 |
-
from . import ui
|
| 16 |
-
|
| 17 |
-
__all__ = [
|
| 18 |
-
"config",
|
| 19 |
-
"prompts",
|
| 20 |
-
"docs_manager",
|
| 21 |
-
"models",
|
| 22 |
-
"parsers",
|
| 23 |
-
"deploy",
|
| 24 |
-
"themes",
|
| 25 |
-
"ui",
|
| 26 |
-
]
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/agent.py
DELETED
|
@@ -1,234 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Agent functionality for interactive code generation with follow-up questions and task planning.
|
| 3 |
-
"""
|
| 4 |
-
import os
|
| 5 |
-
from typing import Dict, List, Optional, Tuple, Generator
|
| 6 |
-
import gradio as gr
|
| 7 |
-
|
| 8 |
-
from .models import (
|
| 9 |
-
get_inference_client, get_real_model_id, history_to_messages,
|
| 10 |
-
history_to_chatbot_messages, strip_thinking_tags
|
| 11 |
-
)
|
| 12 |
-
from .deploy import generation_code
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def agent_generate_with_questions(
|
| 16 |
-
query: Optional[str],
|
| 17 |
-
setting: Dict[str, str],
|
| 18 |
-
history: List,
|
| 19 |
-
current_model: Dict,
|
| 20 |
-
language: str,
|
| 21 |
-
provider: str,
|
| 22 |
-
profile: Optional[gr.OAuthProfile] = None,
|
| 23 |
-
token: Optional[gr.OAuthToken] = None,
|
| 24 |
-
max_questions: int = 3
|
| 25 |
-
) -> Generator[Tuple[List, List], None, None]:
|
| 26 |
-
"""
|
| 27 |
-
Agent that asks follow-up questions, creates a task list, and generates code.
|
| 28 |
-
|
| 29 |
-
Args:
|
| 30 |
-
query: Initial user request
|
| 31 |
-
setting: System settings
|
| 32 |
-
history: Conversation history
|
| 33 |
-
current_model: Selected model configuration
|
| 34 |
-
language: Target programming language/framework
|
| 35 |
-
provider: Model provider
|
| 36 |
-
profile: User OAuth profile
|
| 37 |
-
token: User OAuth token
|
| 38 |
-
max_questions: Maximum number of follow-up questions to ask
|
| 39 |
-
|
| 40 |
-
Yields:
|
| 41 |
-
Tuples of (history, chatbot_messages) at each step
|
| 42 |
-
"""
|
| 43 |
-
if not query or not query.strip():
|
| 44 |
-
return
|
| 45 |
-
|
| 46 |
-
# Initialize history with user's initial query
|
| 47 |
-
current_history = history + [[query, ""]]
|
| 48 |
-
|
| 49 |
-
# Step 1: Agent analyzes the request and asks follow-up questions
|
| 50 |
-
agent_system_prompt = """You are a helpful coding assistant that helps users clarify their requirements before generating code.
|
| 51 |
-
|
| 52 |
-
Your task is to:
|
| 53 |
-
1. Analyze the user's request
|
| 54 |
-
2. Ask 1-3 clarifying questions to better understand their needs
|
| 55 |
-
3. Focus on important details like:
|
| 56 |
-
- Target audience and use case
|
| 57 |
-
- Specific features or functionality needed
|
| 58 |
-
- Design preferences (colors, layout, style)
|
| 59 |
-
- Data sources or APIs to integrate
|
| 60 |
-
- Performance or scalability requirements
|
| 61 |
-
|
| 62 |
-
Output ONLY the questions, numbered 1, 2, 3, etc. Keep questions concise and focused.
|
| 63 |
-
Do not generate code yet - just ask the questions."""
|
| 64 |
-
|
| 65 |
-
# Get LLM client
|
| 66 |
-
client = get_inference_client(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'), provider)
|
| 67 |
-
model_id = get_real_model_id(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'))
|
| 68 |
-
|
| 69 |
-
# Prepare messages for follow-up questions
|
| 70 |
-
messages = [
|
| 71 |
-
{'role': 'system', 'content': agent_system_prompt},
|
| 72 |
-
{'role': 'user', 'content': f"User wants to create: {query}\n\nLanguage/Framework: {language}\n\nAsk clarifying questions."}
|
| 73 |
-
]
|
| 74 |
-
|
| 75 |
-
# Generate follow-up questions
|
| 76 |
-
questions_response = ""
|
| 77 |
-
try:
|
| 78 |
-
# Try to use the client (works for both InferenceClient and OpenAI-compatible clients)
|
| 79 |
-
stream = client.chat.completions.create(
|
| 80 |
-
model=model_id,
|
| 81 |
-
messages=messages,
|
| 82 |
-
temperature=0.7,
|
| 83 |
-
max_tokens=500,
|
| 84 |
-
stream=True
|
| 85 |
-
)
|
| 86 |
-
for chunk in stream:
|
| 87 |
-
if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
|
| 88 |
-
questions_response += chunk.choices[0].delta.content
|
| 89 |
-
# Update display in real-time
|
| 90 |
-
temp_history = current_history[:-1] + [[query, f"🤔 **Analyzing your request...**\n\n{questions_response}"]]
|
| 91 |
-
yield (temp_history, history_to_chatbot_messages(temp_history))
|
| 92 |
-
except Exception as e:
|
| 93 |
-
error_msg = f"❌ Error asking follow-up questions: {str(e)}"
|
| 94 |
-
temp_history = current_history[:-1] + [[query, error_msg]]
|
| 95 |
-
yield (temp_history, history_to_chatbot_messages(temp_history))
|
| 96 |
-
return
|
| 97 |
-
|
| 98 |
-
# Update history with agent's questions
|
| 99 |
-
current_history[-1][1] = f"🤔 **Let me ask you a few questions to better understand your needs:**\n\n{questions_response}\n\n💬 Please answer these questions in your next message."
|
| 100 |
-
yield (current_history, history_to_chatbot_messages(current_history))
|
| 101 |
-
|
| 102 |
-
# Wait for user response (this will be handled by the UI)
|
| 103 |
-
# For now, we'll return and let the user respond, then continue in the next call
|
| 104 |
-
return
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def agent_process_answers_and_generate(
|
| 108 |
-
user_answers: str,
|
| 109 |
-
original_query: str,
|
| 110 |
-
questions: str,
|
| 111 |
-
setting: Dict[str, str],
|
| 112 |
-
history: List,
|
| 113 |
-
current_model: Dict,
|
| 114 |
-
language: str,
|
| 115 |
-
provider: str,
|
| 116 |
-
profile: Optional[gr.OAuthProfile] = None,
|
| 117 |
-
token: Optional[gr.OAuthToken] = None,
|
| 118 |
-
code_output=None,
|
| 119 |
-
history_output=None,
|
| 120 |
-
history_state=None
|
| 121 |
-
) -> Generator:
|
| 122 |
-
"""
|
| 123 |
-
Process user's answers, create task list, and generate code.
|
| 124 |
-
|
| 125 |
-
Args:
|
| 126 |
-
user_answers: User's responses to the questions
|
| 127 |
-
original_query: Original user request
|
| 128 |
-
questions: Agent's questions
|
| 129 |
-
setting: System settings
|
| 130 |
-
history: Conversation history
|
| 131 |
-
current_model: Selected model configuration
|
| 132 |
-
language: Target programming language/framework
|
| 133 |
-
provider: Model provider
|
| 134 |
-
profile: User OAuth profile
|
| 135 |
-
token: User OAuth token
|
| 136 |
-
code_output: Code output component
|
| 137 |
-
history_output: History output component
|
| 138 |
-
history_state: History state
|
| 139 |
-
|
| 140 |
-
Yields:
|
| 141 |
-
Updates to code output and history
|
| 142 |
-
"""
|
| 143 |
-
# Step 2: Create task list based on answers
|
| 144 |
-
task_planning_prompt = f"""Based on the user's request and their answers, create a detailed task list for implementing the solution.
|
| 145 |
-
|
| 146 |
-
Original Request: {original_query}
|
| 147 |
-
|
| 148 |
-
Questions Asked:
|
| 149 |
-
{questions}
|
| 150 |
-
|
| 151 |
-
User's Answers:
|
| 152 |
-
{user_answers}
|
| 153 |
-
|
| 154 |
-
Create a numbered task list with 5-8 specific, actionable tasks. Each task should be clear and focused.
|
| 155 |
-
Start with "📋 **Task List:**" and then list the tasks."""
|
| 156 |
-
|
| 157 |
-
client = get_inference_client(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'), provider)
|
| 158 |
-
model_id = get_real_model_id(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'))
|
| 159 |
-
|
| 160 |
-
messages = [
|
| 161 |
-
{'role': 'system', 'content': 'You are a helpful coding assistant creating a task plan.'},
|
| 162 |
-
{'role': 'user', 'content': task_planning_prompt}
|
| 163 |
-
]
|
| 164 |
-
|
| 165 |
-
# Generate task list
|
| 166 |
-
task_list = ""
|
| 167 |
-
try:
|
| 168 |
-
stream = client.chat.completions.create(
|
| 169 |
-
model=model_id,
|
| 170 |
-
messages=messages,
|
| 171 |
-
temperature=0.7,
|
| 172 |
-
max_tokens=800,
|
| 173 |
-
stream=True
|
| 174 |
-
)
|
| 175 |
-
for chunk in stream:
|
| 176 |
-
if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
|
| 177 |
-
task_list += chunk.choices[0].delta.content
|
| 178 |
-
# Update display
|
| 179 |
-
temp_history = history + [[user_answers, f"📋 **Creating task list...**\n\n{task_list}"]]
|
| 180 |
-
yield {
|
| 181 |
-
history_state: temp_history,
|
| 182 |
-
history_output: history_to_chatbot_messages(temp_history)
|
| 183 |
-
}
|
| 184 |
-
except Exception as e:
|
| 185 |
-
error_msg = f"❌ Error creating task list: {str(e)}"
|
| 186 |
-
temp_history = history + [[user_answers, error_msg]]
|
| 187 |
-
yield {
|
| 188 |
-
history_state: temp_history,
|
| 189 |
-
history_output: history_to_chatbot_messages(temp_history)
|
| 190 |
-
}
|
| 191 |
-
return
|
| 192 |
-
|
| 193 |
-
# Update history with task list
|
| 194 |
-
updated_history = history + [[user_answers, task_list]]
|
| 195 |
-
yield {
|
| 196 |
-
history_state: updated_history,
|
| 197 |
-
history_output: history_to_chatbot_messages(updated_history)
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
# Step 3: Generate code based on refined requirements
|
| 201 |
-
refined_query = f"""{original_query}
|
| 202 |
-
|
| 203 |
-
Additional Requirements (based on follow-up):
|
| 204 |
-
{user_answers}
|
| 205 |
-
|
| 206 |
-
Task List:
|
| 207 |
-
{task_list}
|
| 208 |
-
|
| 209 |
-
Please implement the above requirements following the task list."""
|
| 210 |
-
|
| 211 |
-
# Add a message indicating code generation is starting
|
| 212 |
-
code_gen_start_history = updated_history + [["[System]", "🚀 **Starting code generation based on your requirements...**"]]
|
| 213 |
-
yield {
|
| 214 |
-
history_state: code_gen_start_history,
|
| 215 |
-
history_output: history_to_chatbot_messages(code_gen_start_history)
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
# Use the existing generation_code function for actual code generation
|
| 219 |
-
# We need to pass the refined query and updated history
|
| 220 |
-
for result in generation_code(
|
| 221 |
-
refined_query,
|
| 222 |
-
setting,
|
| 223 |
-
updated_history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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/config.py
DELETED
|
@@ -1,175 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Configuration constants for AnyCoder application.
|
| 3 |
-
"""
|
| 4 |
-
import os
|
| 5 |
-
from datetime import datetime
|
| 6 |
-
from typing import Optional
|
| 7 |
-
|
| 8 |
-
# Gradio supported languages for syntax highlighting
|
| 9 |
-
GRADIO_SUPPORTED_LANGUAGES = [
|
| 10 |
-
"python", "json", "html", "javascript"
|
| 11 |
-
]
|
| 12 |
-
|
| 13 |
-
# Search/Replace Constants
|
| 14 |
-
SEARCH_START = "<<<<<<< SEARCH"
|
| 15 |
-
DIVIDER = "======="
|
| 16 |
-
REPLACE_END = ">>>>>>> REPLACE"
|
| 17 |
-
|
| 18 |
-
# Gradio Documentation Auto-Update System
|
| 19 |
-
GRADIO_LLMS_TXT_URL = "https://www.gradio.app/llms.txt"
|
| 20 |
-
GRADIO_DOCS_CACHE_FILE = ".gradio_docs_cache.txt"
|
| 21 |
-
GRADIO_DOCS_LAST_UPDATE_FILE = ".gradio_docs_last_update.txt"
|
| 22 |
-
GRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
|
| 23 |
-
|
| 24 |
-
# Global variable to store the current Gradio documentation
|
| 25 |
-
_gradio_docs_content: Optional[str] = None
|
| 26 |
-
_gradio_docs_last_fetched: Optional[datetime] = None
|
| 27 |
-
|
| 28 |
-
# ComfyUI Documentation Auto-Update System
|
| 29 |
-
COMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"
|
| 30 |
-
COMFYUI_DOCS_CACHE_FILE = ".comfyui_docs_cache.txt"
|
| 31 |
-
COMFYUI_DOCS_LAST_UPDATE_FILE = ".comfyui_docs_last_update.txt"
|
| 32 |
-
COMFYUI_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
|
| 33 |
-
|
| 34 |
-
# Global variable to store the current ComfyUI documentation
|
| 35 |
-
_comfyui_docs_content: Optional[str] = None
|
| 36 |
-
_comfyui_docs_last_fetched: Optional[datetime] = None
|
| 37 |
-
|
| 38 |
-
# FastRTC Documentation Auto-Update System
|
| 39 |
-
FASTRTC_LLMS_TXT_URL = "https://fastrtc.org/llms.txt"
|
| 40 |
-
FASTRTC_DOCS_CACHE_FILE = ".fastrtc_docs_cache.txt"
|
| 41 |
-
FASTRTC_DOCS_LAST_UPDATE_FILE = ".fastrtc_docs_last_update.txt"
|
| 42 |
-
FASTRTC_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
|
| 43 |
-
|
| 44 |
-
# Global variable to store the current FastRTC documentation
|
| 45 |
-
_fastrtc_docs_content: Optional[str] = None
|
| 46 |
-
_fastrtc_docs_last_fetched: Optional[datetime] = None
|
| 47 |
-
|
| 48 |
-
# Available Models Configuration
|
| 49 |
-
AVAILABLE_MODELS = [
|
| 50 |
-
{
|
| 51 |
-
"name": "DeepSeek V3.2-Exp",
|
| 52 |
-
"id": "deepseek-ai/DeepSeek-V3.2-Exp",
|
| 53 |
-
"description": "DeepSeek V3.2 Experimental model for cutting-edge code generation and reasoning"
|
| 54 |
-
},
|
| 55 |
-
{
|
| 56 |
-
"name": "DeepSeek R1",
|
| 57 |
-
"id": "deepseek-ai/DeepSeek-R1-0528",
|
| 58 |
-
"description": "DeepSeek R1 model for code generation"
|
| 59 |
-
},
|
| 60 |
-
{
|
| 61 |
-
"name": "GLM-4.6",
|
| 62 |
-
"id": "zai-org/GLM-4.6",
|
| 63 |
-
"description": "GLM-4.6 model for advanced code generation and general tasks"
|
| 64 |
-
},
|
| 65 |
-
{
|
| 66 |
-
"name": "Gemini Flash Latest",
|
| 67 |
-
"id": "gemini-flash-latest",
|
| 68 |
-
"description": "Google Gemini Flash Latest model via native Gemini API"
|
| 69 |
-
},
|
| 70 |
-
{
|
| 71 |
-
"name": "Gemini Flash Lite Latest",
|
| 72 |
-
"id": "gemini-flash-lite-latest",
|
| 73 |
-
"description": "Google Gemini Flash Lite Latest model via OpenAI-compatible API"
|
| 74 |
-
},
|
| 75 |
-
{
|
| 76 |
-
"name": "GPT-5",
|
| 77 |
-
"id": "gpt-5",
|
| 78 |
-
"description": "OpenAI GPT-5 model for advanced code generation and general tasks"
|
| 79 |
-
},
|
| 80 |
-
{
|
| 81 |
-
"name": "GPT-5.1",
|
| 82 |
-
"id": "gpt-5.1",
|
| 83 |
-
"description": "OpenAI GPT-5.1 model via Poe for advanced code generation and general tasks"
|
| 84 |
-
},
|
| 85 |
-
{
|
| 86 |
-
"name": "GPT-5.1 Instant",
|
| 87 |
-
"id": "gpt-5.1-instant",
|
| 88 |
-
"description": "OpenAI GPT-5.1 Instant model via Poe for fast responses"
|
| 89 |
-
},
|
| 90 |
-
{
|
| 91 |
-
"name": "GPT-5.1 Codex",
|
| 92 |
-
"id": "gpt-5.1-codex",
|
| 93 |
-
"description": "OpenAI GPT-5.1 Codex model via Poe optimized for code generation"
|
| 94 |
-
},
|
| 95 |
-
{
|
| 96 |
-
"name": "GPT-5.1 Codex Mini",
|
| 97 |
-
"id": "gpt-5.1-codex-mini",
|
| 98 |
-
"description": "OpenAI GPT-5.1 Codex Mini model via Poe for lightweight code generation"
|
| 99 |
-
},
|
| 100 |
-
{
|
| 101 |
-
"name": "Grok-4",
|
| 102 |
-
"id": "grok-4",
|
| 103 |
-
"description": "Grok-4 model via Poe (OpenAI-compatible) for advanced tasks"
|
| 104 |
-
},
|
| 105 |
-
{
|
| 106 |
-
"name": "Grok-Code-Fast-1",
|
| 107 |
-
"id": "Grok-Code-Fast-1",
|
| 108 |
-
"description": "Grok-Code-Fast-1 model via Poe (OpenAI-compatible) for fast code generation"
|
| 109 |
-
},
|
| 110 |
-
{
|
| 111 |
-
"name": "Claude-Opus-4.1",
|
| 112 |
-
"id": "claude-opus-4.1",
|
| 113 |
-
"description": "Anthropic Claude Opus 4.1 via Poe (OpenAI-compatible)"
|
| 114 |
-
},
|
| 115 |
-
{
|
| 116 |
-
"name": "Claude-Sonnet-4.5",
|
| 117 |
-
"id": "claude-sonnet-4.5",
|
| 118 |
-
"description": "Anthropic Claude Sonnet 4.5 via Poe (OpenAI-compatible)"
|
| 119 |
-
},
|
| 120 |
-
{
|
| 121 |
-
"name": "Claude-Haiku-4.5",
|
| 122 |
-
"id": "claude-haiku-4.5",
|
| 123 |
-
"description": "Anthropic Claude Haiku 4.5 via Poe (OpenAI-compatible)"
|
| 124 |
-
},
|
| 125 |
-
{
|
| 126 |
-
"name": "Qwen3 Max Preview",
|
| 127 |
-
"id": "qwen3-max-preview",
|
| 128 |
-
"description": "Qwen3 Max Preview model via DashScope International API"
|
| 129 |
-
},
|
| 130 |
-
{
|
| 131 |
-
"name": "MiniMax M2",
|
| 132 |
-
"id": "MiniMaxAI/MiniMax-M2",
|
| 133 |
-
"description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider"
|
| 134 |
-
},
|
| 135 |
-
{
|
| 136 |
-
"name": "Kimi K2 Thinking",
|
| 137 |
-
"id": "moonshotai/Kimi-K2-Thinking",
|
| 138 |
-
"description": "Moonshot Kimi K2 Thinking model for advanced reasoning and code generation"
|
| 139 |
-
}
|
| 140 |
-
]
|
| 141 |
-
|
| 142 |
-
k2_model_name_tag = "moonshotai/Kimi-K2-Thinking"
|
| 143 |
-
|
| 144 |
-
# Default model selection
|
| 145 |
-
DEFAULT_MODEL_NAME = "GPT-5.1 Codex"
|
| 146 |
-
DEFAULT_MODEL = None
|
| 147 |
-
for _m in AVAILABLE_MODELS:
|
| 148 |
-
if _m.get("name") == DEFAULT_MODEL_NAME:
|
| 149 |
-
DEFAULT_MODEL = _m
|
| 150 |
-
break
|
| 151 |
-
if DEFAULT_MODEL is None and AVAILABLE_MODELS:
|
| 152 |
-
DEFAULT_MODEL = AVAILABLE_MODELS[0]
|
| 153 |
-
|
| 154 |
-
# HF Inference Client
|
| 155 |
-
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 156 |
-
# Note: HF_TOKEN is checked at runtime when needed, not at import time
|
| 157 |
-
|
| 158 |
-
# Language choices for code generation
|
| 159 |
-
LANGUAGE_CHOICES = [
|
| 160 |
-
"html", "gradio", "transformers.js", "streamlit", "comfyui", "react"
|
| 161 |
-
]
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
def get_gradio_language(language):
|
| 165 |
-
"""Map composite options to a supported syntax highlighting."""
|
| 166 |
-
if language == "streamlit":
|
| 167 |
-
return "python"
|
| 168 |
-
if language == "gradio":
|
| 169 |
-
return "python"
|
| 170 |
-
if language == "comfyui":
|
| 171 |
-
return "json"
|
| 172 |
-
if language == "react":
|
| 173 |
-
return "javascript"
|
| 174 |
-
return language if language in GRADIO_SUPPORTED_LANGUAGES else None
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Documentation management for Gradio, ComfyUI, and FastRTC.
|
| 3 |
-
Handles fetching, caching, and updating documentation from llms.txt files.
|
| 4 |
-
"""
|
| 5 |
-
import os
|
| 6 |
-
import requests
|
| 7 |
-
import re
|
| 8 |
-
from datetime import datetime, timedelta
|
| 9 |
-
from typing import Optional
|
| 10 |
-
|
| 11 |
-
from .config import (
|
| 12 |
-
GRADIO_LLMS_TXT_URL, GRADIO_DOCS_CACHE_FILE, GRADIO_DOCS_LAST_UPDATE_FILE,
|
| 13 |
-
GRADIO_DOCS_UPDATE_ON_APP_UPDATE, _gradio_docs_content, _gradio_docs_last_fetched,
|
| 14 |
-
COMFYUI_LLMS_TXT_URL, COMFYUI_DOCS_CACHE_FILE, COMFYUI_DOCS_LAST_UPDATE_FILE,
|
| 15 |
-
COMFYUI_DOCS_UPDATE_ON_APP_UPDATE, _comfyui_docs_content, _comfyui_docs_last_fetched,
|
| 16 |
-
FASTRTC_LLMS_TXT_URL, FASTRTC_DOCS_CACHE_FILE, FASTRTC_DOCS_LAST_UPDATE_FILE,
|
| 17 |
-
FASTRTC_DOCS_UPDATE_ON_APP_UPDATE, _fastrtc_docs_content, _fastrtc_docs_last_fetched
|
| 18 |
-
)
|
| 19 |
-
from . import prompts
|
| 20 |
-
|
| 21 |
-
def fetch_gradio_docs() -> Optional[str]:
|
| 22 |
-
"""Fetch the latest Gradio documentation from llms.txt"""
|
| 23 |
-
try:
|
| 24 |
-
response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10)
|
| 25 |
-
response.raise_for_status()
|
| 26 |
-
return response.text
|
| 27 |
-
except Exception as e:
|
| 28 |
-
print(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")
|
| 29 |
-
return None
|
| 30 |
-
|
| 31 |
-
def fetch_comfyui_docs() -> Optional[str]:
|
| 32 |
-
"""Fetch the latest ComfyUI documentation from llms.txt"""
|
| 33 |
-
try:
|
| 34 |
-
response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10)
|
| 35 |
-
response.raise_for_status()
|
| 36 |
-
return response.text
|
| 37 |
-
except Exception as e:
|
| 38 |
-
print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")
|
| 39 |
-
return None
|
| 40 |
-
|
| 41 |
-
def fetch_fastrtc_docs() -> Optional[str]:
|
| 42 |
-
"""Fetch the latest FastRTC documentation from llms.txt"""
|
| 43 |
-
try:
|
| 44 |
-
response = requests.get(FASTRTC_LLMS_TXT_URL, timeout=10)
|
| 45 |
-
response.raise_for_status()
|
| 46 |
-
return response.text
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"Warning: Failed to fetch FastRTC docs from {FASTRTC_LLMS_TXT_URL}: {e}")
|
| 49 |
-
return None
|
| 50 |
-
|
| 51 |
-
def filter_problematic_instructions(content: str) -> str:
|
| 52 |
-
"""Filter out problematic instructions that cause LLM to stop generation prematurely"""
|
| 53 |
-
if not content:
|
| 54 |
-
return content
|
| 55 |
-
|
| 56 |
-
# List of problematic phrases that cause early termination when LLM encounters ``` in user code
|
| 57 |
-
problematic_patterns = [
|
| 58 |
-
r"Output ONLY the code inside a ``` code block, and do not include any explanations or extra text",
|
| 59 |
-
r"output only the code inside a ```.*?``` code block",
|
| 60 |
-
r"Always output only the.*?code.*?inside.*?```.*?```.*?block",
|
| 61 |
-
r"Return ONLY the code inside a.*?```.*?``` code block",
|
| 62 |
-
r"Do NOT add the language name at the top of the code output",
|
| 63 |
-
r"do not include any explanations or extra text",
|
| 64 |
-
r"Always output only the.*?code blocks.*?shown above, and do not include any explanations",
|
| 65 |
-
r"Output.*?ONLY.*?code.*?inside.*?```.*?```",
|
| 66 |
-
r"Return.*?ONLY.*?code.*?inside.*?```.*?```",
|
| 67 |
-
r"Generate.*?ONLY.*?code.*?inside.*?```.*?```",
|
| 68 |
-
r"Provide.*?ONLY.*?code.*?inside.*?```.*?```",
|
| 69 |
-
]
|
| 70 |
-
|
| 71 |
-
# Remove problematic patterns
|
| 72 |
-
filtered_content = content
|
| 73 |
-
for pattern in problematic_patterns:
|
| 74 |
-
# Use case-insensitive matching
|
| 75 |
-
filtered_content = re.sub(pattern, "", filtered_content, flags=re.IGNORECASE | re.DOTALL)
|
| 76 |
-
|
| 77 |
-
# Clean up any double newlines or extra whitespace left by removals
|
| 78 |
-
filtered_content = re.sub(r'\n\s*\n\s*\n', '\n\n', filtered_content)
|
| 79 |
-
filtered_content = re.sub(r'^\s+', '', filtered_content, flags=re.MULTILINE)
|
| 80 |
-
|
| 81 |
-
return filtered_content
|
| 82 |
-
|
| 83 |
-
def load_cached_gradio_docs() -> Optional[str]:
|
| 84 |
-
"""Load cached Gradio documentation from file"""
|
| 85 |
-
try:
|
| 86 |
-
if os.path.exists(GRADIO_DOCS_CACHE_FILE):
|
| 87 |
-
with open(GRADIO_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
|
| 88 |
-
return f.read()
|
| 89 |
-
except Exception as e:
|
| 90 |
-
print(f"Warning: Failed to load cached Gradio docs: {e}")
|
| 91 |
-
return None
|
| 92 |
-
|
| 93 |
-
def save_gradio_docs_cache(content: str):
|
| 94 |
-
"""Save Gradio documentation to cache file"""
|
| 95 |
-
try:
|
| 96 |
-
with open(GRADIO_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
|
| 97 |
-
f.write(content)
|
| 98 |
-
with open(GRADIO_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
|
| 99 |
-
f.write(datetime.now().isoformat())
|
| 100 |
-
except Exception as e:
|
| 101 |
-
print(f"Warning: Failed to save Gradio docs cache: {e}")
|
| 102 |
-
|
| 103 |
-
def load_comfyui_docs_cache() -> Optional[str]:
|
| 104 |
-
"""Load ComfyUI documentation from cache file"""
|
| 105 |
-
try:
|
| 106 |
-
if os.path.exists(COMFYUI_DOCS_CACHE_FILE):
|
| 107 |
-
with open(COMFYUI_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
|
| 108 |
-
return f.read()
|
| 109 |
-
except Exception as e:
|
| 110 |
-
print(f"Warning: Failed to load cached ComfyUI docs: {e}")
|
| 111 |
-
return None
|
| 112 |
-
|
| 113 |
-
def save_comfyui_docs_cache(content: str):
|
| 114 |
-
"""Save ComfyUI documentation to cache file"""
|
| 115 |
-
try:
|
| 116 |
-
with open(COMFYUI_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
|
| 117 |
-
f.write(content)
|
| 118 |
-
with open(COMFYUI_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
|
| 119 |
-
f.write(datetime.now().isoformat())
|
| 120 |
-
except Exception as e:
|
| 121 |
-
print(f"Warning: Failed to save ComfyUI docs cache: {e}")
|
| 122 |
-
|
| 123 |
-
def load_fastrtc_docs_cache() -> Optional[str]:
|
| 124 |
-
"""Load FastRTC documentation from cache file"""
|
| 125 |
-
try:
|
| 126 |
-
if os.path.exists(FASTRTC_DOCS_CACHE_FILE):
|
| 127 |
-
with open(FASTRTC_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
|
| 128 |
-
return f.read()
|
| 129 |
-
except Exception as e:
|
| 130 |
-
print(f"Warning: Failed to load cached FastRTC docs: {e}")
|
| 131 |
-
return None
|
| 132 |
-
|
| 133 |
-
def save_fastrtc_docs_cache(content: str):
|
| 134 |
-
"""Save FastRTC documentation to cache file"""
|
| 135 |
-
try:
|
| 136 |
-
with open(FASTRTC_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
|
| 137 |
-
f.write(content)
|
| 138 |
-
with open(FASTRTC_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
|
| 139 |
-
f.write(datetime.now().isoformat())
|
| 140 |
-
except Exception as e:
|
| 141 |
-
print(f"Warning: Failed to save FastRTC docs cache: {e}")
|
| 142 |
-
|
| 143 |
-
def get_last_update_time() -> Optional[datetime]:
|
| 144 |
-
"""Get the last update time from file"""
|
| 145 |
-
try:
|
| 146 |
-
if os.path.exists(GRADIO_DOCS_LAST_UPDATE_FILE):
|
| 147 |
-
with open(GRADIO_DOCS_LAST_UPDATE_FILE, 'r', encoding='utf-8') as f:
|
| 148 |
-
return datetime.fromisoformat(f.read().strip())
|
| 149 |
-
except Exception as e:
|
| 150 |
-
print(f"Warning: Failed to read last update time: {e}")
|
| 151 |
-
return None
|
| 152 |
-
|
| 153 |
-
def should_update_gradio_docs() -> bool:
|
| 154 |
-
"""Check if Gradio documentation should be updated"""
|
| 155 |
-
# Only update if we don't have cached content (first run or cache deleted)
|
| 156 |
-
return not os.path.exists(GRADIO_DOCS_CACHE_FILE)
|
| 157 |
-
|
| 158 |
-
def should_update_comfyui_docs() -> bool:
|
| 159 |
-
"""Check if ComfyUI documentation should be updated"""
|
| 160 |
-
# Only update if we don't have cached content (first run or cache deleted)
|
| 161 |
-
return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)
|
| 162 |
-
|
| 163 |
-
def should_update_fastrtc_docs() -> bool:
|
| 164 |
-
"""Check if FastRTC documentation should be updated"""
|
| 165 |
-
# Only update if we don't have cached content (first run or cache deleted)
|
| 166 |
-
return not os.path.exists(FASTRTC_DOCS_CACHE_FILE)
|
| 167 |
-
|
| 168 |
-
def force_update_gradio_docs():
|
| 169 |
-
"""
|
| 170 |
-
Force an update of Gradio documentation (useful when app is updated).
|
| 171 |
-
|
| 172 |
-
To manually refresh docs, you can call this function or simply delete the cache file:
|
| 173 |
-
rm .gradio_docs_cache.txt && restart the app
|
| 174 |
-
"""
|
| 175 |
-
global _gradio_docs_content, _gradio_docs_last_fetched
|
| 176 |
-
|
| 177 |
-
print("🔄 Forcing Gradio documentation update...")
|
| 178 |
-
latest_content = fetch_gradio_docs()
|
| 179 |
-
|
| 180 |
-
if latest_content:
|
| 181 |
-
# Filter out problematic instructions that cause early termination
|
| 182 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 183 |
-
_gradio_docs_content = filtered_content
|
| 184 |
-
_gradio_docs_last_fetched = datetime.now()
|
| 185 |
-
save_gradio_docs_cache(filtered_content)
|
| 186 |
-
update_gradio_system_prompts()
|
| 187 |
-
print("✅ Gradio documentation updated successfully")
|
| 188 |
-
return True
|
| 189 |
-
else:
|
| 190 |
-
print("❌ Failed to update Gradio documentation")
|
| 191 |
-
return False
|
| 192 |
-
|
| 193 |
-
def force_update_comfyui_docs():
|
| 194 |
-
"""
|
| 195 |
-
Force an update of ComfyUI documentation (useful when app is updated).
|
| 196 |
-
|
| 197 |
-
To manually refresh docs, you can call this function or simply delete the cache file:
|
| 198 |
-
rm .comfyui_docs_cache.txt && restart the app
|
| 199 |
-
"""
|
| 200 |
-
global _comfyui_docs_content, _comfyui_docs_last_fetched
|
| 201 |
-
|
| 202 |
-
print("🔄 Forcing ComfyUI documentation update...")
|
| 203 |
-
latest_content = fetch_comfyui_docs()
|
| 204 |
-
|
| 205 |
-
if latest_content:
|
| 206 |
-
# Filter out problematic instructions that cause early termination
|
| 207 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 208 |
-
_comfyui_docs_content = filtered_content
|
| 209 |
-
_comfyui_docs_last_fetched = datetime.now()
|
| 210 |
-
save_comfyui_docs_cache(filtered_content)
|
| 211 |
-
update_json_system_prompts()
|
| 212 |
-
print("✅ ComfyUI documentation updated successfully")
|
| 213 |
-
return True
|
| 214 |
-
else:
|
| 215 |
-
print("❌ Failed to update ComfyUI documentation")
|
| 216 |
-
return False
|
| 217 |
-
|
| 218 |
-
def force_update_fastrtc_docs():
|
| 219 |
-
"""
|
| 220 |
-
Force an update of FastRTC documentation (useful when app is updated).
|
| 221 |
-
|
| 222 |
-
To manually refresh docs, you can call this function or simply delete the cache file:
|
| 223 |
-
rm .fastrtc_docs_cache.txt && restart the app
|
| 224 |
-
"""
|
| 225 |
-
global _fastrtc_docs_content, _fastrtc_docs_last_fetched
|
| 226 |
-
|
| 227 |
-
print("🔄 Forcing FastRTC documentation update...")
|
| 228 |
-
latest_content = fetch_fastrtc_docs()
|
| 229 |
-
|
| 230 |
-
if latest_content:
|
| 231 |
-
# Filter out problematic instructions that cause early termination
|
| 232 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 233 |
-
_fastrtc_docs_content = filtered_content
|
| 234 |
-
_fastrtc_docs_last_fetched = datetime.now()
|
| 235 |
-
save_fastrtc_docs_cache(filtered_content)
|
| 236 |
-
update_gradio_system_prompts()
|
| 237 |
-
print("✅ FastRTC documentation updated successfully")
|
| 238 |
-
return True
|
| 239 |
-
else:
|
| 240 |
-
print("❌ Failed to update FastRTC documentation")
|
| 241 |
-
return False
|
| 242 |
-
|
| 243 |
-
def get_gradio_docs_content() -> str:
|
| 244 |
-
"""Get the current Gradio documentation content, updating if necessary"""
|
| 245 |
-
global _gradio_docs_content, _gradio_docs_last_fetched
|
| 246 |
-
|
| 247 |
-
# Check if we need to update
|
| 248 |
-
if (_gradio_docs_content is None or
|
| 249 |
-
_gradio_docs_last_fetched is None or
|
| 250 |
-
should_update_gradio_docs()):
|
| 251 |
-
|
| 252 |
-
print("Updating Gradio documentation...")
|
| 253 |
-
|
| 254 |
-
# Try to fetch latest content
|
| 255 |
-
latest_content = fetch_gradio_docs()
|
| 256 |
-
|
| 257 |
-
if latest_content:
|
| 258 |
-
# Filter out problematic instructions that cause early termination
|
| 259 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 260 |
-
_gradio_docs_content = filtered_content
|
| 261 |
-
_gradio_docs_last_fetched = datetime.now()
|
| 262 |
-
save_gradio_docs_cache(filtered_content)
|
| 263 |
-
print("✅ Gradio documentation updated successfully")
|
| 264 |
-
else:
|
| 265 |
-
# Fallback to cached content
|
| 266 |
-
cached_content = load_cached_gradio_docs()
|
| 267 |
-
if cached_content:
|
| 268 |
-
_gradio_docs_content = cached_content
|
| 269 |
-
_gradio_docs_last_fetched = datetime.now()
|
| 270 |
-
print("⚠️ Using cached Gradio documentation (network fetch failed)")
|
| 271 |
-
else:
|
| 272 |
-
# Fallback to minimal content
|
| 273 |
-
_gradio_docs_content = """
|
| 274 |
-
# Gradio API Reference (Offline Fallback)
|
| 275 |
-
|
| 276 |
-
This is a minimal fallback when documentation cannot be fetched.
|
| 277 |
-
Please check your internet connection for the latest API reference.
|
| 278 |
-
|
| 279 |
-
Basic Gradio components: Button, Textbox, Slider, Image, Audio, Video, File, etc.
|
| 280 |
-
Use gr.Blocks() for custom layouts and gr.Interface() for simple apps.
|
| 281 |
-
"""
|
| 282 |
-
print("❌ Using minimal fallback documentation")
|
| 283 |
-
|
| 284 |
-
return _gradio_docs_content or ""
|
| 285 |
-
|
| 286 |
-
def get_comfyui_docs_content() -> str:
|
| 287 |
-
"""Get the current ComfyUI documentation content, updating if necessary"""
|
| 288 |
-
global _comfyui_docs_content, _comfyui_docs_last_fetched
|
| 289 |
-
|
| 290 |
-
# Check if we need to update
|
| 291 |
-
if (_comfyui_docs_content is None or
|
| 292 |
-
_comfyui_docs_last_fetched is None or
|
| 293 |
-
should_update_comfyui_docs()):
|
| 294 |
-
|
| 295 |
-
print("Updating ComfyUI documentation...")
|
| 296 |
-
|
| 297 |
-
# Try to fetch latest content
|
| 298 |
-
latest_content = fetch_comfyui_docs()
|
| 299 |
-
|
| 300 |
-
if latest_content:
|
| 301 |
-
# Filter out problematic instructions that cause early termination
|
| 302 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 303 |
-
_comfyui_docs_content = filtered_content
|
| 304 |
-
_comfyui_docs_last_fetched = datetime.now()
|
| 305 |
-
save_comfyui_docs_cache(filtered_content)
|
| 306 |
-
print("✅ ComfyUI documentation updated successfully")
|
| 307 |
-
else:
|
| 308 |
-
# Fallback to cached content
|
| 309 |
-
cached_content = load_comfyui_docs_cache()
|
| 310 |
-
if cached_content:
|
| 311 |
-
_comfyui_docs_content = cached_content
|
| 312 |
-
_comfyui_docs_last_fetched = datetime.now()
|
| 313 |
-
print("⚠️ Using cached ComfyUI documentation (network fetch failed)")
|
| 314 |
-
else:
|
| 315 |
-
# Fallback to minimal content
|
| 316 |
-
_comfyui_docs_content = """
|
| 317 |
-
# ComfyUI API Reference (Offline Fallback)
|
| 318 |
-
|
| 319 |
-
This is a minimal fallback when documentation cannot be fetched.
|
| 320 |
-
Please check your internet connection for the latest API reference.
|
| 321 |
-
|
| 322 |
-
Basic ComfyUI workflow structure: nodes, connections, inputs, outputs.
|
| 323 |
-
Use CheckpointLoaderSimple, CLIPTextEncode, KSampler for basic workflows.
|
| 324 |
-
"""
|
| 325 |
-
print("❌ Using minimal fallback documentation")
|
| 326 |
-
|
| 327 |
-
return _comfyui_docs_content or ""
|
| 328 |
-
|
| 329 |
-
def get_fastrtc_docs_content() -> str:
|
| 330 |
-
"""Get the current FastRTC documentation content, updating if necessary"""
|
| 331 |
-
global _fastrtc_docs_content, _fastrtc_docs_last_fetched
|
| 332 |
-
|
| 333 |
-
# Check if we need to update
|
| 334 |
-
if (_fastrtc_docs_content is None or
|
| 335 |
-
_fastrtc_docs_last_fetched is None or
|
| 336 |
-
should_update_fastrtc_docs()):
|
| 337 |
-
|
| 338 |
-
print("Updating FastRTC documentation...")
|
| 339 |
-
|
| 340 |
-
# Try to fetch latest content
|
| 341 |
-
latest_content = fetch_fastrtc_docs()
|
| 342 |
-
|
| 343 |
-
if latest_content:
|
| 344 |
-
# Filter out problematic instructions that cause early termination
|
| 345 |
-
filtered_content = filter_problematic_instructions(latest_content)
|
| 346 |
-
_fastrtc_docs_content = filtered_content
|
| 347 |
-
_fastrtc_docs_last_fetched = datetime.now()
|
| 348 |
-
save_fastrtc_docs_cache(filtered_content)
|
| 349 |
-
print("✅ FastRTC documentation updated successfully")
|
| 350 |
-
else:
|
| 351 |
-
# Fallback to cached content
|
| 352 |
-
cached_content = load_fastrtc_docs_cache()
|
| 353 |
-
if cached_content:
|
| 354 |
-
_fastrtc_docs_content = cached_content
|
| 355 |
-
_fastrtc_docs_last_fetched = datetime.now()
|
| 356 |
-
print("⚠️ Using cached FastRTC documentation (network fetch failed)")
|
| 357 |
-
else:
|
| 358 |
-
# Fallback to minimal content
|
| 359 |
-
_fastrtc_docs_content = """
|
| 360 |
-
# FastRTC API Reference (Offline Fallback)
|
| 361 |
-
|
| 362 |
-
This is a minimal fallback when documentation cannot be fetched.
|
| 363 |
-
Please check your internet connection for the latest API reference.
|
| 364 |
-
|
| 365 |
-
Basic FastRTC usage: Stream class, handlers, real-time audio/video processing.
|
| 366 |
-
Use Stream(handler, modality, mode) for real-time communication apps.
|
| 367 |
-
"""
|
| 368 |
-
print("❌ Using minimal fallback documentation")
|
| 369 |
-
|
| 370 |
-
return _fastrtc_docs_content or ""
|
| 371 |
-
|
| 372 |
-
def update_gradio_system_prompts():
|
| 373 |
-
"""Update the global Gradio system prompts with latest documentation"""
|
| 374 |
-
docs_content = get_gradio_docs_content()
|
| 375 |
-
fastrtc_content = get_fastrtc_docs_content()
|
| 376 |
-
|
| 377 |
-
# Base system prompt
|
| 378 |
-
base_prompt = """You are an expert Gradio developer. Create a complete, working Gradio application based on the user's request. Generate all necessary code to make the application functional and runnable.
|
| 379 |
-
|
| 380 |
-
🚨 CRITICAL OUTPUT RULES:
|
| 381 |
-
- DO NOT use <think> tags or thinking blocks in your output
|
| 382 |
-
- DO NOT use [TOOL_CALL] or any tool call markers
|
| 383 |
-
- Generate ONLY the requested code files and requirements.txt
|
| 384 |
-
- No explanatory text outside the code blocks
|
| 385 |
-
|
| 386 |
-
## 🎯 Working with Imported Model Code
|
| 387 |
-
|
| 388 |
-
**CRITICAL: If the user has imported model code in the conversation history (InferenceClient, transformers, diffusers), you MUST integrate it into your Gradio application!**
|
| 389 |
-
|
| 390 |
-
**For InferenceClient Code (HuggingFace Inference API):**
|
| 391 |
-
- DO NOT just copy the standalone inference code
|
| 392 |
-
- Create a complete Gradio application that wraps the inference code
|
| 393 |
-
- Use `gr.ChatInterface()` for chat models or appropriate interface for other tasks
|
| 394 |
-
- Extract the model name from the imported code
|
| 395 |
-
- Implement proper streaming if the model supports it
|
| 396 |
-
- Handle conversation history correctly
|
| 397 |
-
|
| 398 |
-
**Example Structure for Chatbot:**
|
| 399 |
-
```python
|
| 400 |
-
import gradio as gr
|
| 401 |
-
import os
|
| 402 |
-
from huggingface_hub import InferenceClient
|
| 403 |
-
|
| 404 |
-
# Use the InferenceClient configuration from imported code
|
| 405 |
-
client = InferenceClient(api_key=os.environ["HF_TOKEN"])
|
| 406 |
-
|
| 407 |
-
def respond(message, history):
|
| 408 |
-
# Build messages from history
|
| 409 |
-
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 410 |
-
for user_msg, assistant_msg in history:
|
| 411 |
-
messages.append({"role": "user", "content": user_msg})
|
| 412 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
| 413 |
-
messages.append({"role": "user", "content": message})
|
| 414 |
-
|
| 415 |
-
# Call the model (use model name from imported code)
|
| 416 |
-
response = ""
|
| 417 |
-
for chunk in client.chat.completions.create(
|
| 418 |
-
model="MODEL_NAME_FROM_IMPORTED_CODE",
|
| 419 |
-
messages=messages,
|
| 420 |
-
stream=True,
|
| 421 |
-
max_tokens=1024,
|
| 422 |
-
):
|
| 423 |
-
if chunk.choices[0].delta.content:
|
| 424 |
-
response += chunk.choices[0].delta.content
|
| 425 |
-
yield response
|
| 426 |
-
|
| 427 |
-
demo = gr.ChatInterface(respond, title="Chatbot", description="Chat with the model")
|
| 428 |
-
demo.launch()
|
| 429 |
-
```
|
| 430 |
-
|
| 431 |
-
**For Transformers/Diffusers Code:**
|
| 432 |
-
- Extract model loading and inference logic
|
| 433 |
-
- Wrap it in appropriate Gradio interface
|
| 434 |
-
- For chat models: use gr.ChatInterface
|
| 435 |
-
- For image generation: use gr.Interface with image output
|
| 436 |
-
- For other tasks: choose appropriate interface type
|
| 437 |
-
- Include proper error handling and loading states
|
| 438 |
-
|
| 439 |
-
**Key Requirements:**
|
| 440 |
-
1. ✅ ALWAYS create a complete Gradio application, not just inference code
|
| 441 |
-
2. ✅ Extract model configuration from imported code
|
| 442 |
-
3. ✅ Use appropriate Gradio interface for the task
|
| 443 |
-
4. ✅ Include demo.launch() at the end
|
| 444 |
-
5. ✅ Add requirements.txt with necessary dependencies
|
| 445 |
-
|
| 446 |
-
## Multi-File Application Structure
|
| 447 |
-
|
| 448 |
-
When creating complex Gradio applications, organize your code into multiple files for better maintainability:
|
| 449 |
-
|
| 450 |
-
**File Organization:**
|
| 451 |
-
- `app.py` - Main application entry point with Gradio interface
|
| 452 |
-
- `utils.py` - Utility functions and helpers
|
| 453 |
-
- `models.py` - Model loading and inference functions
|
| 454 |
-
- `config.py` - Configuration and constants
|
| 455 |
-
- `requirements.txt` - Python dependencies
|
| 456 |
-
- Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
|
| 457 |
-
|
| 458 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 459 |
-
- NEVER generate README.md files under any circumstances
|
| 460 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 461 |
-
- Generating a README.md will break the deployment process
|
| 462 |
-
- Only generate the code files listed above
|
| 463 |
-
|
| 464 |
-
**Output Format for Multi-File Apps:**
|
| 465 |
-
When generating multi-file applications, use this exact format:
|
| 466 |
-
|
| 467 |
-
```
|
| 468 |
-
=== app.py ===
|
| 469 |
-
[main application code]
|
| 470 |
-
|
| 471 |
-
=== utils.py ===
|
| 472 |
-
[utility functions]
|
| 473 |
-
|
| 474 |
-
=== requirements.txt ===
|
| 475 |
-
[dependencies]
|
| 476 |
-
```
|
| 477 |
-
|
| 478 |
-
**🚨 CRITICAL: Always Generate requirements.txt for New Applications**
|
| 479 |
-
- ALWAYS include requirements.txt when creating new Gradio applications
|
| 480 |
-
- Generate comprehensive, production-ready dependencies based on your code
|
| 481 |
-
- Include not just direct imports but also commonly needed companion packages
|
| 482 |
-
- Use correct PyPI package names (e.g., PIL → Pillow, sklearn → scikit-learn)
|
| 483 |
-
- For diffusers: use `git+https://github.com/huggingface/diffusers`
|
| 484 |
-
- For transformers: use `git+https://github.com/huggingface/transformers`
|
| 485 |
-
- Include supporting packages (accelerate, torch, tokenizers, etc.) when using ML libraries
|
| 486 |
-
- Your requirements.txt should ensure the application works smoothly in production
|
| 487 |
-
|
| 488 |
-
**🚨 CRITICAL: requirements.txt Formatting Rules**
|
| 489 |
-
- Output ONLY plain text package names, one per line
|
| 490 |
-
- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
|
| 491 |
-
- Do NOT add explanatory text or descriptions
|
| 492 |
-
- Do NOT wrap in code blocks
|
| 493 |
-
- Just raw package names as they would appear in a real requirements.txt file
|
| 494 |
-
- Example of CORRECT format:
|
| 495 |
-
gradio
|
| 496 |
-
torch
|
| 497 |
-
transformers
|
| 498 |
-
- Example of INCORRECT format (DO NOT DO THIS):
|
| 499 |
-
```
|
| 500 |
-
gradio # For web interface
|
| 501 |
-
**Core dependencies:**
|
| 502 |
-
- torch
|
| 503 |
-
```
|
| 504 |
-
|
| 505 |
-
**Single vs Multi-File Decision:**
|
| 506 |
-
- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist
|
| 507 |
-
- Use multi-file structure for complex applications with:
|
| 508 |
-
- Multiple models or processing pipelines
|
| 509 |
-
- Extensive utility functions
|
| 510 |
-
- Complex UI with many components
|
| 511 |
-
- Data processing workflows
|
| 512 |
-
- When user specifically requests modular structure
|
| 513 |
-
|
| 514 |
-
🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
|
| 515 |
-
|
| 516 |
-
🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
|
| 517 |
-
|
| 518 |
-
## ZeroGPU Integration (MANDATORY)
|
| 519 |
-
|
| 520 |
-
ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
|
| 521 |
-
|
| 522 |
-
1. Import the spaces module: `import spaces`
|
| 523 |
-
2. Decorate GPU-dependent functions with `@spaces.GPU`
|
| 524 |
-
3. Specify appropriate duration based on expected runtime:
|
| 525 |
-
- Quick inference (< 30s): `@spaces.GPU(duration=30)`
|
| 526 |
-
- Standard generation (30-60s): `@spaces.GPU` (default 60s)
|
| 527 |
-
- Complex generation (60-120s): `@spaces.GPU(duration=120)`
|
| 528 |
-
- Heavy processing (120-180s): `@spaces.GPU(duration=180)`
|
| 529 |
-
|
| 530 |
-
Example usage:
|
| 531 |
-
```python
|
| 532 |
-
import spaces
|
| 533 |
-
from diffusers import DiffusionPipeline
|
| 534 |
-
|
| 535 |
-
pipe = DiffusionPipeline.from_pretrained(...)
|
| 536 |
-
pipe.to('cuda')
|
| 537 |
-
|
| 538 |
-
@spaces.GPU(duration=120)
|
| 539 |
-
def generate(prompt):
|
| 540 |
-
return pipe(prompt).images
|
| 541 |
-
|
| 542 |
-
gr.Interface(
|
| 543 |
-
fn=generate,
|
| 544 |
-
inputs=gr.Text(),
|
| 545 |
-
outputs=gr.Gallery(),
|
| 546 |
-
).launch()
|
| 547 |
-
```
|
| 548 |
-
|
| 549 |
-
Duration Guidelines:
|
| 550 |
-
- Shorter durations improve queue priority for users
|
| 551 |
-
- Text-to-image: typically 30-60 seconds
|
| 552 |
-
- Image-to-image: typically 20-40 seconds
|
| 553 |
-
- Video generation: typically 60-180 seconds
|
| 554 |
-
- Audio/music generation: typically 30-90 seconds
|
| 555 |
-
- Model loading + inference: add 10-30s buffer
|
| 556 |
-
- AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
|
| 557 |
-
|
| 558 |
-
Functions that typically need @spaces.GPU:
|
| 559 |
-
- Image generation (text-to-image, image-to-image)
|
| 560 |
-
- Video generation
|
| 561 |
-
- Audio/music generation
|
| 562 |
-
- Model inference with transformers, diffusers
|
| 563 |
-
- Any function using .to('cuda') or GPU operations
|
| 564 |
-
|
| 565 |
-
## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
|
| 566 |
-
|
| 567 |
-
FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.
|
| 568 |
-
This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
|
| 569 |
-
|
| 570 |
-
ALWAYS implement this pattern for diffusion models:
|
| 571 |
-
|
| 572 |
-
### MANDATORY: Basic AoT Compilation Pattern
|
| 573 |
-
YOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
|
| 574 |
-
|
| 575 |
-
1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)
|
| 576 |
-
2. ALWAYS use spaces.aoti_capture to capture inputs
|
| 577 |
-
3. ALWAYS use torch.export.export to export the transformer
|
| 578 |
-
4. ALWAYS use spaces.aoti_compile to compile
|
| 579 |
-
5. ALWAYS use spaces.aoti_apply to apply to pipeline
|
| 580 |
-
|
| 581 |
-
### Required AoT Implementation
|
| 582 |
-
```python
|
| 583 |
-
import spaces
|
| 584 |
-
import torch
|
| 585 |
-
from diffusers import DiffusionPipeline
|
| 586 |
-
|
| 587 |
-
MODEL_ID = 'black-forest-labs/FLUX.1-dev'
|
| 588 |
-
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
|
| 589 |
-
pipe.to('cuda')
|
| 590 |
-
|
| 591 |
-
@spaces.GPU(duration=1500) # Maximum duration allowed during startup
|
| 592 |
-
def compile_transformer():
|
| 593 |
-
# 1. Capture example inputs
|
| 594 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 595 |
-
pipe("arbitrary example prompt")
|
| 596 |
-
|
| 597 |
-
# 2. Export the model
|
| 598 |
-
exported = torch.export.export(
|
| 599 |
-
pipe.transformer,
|
| 600 |
-
args=call.args,
|
| 601 |
-
kwargs=call.kwargs,
|
| 602 |
-
)
|
| 603 |
-
|
| 604 |
-
# 3. Compile the exported model
|
| 605 |
-
return spaces.aoti_compile(exported)
|
| 606 |
-
|
| 607 |
-
# 4. Apply compiled model to pipeline
|
| 608 |
-
compiled_transformer = compile_transformer()
|
| 609 |
-
spaces.aoti_apply(compiled_transformer, pipe.transformer)
|
| 610 |
-
|
| 611 |
-
@spaces.GPU
|
| 612 |
-
def generate(prompt):
|
| 613 |
-
return pipe(prompt).images
|
| 614 |
-
```
|
| 615 |
-
|
| 616 |
-
### Advanced Optimizations
|
| 617 |
-
|
| 618 |
-
#### FP8 Quantization (Additional 1.2x speedup on H200)
|
| 619 |
-
```python
|
| 620 |
-
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
|
| 621 |
-
|
| 622 |
-
@spaces.GPU(duration=1500)
|
| 623 |
-
def compile_transformer_with_quantization():
|
| 624 |
-
# Quantize before export for FP8 speedup
|
| 625 |
-
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 626 |
-
|
| 627 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 628 |
-
pipe("arbitrary example prompt")
|
| 629 |
-
|
| 630 |
-
exported = torch.export.export(
|
| 631 |
-
pipe.transformer,
|
| 632 |
-
args=call.args,
|
| 633 |
-
kwargs=call.kwargs,
|
| 634 |
-
)
|
| 635 |
-
return spaces.aoti_compile(exported)
|
| 636 |
-
```
|
| 637 |
-
|
| 638 |
-
#### Dynamic Shapes (Variable input sizes)
|
| 639 |
-
```python
|
| 640 |
-
from torch.utils._pytree import tree_map
|
| 641 |
-
|
| 642 |
-
@spaces.GPU(duration=1500)
|
| 643 |
-
def compile_transformer_dynamic():
|
| 644 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 645 |
-
pipe("arbitrary example prompt")
|
| 646 |
-
|
| 647 |
-
# Define dynamic dimension ranges (model-dependent)
|
| 648 |
-
transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)
|
| 649 |
-
|
| 650 |
-
# Map argument names to dynamic dimensions
|
| 651 |
-
transformer_dynamic_shapes = {
|
| 652 |
-
"hidden_states": {1: transformer_hidden_dim},
|
| 653 |
-
"img_ids": {0: transformer_hidden_dim},
|
| 654 |
-
}
|
| 655 |
-
|
| 656 |
-
# Create dynamic shapes structure
|
| 657 |
-
dynamic_shapes = tree_map(lambda v: None, call.kwargs)
|
| 658 |
-
dynamic_shapes.update(transformer_dynamic_shapes)
|
| 659 |
-
|
| 660 |
-
exported = torch.export.export(
|
| 661 |
-
pipe.transformer,
|
| 662 |
-
args=call.args,
|
| 663 |
-
kwargs=call.kwargs,
|
| 664 |
-
dynamic_shapes=dynamic_shapes,
|
| 665 |
-
)
|
| 666 |
-
return spaces.aoti_compile(exported)
|
| 667 |
-
```
|
| 668 |
-
|
| 669 |
-
#### Multi-Compile for Different Resolutions
|
| 670 |
-
```python
|
| 671 |
-
@spaces.GPU(duration=1500)
|
| 672 |
-
def compile_multiple_resolutions():
|
| 673 |
-
compiled_models = {}
|
| 674 |
-
resolutions = [(512, 512), (768, 768), (1024, 1024)]
|
| 675 |
-
|
| 676 |
-
for width, height in resolutions:
|
| 677 |
-
# Capture inputs for specific resolution
|
| 678 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 679 |
-
pipe(f"test prompt {width}x{height}", width=width, height=height)
|
| 680 |
-
|
| 681 |
-
exported = torch.export.export(
|
| 682 |
-
pipe.transformer,
|
| 683 |
-
args=call.args,
|
| 684 |
-
kwargs=call.kwargs,
|
| 685 |
-
)
|
| 686 |
-
compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)
|
| 687 |
-
|
| 688 |
-
return compiled_models
|
| 689 |
-
|
| 690 |
-
# Usage with resolution dispatch
|
| 691 |
-
compiled_models = compile_multiple_resolutions()
|
| 692 |
-
|
| 693 |
-
@spaces.GPU
|
| 694 |
-
def generate_with_resolution(prompt, width=1024, height=1024):
|
| 695 |
-
resolution_key = f"{width}x{height}"
|
| 696 |
-
if resolution_key in compiled_models:
|
| 697 |
-
# Temporarily apply the right compiled model
|
| 698 |
-
spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)
|
| 699 |
-
return pipe(prompt, width=width, height=height).images
|
| 700 |
-
```
|
| 701 |
-
|
| 702 |
-
#### FlashAttention-3 Integration
|
| 703 |
-
```python
|
| 704 |
-
from kernels import get_kernel
|
| 705 |
-
|
| 706 |
-
# Load pre-built FA3 kernel compatible with H200
|
| 707 |
-
try:
|
| 708 |
-
vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")
|
| 709 |
-
print("✅ FlashAttention-3 kernel loaded successfully")
|
| 710 |
-
except Exception as e:
|
| 711 |
-
print(f"⚠️ FlashAttention-3 not available: {e}")
|
| 712 |
-
|
| 713 |
-
# Custom attention processor example
|
| 714 |
-
class FlashAttention3Processor:
|
| 715 |
-
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
|
| 716 |
-
# Use FA3 kernel for attention computation
|
| 717 |
-
return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
|
| 718 |
-
|
| 719 |
-
# Apply FA3 processor to model
|
| 720 |
-
if 'vllm_flash_attn3' in locals():
|
| 721 |
-
for name, module in pipe.transformer.named_modules():
|
| 722 |
-
if hasattr(module, 'processor'):
|
| 723 |
-
module.processor = FlashAttention3Processor()
|
| 724 |
-
```
|
| 725 |
-
|
| 726 |
-
### Complete Optimized Example
|
| 727 |
-
```python
|
| 728 |
-
import spaces
|
| 729 |
-
import torch
|
| 730 |
-
from diffusers import DiffusionPipeline
|
| 731 |
-
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
|
| 732 |
-
|
| 733 |
-
MODEL_ID = 'black-forest-labs/FLUX.1-dev'
|
| 734 |
-
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
|
| 735 |
-
pipe.to('cuda')
|
| 736 |
-
|
| 737 |
-
@spaces.GPU(duration=1500)
|
| 738 |
-
def compile_optimized_transformer():
|
| 739 |
-
# Apply FP8 quantization
|
| 740 |
-
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 741 |
-
|
| 742 |
-
# Capture inputs
|
| 743 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 744 |
-
pipe("optimization test prompt")
|
| 745 |
-
|
| 746 |
-
# Export and compile
|
| 747 |
-
exported = torch.export.export(
|
| 748 |
-
pipe.transformer,
|
| 749 |
-
args=call.args,
|
| 750 |
-
kwargs=call.kwargs,
|
| 751 |
-
)
|
| 752 |
-
return spaces.aoti_compile(exported)
|
| 753 |
-
|
| 754 |
-
# Compile during startup
|
| 755 |
-
compiled_transformer = compile_optimized_transformer()
|
| 756 |
-
spaces.aoti_apply(compiled_transformer, pipe.transformer)
|
| 757 |
-
|
| 758 |
-
@spaces.GPU
|
| 759 |
-
def generate(prompt):
|
| 760 |
-
return pipe(prompt).images
|
| 761 |
-
```
|
| 762 |
-
|
| 763 |
-
**Expected Performance Gains:**
|
| 764 |
-
- Basic AoT: 1.3x-1.8x speedup
|
| 765 |
-
- + FP8 Quantization: Additional 1.2x speedup
|
| 766 |
-
- + FlashAttention-3: Additional attention speedup
|
| 767 |
-
- Total potential: 2x-3x faster inference
|
| 768 |
-
**Hardware Requirements:**
|
| 769 |
-
- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)
|
| 770 |
-
- FlashAttention-3 works on H200 hardware via kernels library
|
| 771 |
-
- Dynamic shapes add flexibility for variable input sizes
|
| 772 |
-
## MCP Server Integration
|
| 773 |
-
|
| 774 |
-
When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
|
| 775 |
-
|
| 776 |
-
**🚨 CRITICAL: Enabling MCP Server**
|
| 777 |
-
To make your Gradio app function as an MCP (Model Control Protocol) server:
|
| 778 |
-
1. Set `mcp_server=True` in the `.launch()` method
|
| 779 |
-
2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)
|
| 780 |
-
3. Ensure all functions have detailed docstrings with proper Args sections
|
| 781 |
-
4. Use type hints for all function parameters
|
| 782 |
-
|
| 783 |
-
**Example:**
|
| 784 |
-
```
|
| 785 |
-
import gradio as gr
|
| 786 |
-
|
| 787 |
-
def letter_counter(word: str, letter: str) -> int:
|
| 788 |
-
\"\"\"
|
| 789 |
-
Count the number of occurrences of a letter in a word or text.
|
| 790 |
-
|
| 791 |
-
Args:
|
| 792 |
-
word (str): The input text to search through
|
| 793 |
-
letter (str): The letter to search for
|
| 794 |
-
|
| 795 |
-
Returns:
|
| 796 |
-
int: The number of times the letter appears
|
| 797 |
-
\"\"\"
|
| 798 |
-
return word.lower().count(letter.lower())
|
| 799 |
-
|
| 800 |
-
demo = gr.Interface(
|
| 801 |
-
fn=letter_counter,
|
| 802 |
-
inputs=[gr.Textbox("strawberry"), gr.Textbox("r")],
|
| 803 |
-
outputs=[gr.Number()],
|
| 804 |
-
title="Letter Counter",
|
| 805 |
-
description="Count letter occurrences in text."
|
| 806 |
-
)
|
| 807 |
-
|
| 808 |
-
if __name__ == "__main__":
|
| 809 |
-
demo.launch(mcp_server=True)
|
| 810 |
-
```
|
| 811 |
-
|
| 812 |
-
**When to Enable MCP:**
|
| 813 |
-
- User explicitly requests "MCP server" or "MCP-enabled app"
|
| 814 |
-
- User wants tool calling capabilities for LLMs
|
| 815 |
-
- User mentions Claude Desktop, Cursor, or Cline integration
|
| 816 |
-
- User wants to expose functions as tools for AI assistants
|
| 817 |
-
|
| 818 |
-
**MCP Requirements:**
|
| 819 |
-
1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)
|
| 820 |
-
2. **Docstrings:** Every function must have a detailed docstring with:
|
| 821 |
-
- Brief description on first line
|
| 822 |
-
- Args section listing each parameter with type and description
|
| 823 |
-
- Returns section (optional but recommended)
|
| 824 |
-
3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)
|
| 825 |
-
4. **Default Values:** Use default values in components to provide examples
|
| 826 |
-
|
| 827 |
-
**Best Practices for MCP Tools:**
|
| 828 |
-
- Use descriptive function names (they become tool names)
|
| 829 |
-
- Keep functions focused and single-purpose
|
| 830 |
-
- Accept string parameters when possible for better compatibility
|
| 831 |
-
- Return simple types (str, int, float, list, dict) rather than complex objects
|
| 832 |
-
- Use gr.Header for authentication headers when needed
|
| 833 |
-
- Use gr.Progress() for long-running operations
|
| 834 |
-
|
| 835 |
-
**Multiple Tools Example:**
|
| 836 |
-
```
|
| 837 |
-
import gradio as gr
|
| 838 |
-
|
| 839 |
-
def add_numbers(a: str, b: str) -> str:
|
| 840 |
-
\"\"\"
|
| 841 |
-
Add two numbers together.
|
| 842 |
-
|
| 843 |
-
Args:
|
| 844 |
-
a (str): First number
|
| 845 |
-
b (str): Second number
|
| 846 |
-
|
| 847 |
-
Returns:
|
| 848 |
-
str: Sum of the two numbers
|
| 849 |
-
\"\"\"
|
| 850 |
-
return str(int(a) + int(b))
|
| 851 |
-
|
| 852 |
-
def multiply_numbers(a: str, b: str) -> str:
|
| 853 |
-
\"\"\"
|
| 854 |
-
Multiply two numbers.
|
| 855 |
-
|
| 856 |
-
Args:
|
| 857 |
-
a (str): First number
|
| 858 |
-
b (str): Second number
|
| 859 |
-
|
| 860 |
-
Returns:
|
| 861 |
-
str: Product of the two numbers
|
| 862 |
-
\"\"\"
|
| 863 |
-
return str(int(a) * int(b))
|
| 864 |
-
|
| 865 |
-
with gr.Blocks() as demo:
|
| 866 |
-
gr.Markdown("# Math Tools MCP Server")
|
| 867 |
-
|
| 868 |
-
with gr.Tab("Add"):
|
| 869 |
-
gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox())
|
| 870 |
-
|
| 871 |
-
with gr.Tab("Multiply"):
|
| 872 |
-
gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
|
| 873 |
-
|
| 874 |
-
if __name__ == "__main__":
|
| 875 |
-
demo.launch(mcp_server=True)
|
| 876 |
-
```
|
| 877 |
-
|
| 878 |
-
**REMEMBER:** If MCP is requested, ALWAYS:
|
| 879 |
-
1. Set `mcp_server=True` in `.launch()`
|
| 880 |
-
2. Use `gradio[mcp]` in requirements.txt
|
| 881 |
-
3. Include complete docstrings with Args sections
|
| 882 |
-
4. Add type hints to all parameters
|
| 883 |
-
|
| 884 |
-
## Complete Gradio API Reference
|
| 885 |
-
|
| 886 |
-
This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
|
| 887 |
-
|
| 888 |
-
"""
|
| 889 |
-
|
| 890 |
-
# Search-enabled prompt
|
| 891 |
-
search_prompt = """You are an expert Gradio developer with access to real-time web search. Create a complete, working Gradio application based on the user's request. When needed, use web search to find current best practices or verify latest Gradio features. Generate all necessary code to make the application functional and runnable.
|
| 892 |
-
|
| 893 |
-
## Multi-File Application Structure
|
| 894 |
-
|
| 895 |
-
When creating complex Gradio applications, organize your code into multiple files for better maintainability:
|
| 896 |
-
|
| 897 |
-
**File Organization:**
|
| 898 |
-
- `app.py` - Main application entry point with Gradio interface
|
| 899 |
-
- `utils.py` - Utility functions and helpers
|
| 900 |
-
- `models.py` - Model loading and inference functions
|
| 901 |
-
- `config.py` - Configuration and constants
|
| 902 |
-
- `requirements.txt` - Python dependencies
|
| 903 |
-
- Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
|
| 904 |
-
|
| 905 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 906 |
-
- NEVER generate README.md files under any circumstances
|
| 907 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 908 |
-
- Generating a README.md will break the deployment process
|
| 909 |
-
- Only generate the code files listed above
|
| 910 |
-
|
| 911 |
-
**Output Format for Multi-File Apps:**
|
| 912 |
-
When generating multi-file applications, use this exact format:
|
| 913 |
-
|
| 914 |
-
```
|
| 915 |
-
=== app.py ===
|
| 916 |
-
[main application code]
|
| 917 |
-
|
| 918 |
-
=== utils.py ===
|
| 919 |
-
[utility functions]
|
| 920 |
-
|
| 921 |
-
=== requirements.txt ===
|
| 922 |
-
[dependencies]
|
| 923 |
-
```
|
| 924 |
-
|
| 925 |
-
**🚨 CRITICAL: requirements.txt Formatting Rules**
|
| 926 |
-
- Output ONLY plain text package names, one per line
|
| 927 |
-
- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
|
| 928 |
-
- Do NOT add explanatory text or descriptions
|
| 929 |
-
- Do NOT wrap in code blocks
|
| 930 |
-
- Just raw package names as they would appear in a real requirements.txt file
|
| 931 |
-
- Example of CORRECT format:
|
| 932 |
-
gradio
|
| 933 |
-
torch
|
| 934 |
-
transformers
|
| 935 |
-
- Example of INCORRECT format (DO NOT DO THIS):
|
| 936 |
-
```
|
| 937 |
-
gradio # For web interface
|
| 938 |
-
**Core dependencies:**
|
| 939 |
-
- torch
|
| 940 |
-
```
|
| 941 |
-
|
| 942 |
-
**Single vs Multi-File Decision:**
|
| 943 |
-
- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist
|
| 944 |
-
- Use multi-file structure for complex applications with:
|
| 945 |
-
- Multiple models or processing pipelines
|
| 946 |
-
- Extensive utility functions
|
| 947 |
-
- Complex UI with many components
|
| 948 |
-
- Data processing workflows
|
| 949 |
-
- When user specifically requests modular structure
|
| 950 |
-
|
| 951 |
-
🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
|
| 952 |
-
|
| 953 |
-
🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
|
| 954 |
-
|
| 955 |
-
## ZeroGPU Integration (MANDATORY)
|
| 956 |
-
|
| 957 |
-
ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
|
| 958 |
-
|
| 959 |
-
1. Import the spaces module: `import spaces`
|
| 960 |
-
2. Decorate GPU-dependent functions with `@spaces.GPU`
|
| 961 |
-
3. Specify appropriate duration based on expected runtime:
|
| 962 |
-
- Quick inference (< 30s): `@spaces.GPU(duration=30)`
|
| 963 |
-
- Standard generation (30-60s): `@spaces.GPU` (default 60s)
|
| 964 |
-
- Complex generation (60-120s): `@spaces.GPU(duration=120)`
|
| 965 |
-
- Heavy processing (120-180s): `@spaces.GPU(duration=180)`
|
| 966 |
-
|
| 967 |
-
Example usage:
|
| 968 |
-
```
|
| 969 |
-
import spaces
|
| 970 |
-
from diffusers import DiffusionPipeline
|
| 971 |
-
|
| 972 |
-
pipe = DiffusionPipeline.from_pretrained(...)
|
| 973 |
-
pipe.to('cuda')
|
| 974 |
-
|
| 975 |
-
@spaces.GPU(duration=120)
|
| 976 |
-
def generate(prompt):
|
| 977 |
-
return pipe(prompt).images
|
| 978 |
-
|
| 979 |
-
gr.Interface(
|
| 980 |
-
fn=generate,
|
| 981 |
-
inputs=gr.Text(),
|
| 982 |
-
outputs=gr.Gallery(),
|
| 983 |
-
).launch()
|
| 984 |
-
```
|
| 985 |
-
|
| 986 |
-
Duration Guidelines:
|
| 987 |
-
- Shorter durations improve queue priority for users
|
| 988 |
-
- Text-to-image: typically 30-60 seconds
|
| 989 |
-
- Image-to-image: typically 20-40 seconds
|
| 990 |
-
- Video generation: typically 60-180 seconds
|
| 991 |
-
- Audio/music generation: typically 30-90 seconds
|
| 992 |
-
- Model loading + inference: add 10-30s buffer
|
| 993 |
-
- AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
|
| 994 |
-
|
| 995 |
-
Functions that typically need @spaces.GPU:
|
| 996 |
-
- Image generation (text-to-image, image-to-image)
|
| 997 |
-
- Video generation
|
| 998 |
-
- Audio/music generation
|
| 999 |
-
- Model inference with transformers, diffusers
|
| 1000 |
-
- Any function using .to('cuda') or GPU operations
|
| 1001 |
-
|
| 1002 |
-
## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
|
| 1003 |
-
|
| 1004 |
-
FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.
|
| 1005 |
-
This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
|
| 1006 |
-
|
| 1007 |
-
ALWAYS implement this pattern for diffusion models:
|
| 1008 |
-
|
| 1009 |
-
### MANDATORY: Basic AoT Compilation Pattern
|
| 1010 |
-
YOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
|
| 1011 |
-
|
| 1012 |
-
1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)
|
| 1013 |
-
2. ALWAYS use spaces.aoti_capture to capture inputs
|
| 1014 |
-
3. ALWAYS use torch.export.export to export the transformer
|
| 1015 |
-
4. ALWAYS use spaces.aoti_compile to compile
|
| 1016 |
-
5. ALWAYS use spaces.aoti_apply to apply to pipeline
|
| 1017 |
-
|
| 1018 |
-
### Required AoT Implementation
|
| 1019 |
-
|
| 1020 |
-
For production Spaces with heavy models, use ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:
|
| 1021 |
-
|
| 1022 |
-
### Basic AoT Compilation
|
| 1023 |
-
```
|
| 1024 |
-
import spaces
|
| 1025 |
-
import torch
|
| 1026 |
-
from diffusers import DiffusionPipeline
|
| 1027 |
-
|
| 1028 |
-
MODEL_ID = 'black-forest-labs/FLUX.1-dev'
|
| 1029 |
-
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
|
| 1030 |
-
pipe.to('cuda')
|
| 1031 |
-
|
| 1032 |
-
@spaces.GPU(duration=1500) # Maximum duration allowed during startup
|
| 1033 |
-
def compile_transformer():
|
| 1034 |
-
# 1. Capture example inputs
|
| 1035 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 1036 |
-
pipe("arbitrary example prompt")
|
| 1037 |
-
|
| 1038 |
-
# 2. Export the model
|
| 1039 |
-
exported = torch.export.export(
|
| 1040 |
-
pipe.transformer,
|
| 1041 |
-
args=call.args,
|
| 1042 |
-
kwargs=call.kwargs,
|
| 1043 |
-
)
|
| 1044 |
-
|
| 1045 |
-
# 3. Compile the exported model
|
| 1046 |
-
return spaces.aoti_compile(exported)
|
| 1047 |
-
|
| 1048 |
-
# 4. Apply compiled model to pipeline
|
| 1049 |
-
compiled_transformer = compile_transformer()
|
| 1050 |
-
spaces.aoti_apply(compiled_transformer, pipe.transformer)
|
| 1051 |
-
|
| 1052 |
-
@spaces.GPU
|
| 1053 |
-
def generate(prompt):
|
| 1054 |
-
return pipe(prompt).images
|
| 1055 |
-
```
|
| 1056 |
-
|
| 1057 |
-
### Advanced Optimizations
|
| 1058 |
-
|
| 1059 |
-
#### FP8 Quantization (Additional 1.2x speedup on H200)
|
| 1060 |
-
```
|
| 1061 |
-
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
|
| 1062 |
-
|
| 1063 |
-
@spaces.GPU(duration=1500)
|
| 1064 |
-
def compile_transformer_with_quantization():
|
| 1065 |
-
# Quantize before export for FP8 speedup
|
| 1066 |
-
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 1067 |
-
|
| 1068 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 1069 |
-
pipe("arbitrary example prompt")
|
| 1070 |
-
|
| 1071 |
-
exported = torch.export.export(
|
| 1072 |
-
pipe.transformer,
|
| 1073 |
-
args=call.args,
|
| 1074 |
-
kwargs=call.kwargs,
|
| 1075 |
-
)
|
| 1076 |
-
return spaces.aoti_compile(exported)
|
| 1077 |
-
```
|
| 1078 |
-
|
| 1079 |
-
#### Dynamic Shapes (Variable input sizes)
|
| 1080 |
-
```
|
| 1081 |
-
from torch.utils._pytree import tree_map
|
| 1082 |
-
|
| 1083 |
-
@spaces.GPU(duration=1500)
|
| 1084 |
-
def compile_transformer_dynamic():
|
| 1085 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 1086 |
-
pipe("arbitrary example prompt")
|
| 1087 |
-
|
| 1088 |
-
# Define dynamic dimension ranges (model-dependent)
|
| 1089 |
-
transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)
|
| 1090 |
-
|
| 1091 |
-
# Map argument names to dynamic dimensions
|
| 1092 |
-
transformer_dynamic_shapes = {
|
| 1093 |
-
"hidden_states": {1: transformer_hidden_dim},
|
| 1094 |
-
"img_ids": {0: transformer_hidden_dim},
|
| 1095 |
-
}
|
| 1096 |
-
|
| 1097 |
-
# Create dynamic shapes structure
|
| 1098 |
-
dynamic_shapes = tree_map(lambda v: None, call.kwargs)
|
| 1099 |
-
dynamic_shapes.update(transformer_dynamic_shapes)
|
| 1100 |
-
|
| 1101 |
-
exported = torch.export.export(
|
| 1102 |
-
pipe.transformer,
|
| 1103 |
-
args=call.args,
|
| 1104 |
-
kwargs=call.kwargs,
|
| 1105 |
-
dynamic_shapes=dynamic_shapes,
|
| 1106 |
-
)
|
| 1107 |
-
return spaces.aoti_compile(exported)
|
| 1108 |
-
```
|
| 1109 |
-
|
| 1110 |
-
#### Multi-Compile for Different Resolutions
|
| 1111 |
-
```
|
| 1112 |
-
@spaces.GPU(duration=1500)
|
| 1113 |
-
def compile_multiple_resolutions():
|
| 1114 |
-
compiled_models = {}
|
| 1115 |
-
resolutions = [(512, 512), (768, 768), (1024, 1024)]
|
| 1116 |
-
|
| 1117 |
-
for width, height in resolutions:
|
| 1118 |
-
# Capture inputs for specific resolution
|
| 1119 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 1120 |
-
pipe(f"test prompt {width}x{height}", width=width, height=height)
|
| 1121 |
-
|
| 1122 |
-
exported = torch.export.export(
|
| 1123 |
-
pipe.transformer,
|
| 1124 |
-
args=call.args,
|
| 1125 |
-
kwargs=call.kwargs,
|
| 1126 |
-
)
|
| 1127 |
-
compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)
|
| 1128 |
-
|
| 1129 |
-
return compiled_models
|
| 1130 |
-
|
| 1131 |
-
# Usage with resolution dispatch
|
| 1132 |
-
compiled_models = compile_multiple_resolutions()
|
| 1133 |
-
|
| 1134 |
-
@spaces.GPU
|
| 1135 |
-
def generate_with_resolution(prompt, width=1024, height=1024):
|
| 1136 |
-
resolution_key = f"{width}x{height}"
|
| 1137 |
-
if resolution_key in compiled_models:
|
| 1138 |
-
# Temporarily apply the right compiled model
|
| 1139 |
-
spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)
|
| 1140 |
-
return pipe(prompt, width=width, height=height).images
|
| 1141 |
-
```
|
| 1142 |
-
|
| 1143 |
-
#### FlashAttention-3 Integration
|
| 1144 |
-
```
|
| 1145 |
-
from kernels import get_kernel
|
| 1146 |
-
|
| 1147 |
-
# Load pre-built FA3 kernel compatible with H200
|
| 1148 |
-
try:
|
| 1149 |
-
vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")
|
| 1150 |
-
print("✅ FlashAttention-3 kernel loaded successfully")
|
| 1151 |
-
except Exception as e:
|
| 1152 |
-
print(f"⚠️ FlashAttention-3 not available: {e}")
|
| 1153 |
-
|
| 1154 |
-
# Custom attention processor example
|
| 1155 |
-
class FlashAttention3Processor:
|
| 1156 |
-
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
|
| 1157 |
-
# Use FA3 kernel for attention computation
|
| 1158 |
-
return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
|
| 1159 |
-
|
| 1160 |
-
# Apply FA3 processor to model
|
| 1161 |
-
if 'vllm_flash_attn3' in locals():
|
| 1162 |
-
for name, module in pipe.transformer.named_modules():
|
| 1163 |
-
if hasattr(module, 'processor'):
|
| 1164 |
-
module.processor = FlashAttention3Processor()
|
| 1165 |
-
```
|
| 1166 |
-
|
| 1167 |
-
### Complete Optimized Example
|
| 1168 |
-
```
|
| 1169 |
-
import spaces
|
| 1170 |
-
import torch
|
| 1171 |
-
from diffusers import DiffusionPipeline
|
| 1172 |
-
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
|
| 1173 |
-
|
| 1174 |
-
MODEL_ID = 'black-forest-labs/FLUX.1-dev'
|
| 1175 |
-
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
|
| 1176 |
-
pipe.to('cuda')
|
| 1177 |
-
|
| 1178 |
-
@spaces.GPU(duration=1500)
|
| 1179 |
-
def compile_optimized_transformer():
|
| 1180 |
-
# Apply FP8 quantization
|
| 1181 |
-
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 1182 |
-
|
| 1183 |
-
# Capture inputs
|
| 1184 |
-
with spaces.aoti_capture(pipe.transformer) as call:
|
| 1185 |
-
pipe("optimization test prompt")
|
| 1186 |
-
|
| 1187 |
-
# Export and compile
|
| 1188 |
-
exported = torch.export.export(
|
| 1189 |
-
pipe.transformer,
|
| 1190 |
-
args=call.args,
|
| 1191 |
-
kwargs=call.kwargs,
|
| 1192 |
-
)
|
| 1193 |
-
return spaces.aoti_compile(exported)
|
| 1194 |
-
|
| 1195 |
-
# Compile during startup
|
| 1196 |
-
compiled_transformer = compile_optimized_transformer()
|
| 1197 |
-
spaces.aoti_apply(compiled_transformer, pipe.transformer)
|
| 1198 |
-
|
| 1199 |
-
@spaces.GPU
|
| 1200 |
-
def generate(prompt):
|
| 1201 |
-
return pipe(prompt).images
|
| 1202 |
-
```
|
| 1203 |
-
|
| 1204 |
-
**Expected Performance Gains:**
|
| 1205 |
-
- Basic AoT: 1.3x-1.8x speedup
|
| 1206 |
-
- + FP8 Quantization: Additional 1.2x speedup
|
| 1207 |
-
- + FlashAttention-3: Additional attention speedup
|
| 1208 |
-
- Total potential: 2x-3x faster inference
|
| 1209 |
-
|
| 1210 |
-
**Hardware Requirements:**
|
| 1211 |
-
- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)
|
| 1212 |
-
- FlashAttention-3 works on H200 hardware via kernels library
|
| 1213 |
-
- Dynamic shapes add flexibility for variable input sizes
|
| 1214 |
-
|
| 1215 |
-
## MCP Server Integration
|
| 1216 |
-
|
| 1217 |
-
When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
|
| 1218 |
-
|
| 1219 |
-
**🚨 CRITICAL: Enabling MCP Server**
|
| 1220 |
-
To make your Gradio app function as an MCP (Model Control Protocol) server:
|
| 1221 |
-
1. Set `mcp_server=True` in the `.launch()` method
|
| 1222 |
-
2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)
|
| 1223 |
-
3. Ensure all functions have detailed docstrings with proper Args sections
|
| 1224 |
-
4. Use type hints for all function parameters
|
| 1225 |
-
|
| 1226 |
-
**Example:**
|
| 1227 |
-
```
|
| 1228 |
-
import gradio as gr
|
| 1229 |
-
|
| 1230 |
-
def letter_counter(word: str, letter: str) -> int:
|
| 1231 |
-
\"\"\"
|
| 1232 |
-
Count the number of occurrences of a letter in a word or text.
|
| 1233 |
-
|
| 1234 |
-
Args:
|
| 1235 |
-
word (str): The input text to search through
|
| 1236 |
-
letter (str): The letter to search for
|
| 1237 |
-
|
| 1238 |
-
Returns:
|
| 1239 |
-
int: The number of times the letter appears
|
| 1240 |
-
\"\"\"
|
| 1241 |
-
return word.lower().count(letter.lower())
|
| 1242 |
-
|
| 1243 |
-
demo = gr.Interface(
|
| 1244 |
-
fn=letter_counter,
|
| 1245 |
-
inputs=[gr.Textbox("strawberry"), gr.Textbox("r")],
|
| 1246 |
-
outputs=[gr.Number()],
|
| 1247 |
-
title="Letter Counter",
|
| 1248 |
-
description="Count letter occurrences in text."
|
| 1249 |
-
)
|
| 1250 |
-
|
| 1251 |
-
if __name__ == "__main__":
|
| 1252 |
-
demo.launch(mcp_server=True)
|
| 1253 |
-
```
|
| 1254 |
-
|
| 1255 |
-
**When to Enable MCP:**
|
| 1256 |
-
- User explicitly requests "MCP server" or "MCP-enabled app"
|
| 1257 |
-
- User wants tool calling capabilities for LLMs
|
| 1258 |
-
- User mentions Claude Desktop, Cursor, or Cline integration
|
| 1259 |
-
- User wants to expose functions as tools for AI assistants
|
| 1260 |
-
|
| 1261 |
-
**MCP Requirements:**
|
| 1262 |
-
1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)
|
| 1263 |
-
2. **Docstrings:** Every function must have a detailed docstring with:
|
| 1264 |
-
- Brief description on first line
|
| 1265 |
-
- Args section listing each parameter with type and description
|
| 1266 |
-
- Returns section (optional but recommended)
|
| 1267 |
-
3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)
|
| 1268 |
-
4. **Default Values:** Use default values in components to provide examples
|
| 1269 |
-
|
| 1270 |
-
**Best Practices for MCP Tools:**
|
| 1271 |
-
- Use descriptive function names (they become tool names)
|
| 1272 |
-
- Keep functions focused and single-purpose
|
| 1273 |
-
- Accept string parameters when possible for better compatibility
|
| 1274 |
-
- Return simple types (str, int, float, list, dict) rather than complex objects
|
| 1275 |
-
- Use gr.Header for authentication headers when needed
|
| 1276 |
-
- Use gr.Progress() for long-running operations
|
| 1277 |
-
|
| 1278 |
-
**Multiple Tools Example:**
|
| 1279 |
-
```
|
| 1280 |
-
import gradio as gr
|
| 1281 |
-
|
| 1282 |
-
def add_numbers(a: str, b: str) -> str:
|
| 1283 |
-
\"\"\"
|
| 1284 |
-
Add two numbers together.
|
| 1285 |
-
|
| 1286 |
-
Args:
|
| 1287 |
-
a (str): First number
|
| 1288 |
-
b (str): Second number
|
| 1289 |
-
|
| 1290 |
-
Returns:
|
| 1291 |
-
str: Sum of the two numbers
|
| 1292 |
-
\"\"\"
|
| 1293 |
-
return str(int(a) + int(b))
|
| 1294 |
-
|
| 1295 |
-
def multiply_numbers(a: str, b: str) -> str:
|
| 1296 |
-
\"\"\"
|
| 1297 |
-
Multiply two numbers.
|
| 1298 |
-
|
| 1299 |
-
Args:
|
| 1300 |
-
a (str): First number
|
| 1301 |
-
b (str): Second number
|
| 1302 |
-
|
| 1303 |
-
Returns:
|
| 1304 |
-
str: Product of the two numbers
|
| 1305 |
-
\"\"\"
|
| 1306 |
-
return str(int(a) * int(b))
|
| 1307 |
-
|
| 1308 |
-
with gr.Blocks() as demo:
|
| 1309 |
-
gr.Markdown("# Math Tools MCP Server")
|
| 1310 |
-
|
| 1311 |
-
with gr.Tab("Add"):
|
| 1312 |
-
gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox())
|
| 1313 |
-
|
| 1314 |
-
with gr.Tab("Multiply"):
|
| 1315 |
-
gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
|
| 1316 |
-
|
| 1317 |
-
if __name__ == "__main__":
|
| 1318 |
-
demo.launch(mcp_server=True)
|
| 1319 |
-
```
|
| 1320 |
-
|
| 1321 |
-
**REMEMBER:** If MCP is requested, ALWAYS:
|
| 1322 |
-
1. Set `mcp_server=True` in `.launch()`
|
| 1323 |
-
2. Use `gradio[mcp]` in requirements.txt
|
| 1324 |
-
3. Include complete docstrings with Args sections
|
| 1325 |
-
4. Add type hints to all parameters
|
| 1326 |
-
|
| 1327 |
-
## Complete Gradio API Reference
|
| 1328 |
-
|
| 1329 |
-
This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
|
| 1330 |
-
|
| 1331 |
-
"""
|
| 1332 |
-
|
| 1333 |
-
# Add FastRTC documentation if available
|
| 1334 |
-
if fastrtc_content.strip():
|
| 1335 |
-
fastrtc_section = f"""
|
| 1336 |
-
## FastRTC Reference Documentation
|
| 1337 |
-
|
| 1338 |
-
When building real-time audio/video applications with Gradio, use this FastRTC reference:
|
| 1339 |
-
|
| 1340 |
-
{fastrtc_content}
|
| 1341 |
-
|
| 1342 |
-
This reference is automatically synced from https://fastrtc.org/llms.txt to ensure accuracy.
|
| 1343 |
-
|
| 1344 |
-
"""
|
| 1345 |
-
base_prompt += fastrtc_section
|
| 1346 |
-
search_prompt += fastrtc_section
|
| 1347 |
-
|
| 1348 |
-
# Update the prompts in the prompts module
|
| 1349 |
-
final_instructions = """\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.
|
| 1350 |
-
|
| 1351 |
-
🔍 BEFORE GENERATING: Review the conversation history carefully. If the user has imported any model code (InferenceClient, transformers, diffusers), you MUST integrate that code into your Gradio application. Do not generate standalone inference code - create a complete Gradio app that wraps the imported model functionality.
|
| 1352 |
-
|
| 1353 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 1354 |
-
|
| 1355 |
-
prompts.GRADIO_SYSTEM_PROMPT = base_prompt + docs_content + final_instructions
|
| 1356 |
-
prompts.GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + final_instructions
|
| 1357 |
-
|
| 1358 |
-
def update_json_system_prompts():
|
| 1359 |
-
"""Update the global JSON system prompts with latest ComfyUI documentation"""
|
| 1360 |
-
docs_content = get_comfyui_docs_content()
|
| 1361 |
-
|
| 1362 |
-
# Base system prompt for regular JSON
|
| 1363 |
-
base_prompt = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
|
| 1364 |
-
- Use double quotes for strings
|
| 1365 |
-
- No trailing commas
|
| 1366 |
-
- Proper nesting and structure
|
| 1367 |
-
- Valid data types (string, number, boolean, null, object, array)
|
| 1368 |
-
|
| 1369 |
-
Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly.
|
| 1370 |
-
|
| 1371 |
-
"""
|
| 1372 |
-
|
| 1373 |
-
# Search-enabled system prompt for regular JSON
|
| 1374 |
-
search_prompt = """You are an expert JSON developer. You have access to real-time web search. When needed, use web search to find the latest information or data structures for your JSON generation.
|
| 1375 |
-
|
| 1376 |
-
Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
|
| 1377 |
-
- Use double quotes for strings
|
| 1378 |
-
- No trailing commas
|
| 1379 |
-
- Proper nesting and structure
|
| 1380 |
-
- Valid data types (string, number, boolean, null, object, array)
|
| 1381 |
-
|
| 1382 |
-
Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly.
|
| 1383 |
-
|
| 1384 |
-
"""
|
| 1385 |
-
|
| 1386 |
-
# Add ComfyUI documentation if available
|
| 1387 |
-
if docs_content.strip():
|
| 1388 |
-
comfyui_section = f"""
|
| 1389 |
-
## ComfyUI Reference Documentation
|
| 1390 |
-
|
| 1391 |
-
When generating JSON data related to ComfyUI workflows, nodes, or configurations, use this reference:
|
| 1392 |
-
|
| 1393 |
-
{docs_content}
|
| 1394 |
-
|
| 1395 |
-
This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
|
| 1396 |
-
|
| 1397 |
-
"""
|
| 1398 |
-
base_prompt += comfyui_section
|
| 1399 |
-
search_prompt += comfyui_section
|
| 1400 |
-
|
| 1401 |
-
# Update the prompts in the prompts module
|
| 1402 |
-
prompts.JSON_SYSTEM_PROMPT = base_prompt
|
| 1403 |
-
prompts.JSON_SYSTEM_PROMPT_WITH_SEARCH = search_prompt
|
| 1404 |
-
|
| 1405 |
-
def get_comfyui_system_prompt():
|
| 1406 |
-
"""Get ComfyUI-specific system prompt with enhanced guidance"""
|
| 1407 |
-
docs_content = get_comfyui_docs_content()
|
| 1408 |
-
|
| 1409 |
-
base_prompt = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
|
| 1410 |
-
|
| 1411 |
-
ComfyUI workflows are JSON structures that define:
|
| 1412 |
-
- Nodes: Individual processing units with specific functions
|
| 1413 |
-
- Connections: Links between nodes that define data flow
|
| 1414 |
-
- Parameters: Configuration values for each node
|
| 1415 |
-
- Inputs/Outputs: Data flow between nodes
|
| 1416 |
-
|
| 1417 |
-
Follow JSON syntax rules strictly:
|
| 1418 |
-
- Use double quotes for strings
|
| 1419 |
-
- No trailing commas
|
| 1420 |
-
- Proper nesting and structure
|
| 1421 |
-
- Valid data types (string, number, boolean, null, object, array)
|
| 1422 |
-
|
| 1423 |
-
Generate ONLY the ComfyUI workflow JSON - no HTML, no applications, no explanations outside the JSON. The output should be a complete, valid ComfyUI workflow that can be loaded directly into ComfyUI.
|
| 1424 |
-
|
| 1425 |
-
"""
|
| 1426 |
-
|
| 1427 |
-
# Add ComfyUI documentation if available
|
| 1428 |
-
if docs_content.strip():
|
| 1429 |
-
comfyui_section = f"""
|
| 1430 |
-
## ComfyUI Reference Documentation
|
| 1431 |
-
|
| 1432 |
-
Use this reference for accurate node types, parameters, and workflow structures:
|
| 1433 |
-
|
| 1434 |
-
{docs_content}
|
| 1435 |
-
|
| 1436 |
-
This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
|
| 1437 |
-
|
| 1438 |
-
"""
|
| 1439 |
-
base_prompt += comfyui_section
|
| 1440 |
-
|
| 1441 |
-
base_prompt += """
|
| 1442 |
-
IMPORTANT: Always include "Built with anycoder" as a comment or metadata field in your ComfyUI workflow JSON that references https://huggingface.co/spaces/akhaliq/anycoder
|
| 1443 |
-
"""
|
| 1444 |
-
|
| 1445 |
-
return base_prompt
|
| 1446 |
-
|
| 1447 |
-
# Initialize Gradio documentation on startup
|
| 1448 |
-
def initialize_gradio_docs():
|
| 1449 |
-
"""Initialize Gradio documentation on application startup"""
|
| 1450 |
-
try:
|
| 1451 |
-
update_gradio_system_prompts()
|
| 1452 |
-
if should_update_gradio_docs():
|
| 1453 |
-
print("🚀 Gradio documentation system initialized (fetched fresh content)")
|
| 1454 |
-
else:
|
| 1455 |
-
print("🚀 Gradio documentation system initialized (using cached content)")
|
| 1456 |
-
except Exception as e:
|
| 1457 |
-
print(f"Warning: Failed to initialize Gradio documentation: {e}")
|
| 1458 |
-
|
| 1459 |
-
# Initialize ComfyUI documentation on startup
|
| 1460 |
-
def initialize_comfyui_docs():
|
| 1461 |
-
"""Initialize ComfyUI documentation on application startup"""
|
| 1462 |
-
try:
|
| 1463 |
-
update_json_system_prompts()
|
| 1464 |
-
if should_update_comfyui_docs():
|
| 1465 |
-
print("🚀 ComfyUI documentation system initialized (fetched fresh content)")
|
| 1466 |
-
else:
|
| 1467 |
-
print("🚀 ComfyUI documentation system initialized (using cached content)")
|
| 1468 |
-
except Exception as e:
|
| 1469 |
-
print(f"Warning: Failed to initialize ComfyUI documentation: {e}")
|
| 1470 |
-
|
| 1471 |
-
# Initialize FastRTC documentation on startup
|
| 1472 |
-
def initialize_fastrtc_docs():
|
| 1473 |
-
"""Initialize FastRTC documentation on application startup"""
|
| 1474 |
-
try:
|
| 1475 |
-
# FastRTC docs are integrated into Gradio system prompts
|
| 1476 |
-
# So we call update_gradio_system_prompts to include FastRTC content
|
| 1477 |
-
update_gradio_system_prompts()
|
| 1478 |
-
if should_update_fastrtc_docs():
|
| 1479 |
-
print("🚀 FastRTC documentation system initialized (fetched fresh content)")
|
| 1480 |
-
else:
|
| 1481 |
-
print("🚀 FastRTC documentation system initialized (using cached content)")
|
| 1482 |
-
except Exception as e:
|
| 1483 |
-
print(f"Warning: Failed to initialize FastRTC documentation: {e}")
|
| 1484 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/models.py
DELETED
|
@@ -1,338 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Model inference and client management for AnyCoder.
|
| 3 |
-
Handles different model providers and inference clients.
|
| 4 |
-
"""
|
| 5 |
-
import os
|
| 6 |
-
from typing import Dict, List, Optional, Tuple
|
| 7 |
-
import re
|
| 8 |
-
from http import HTTPStatus
|
| 9 |
-
|
| 10 |
-
from huggingface_hub import InferenceClient
|
| 11 |
-
from openai import OpenAI
|
| 12 |
-
from mistralai import Mistral
|
| 13 |
-
import dashscope
|
| 14 |
-
|
| 15 |
-
from .config import HF_TOKEN, AVAILABLE_MODELS
|
| 16 |
-
|
| 17 |
-
# Type definitions
|
| 18 |
-
History = List[Dict[str, str]]
|
| 19 |
-
Messages = List[Dict[str, str]]
|
| 20 |
-
|
| 21 |
-
def get_inference_client(model_id, provider="auto"):
|
| 22 |
-
"""Return an InferenceClient with provider based on model_id and user selection."""
|
| 23 |
-
if model_id == "qwen3-30b-a3b-instruct-2507":
|
| 24 |
-
# Use DashScope OpenAI client
|
| 25 |
-
return OpenAI(
|
| 26 |
-
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
| 27 |
-
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
| 28 |
-
)
|
| 29 |
-
elif model_id == "qwen3-30b-a3b-thinking-2507":
|
| 30 |
-
# Use DashScope OpenAI client for Thinking model
|
| 31 |
-
return OpenAI(
|
| 32 |
-
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
| 33 |
-
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
| 34 |
-
)
|
| 35 |
-
elif model_id == "qwen3-coder-30b-a3b-instruct":
|
| 36 |
-
# Use DashScope OpenAI client for Coder model
|
| 37 |
-
return OpenAI(
|
| 38 |
-
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
| 39 |
-
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
| 40 |
-
)
|
| 41 |
-
elif model_id == "gpt-5":
|
| 42 |
-
# Use Poe (OpenAI-compatible) client for GPT-5 model
|
| 43 |
-
return OpenAI(
|
| 44 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 45 |
-
base_url="https://api.poe.com/v1"
|
| 46 |
-
)
|
| 47 |
-
elif model_id == "gpt-5.1":
|
| 48 |
-
# Use Poe (OpenAI-compatible) client for GPT-5.1 model
|
| 49 |
-
return OpenAI(
|
| 50 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 51 |
-
base_url="https://api.poe.com/v1"
|
| 52 |
-
)
|
| 53 |
-
elif model_id == "gpt-5.1-instant":
|
| 54 |
-
# Use Poe (OpenAI-compatible) client for GPT-5.1 Instant model
|
| 55 |
-
return OpenAI(
|
| 56 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 57 |
-
base_url="https://api.poe.com/v1"
|
| 58 |
-
)
|
| 59 |
-
elif model_id == "gpt-5.1-codex":
|
| 60 |
-
# Use Poe (OpenAI-compatible) client for GPT-5.1 Codex model
|
| 61 |
-
return OpenAI(
|
| 62 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 63 |
-
base_url="https://api.poe.com/v1"
|
| 64 |
-
)
|
| 65 |
-
elif model_id == "gpt-5.1-codex-mini":
|
| 66 |
-
# Use Poe (OpenAI-compatible) client for GPT-5.1 Codex Mini model
|
| 67 |
-
return OpenAI(
|
| 68 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 69 |
-
base_url="https://api.poe.com/v1"
|
| 70 |
-
)
|
| 71 |
-
elif model_id == "grok-4":
|
| 72 |
-
# Use Poe (OpenAI-compatible) client for Grok-4 model
|
| 73 |
-
return OpenAI(
|
| 74 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 75 |
-
base_url="https://api.poe.com/v1"
|
| 76 |
-
)
|
| 77 |
-
elif model_id == "Grok-Code-Fast-1":
|
| 78 |
-
# Use Poe (OpenAI-compatible) client for Grok-Code-Fast-1 model
|
| 79 |
-
return OpenAI(
|
| 80 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 81 |
-
base_url="https://api.poe.com/v1"
|
| 82 |
-
)
|
| 83 |
-
elif model_id == "claude-opus-4.1":
|
| 84 |
-
# Use Poe (OpenAI-compatible) client for Claude-Opus-4.1
|
| 85 |
-
return OpenAI(
|
| 86 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 87 |
-
base_url="https://api.poe.com/v1"
|
| 88 |
-
)
|
| 89 |
-
elif model_id == "claude-sonnet-4.5":
|
| 90 |
-
# Use Poe (OpenAI-compatible) client for Claude-Sonnet-4.5
|
| 91 |
-
return OpenAI(
|
| 92 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 93 |
-
base_url="https://api.poe.com/v1"
|
| 94 |
-
)
|
| 95 |
-
elif model_id == "claude-haiku-4.5":
|
| 96 |
-
# Use Poe (OpenAI-compatible) client for Claude-Haiku-4.5
|
| 97 |
-
return OpenAI(
|
| 98 |
-
api_key=os.getenv("POE_API_KEY"),
|
| 99 |
-
base_url="https://api.poe.com/v1"
|
| 100 |
-
)
|
| 101 |
-
elif model_id == "qwen3-max-preview":
|
| 102 |
-
# Use DashScope International OpenAI client for Qwen3 Max Preview
|
| 103 |
-
return OpenAI(
|
| 104 |
-
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
| 105 |
-
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
| 106 |
-
)
|
| 107 |
-
elif model_id == "openrouter/sonoma-dusk-alpha":
|
| 108 |
-
# Use OpenRouter client for Sonoma Dusk Alpha model
|
| 109 |
-
return OpenAI(
|
| 110 |
-
api_key=os.getenv("OPENROUTER_API_KEY"),
|
| 111 |
-
base_url="https://openrouter.ai/api/v1",
|
| 112 |
-
)
|
| 113 |
-
elif model_id == "openrouter/sonoma-sky-alpha":
|
| 114 |
-
# Use OpenRouter client for Sonoma Sky Alpha model
|
| 115 |
-
return OpenAI(
|
| 116 |
-
api_key=os.getenv("OPENROUTER_API_KEY"),
|
| 117 |
-
base_url="https://openrouter.ai/api/v1",
|
| 118 |
-
)
|
| 119 |
-
elif model_id == "MiniMaxAI/MiniMax-M2":
|
| 120 |
-
# Use HuggingFace InferenceClient with Novita provider for MiniMax M2 model
|
| 121 |
-
provider = "novita"
|
| 122 |
-
elif model_id == "step-3":
|
| 123 |
-
# Use StepFun API client for Step-3 model
|
| 124 |
-
return OpenAI(
|
| 125 |
-
api_key=os.getenv("STEP_API_KEY"),
|
| 126 |
-
base_url="https://api.stepfun.com/v1"
|
| 127 |
-
)
|
| 128 |
-
elif model_id == "codestral-2508" or model_id == "mistral-medium-2508":
|
| 129 |
-
# Use Mistral client for Mistral models
|
| 130 |
-
return Mistral(api_key=os.getenv("MISTRAL_API_KEY"))
|
| 131 |
-
elif model_id == "gemini-2.5-flash":
|
| 132 |
-
# Use Google Gemini (OpenAI-compatible) client
|
| 133 |
-
return OpenAI(
|
| 134 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 135 |
-
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 136 |
-
)
|
| 137 |
-
elif model_id == "gemini-2.5-pro":
|
| 138 |
-
# Use Google Gemini Pro (OpenAI-compatible) client
|
| 139 |
-
return OpenAI(
|
| 140 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 141 |
-
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 142 |
-
)
|
| 143 |
-
elif model_id == "gemini-flash-latest":
|
| 144 |
-
# Use Google Gemini Flash Latest (OpenAI-compatible) client
|
| 145 |
-
return OpenAI(
|
| 146 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 147 |
-
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 148 |
-
)
|
| 149 |
-
elif model_id == "gemini-flash-lite-latest":
|
| 150 |
-
# Use Google Gemini Flash Lite Latest (OpenAI-compatible) client
|
| 151 |
-
return OpenAI(
|
| 152 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 153 |
-
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 154 |
-
)
|
| 155 |
-
elif model_id == "kimi-k2-turbo-preview":
|
| 156 |
-
# Use Moonshot AI (OpenAI-compatible) client for Kimi K2 Turbo (Preview)
|
| 157 |
-
return OpenAI(
|
| 158 |
-
api_key=os.getenv("MOONSHOT_API_KEY"),
|
| 159 |
-
base_url="https://api.moonshot.ai/v1",
|
| 160 |
-
)
|
| 161 |
-
elif model_id == "moonshotai/Kimi-K2-Thinking":
|
| 162 |
-
# Use HuggingFace InferenceClient with Novita provider for Kimi K2 Thinking
|
| 163 |
-
provider = "novita"
|
| 164 |
-
elif model_id == "stealth-model-1":
|
| 165 |
-
# Use stealth model with generic configuration
|
| 166 |
-
api_key = os.getenv("STEALTH_MODEL_1_API_KEY")
|
| 167 |
-
if not api_key:
|
| 168 |
-
raise ValueError("STEALTH_MODEL_1_API_KEY environment variable is required for Carrot model")
|
| 169 |
-
|
| 170 |
-
base_url = os.getenv("STEALTH_MODEL_1_BASE_URL")
|
| 171 |
-
if not base_url:
|
| 172 |
-
raise ValueError("STEALTH_MODEL_1_BASE_URL environment variable is required for Carrot model")
|
| 173 |
-
|
| 174 |
-
return OpenAI(
|
| 175 |
-
api_key=api_key,
|
| 176 |
-
base_url=base_url,
|
| 177 |
-
)
|
| 178 |
-
elif model_id == "moonshotai/Kimi-K2-Instruct":
|
| 179 |
-
provider = "groq"
|
| 180 |
-
elif model_id == "deepseek-ai/DeepSeek-V3.1":
|
| 181 |
-
provider = "novita"
|
| 182 |
-
elif model_id == "deepseek-ai/DeepSeek-V3.1-Terminus":
|
| 183 |
-
provider = "novita"
|
| 184 |
-
elif model_id == "deepseek-ai/DeepSeek-V3.2-Exp":
|
| 185 |
-
provider = "novita"
|
| 186 |
-
elif model_id == "zai-org/GLM-4.5":
|
| 187 |
-
provider = "fireworks-ai"
|
| 188 |
-
elif model_id == "zai-org/GLM-4.6":
|
| 189 |
-
# Use auto provider for GLM-4.6, HuggingFace will select best available
|
| 190 |
-
provider = "auto"
|
| 191 |
-
return InferenceClient(
|
| 192 |
-
provider=provider,
|
| 193 |
-
api_key=HF_TOKEN,
|
| 194 |
-
bill_to="huggingface"
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
# Helper function to get real model ID for stealth models and special cases
|
| 198 |
-
def get_real_model_id(model_id: str) -> str:
|
| 199 |
-
"""Get the real model ID, checking environment variables for stealth models and handling special model formats"""
|
| 200 |
-
if model_id == "stealth-model-1":
|
| 201 |
-
# Get the real model ID from environment variable
|
| 202 |
-
real_model_id = os.getenv("STEALTH_MODEL_1_ID")
|
| 203 |
-
if not real_model_id:
|
| 204 |
-
raise ValueError("STEALTH_MODEL_1_ID environment variable is required for Carrot model")
|
| 205 |
-
|
| 206 |
-
return real_model_id
|
| 207 |
-
elif model_id == "zai-org/GLM-4.6":
|
| 208 |
-
# GLM-4.6 requires provider suffix in model string for API calls
|
| 209 |
-
return "zai-org/GLM-4.6:zai-org"
|
| 210 |
-
return model_id
|
| 211 |
-
|
| 212 |
-
# Type definitions
|
| 213 |
-
History = List[Tuple[str, str]]
|
| 214 |
-
Messages = List[Dict[str, str]]
|
| 215 |
-
|
| 216 |
-
def history_to_messages(history: History, system: str) -> Messages:
|
| 217 |
-
messages = [{'role': 'system', 'content': system}]
|
| 218 |
-
for h in history:
|
| 219 |
-
# Handle multimodal content in history
|
| 220 |
-
user_content = h[0]
|
| 221 |
-
if isinstance(user_content, list):
|
| 222 |
-
# Extract text from multimodal content
|
| 223 |
-
text_content = ""
|
| 224 |
-
for item in user_content:
|
| 225 |
-
if isinstance(item, dict) and item.get("type") == "text":
|
| 226 |
-
text_content += item.get("text", "")
|
| 227 |
-
user_content = text_content if text_content else str(user_content)
|
| 228 |
-
|
| 229 |
-
messages.append({'role': 'user', 'content': user_content})
|
| 230 |
-
messages.append({'role': 'assistant', 'content': h[1]})
|
| 231 |
-
return messages
|
| 232 |
-
|
| 233 |
-
def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
|
| 234 |
-
"""Convert history tuples to chatbot message format"""
|
| 235 |
-
messages = []
|
| 236 |
-
for user_msg, assistant_msg in history:
|
| 237 |
-
# Handle multimodal content
|
| 238 |
-
if isinstance(user_msg, list):
|
| 239 |
-
text_content = ""
|
| 240 |
-
for item in user_msg:
|
| 241 |
-
if isinstance(item, dict) and item.get("type") == "text":
|
| 242 |
-
text_content += item.get("text", "")
|
| 243 |
-
user_msg = text_content if text_content else str(user_msg)
|
| 244 |
-
|
| 245 |
-
messages.append({"role": "user", "content": user_msg})
|
| 246 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
| 247 |
-
return messages
|
| 248 |
-
|
| 249 |
-
def strip_tool_call_markers(text):
|
| 250 |
-
"""Remove TOOL_CALL markers that some LLMs (like Qwen) add to their output."""
|
| 251 |
-
if not text:
|
| 252 |
-
return text
|
| 253 |
-
# Remove [TOOL_CALL] and [/TOOL_CALL] markers
|
| 254 |
-
text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE)
|
| 255 |
-
# Remove standalone }} that appears with tool calls
|
| 256 |
-
# Only remove if it's on its own line or at the end
|
| 257 |
-
text = re.sub(r'^\s*\}\}\s*$', '', text, flags=re.MULTILINE)
|
| 258 |
-
return text.strip()
|
| 259 |
-
|
| 260 |
-
def remove_code_block(text):
|
| 261 |
-
# First strip any tool call markers
|
| 262 |
-
text = strip_tool_call_markers(text)
|
| 263 |
-
|
| 264 |
-
# Try to match code blocks with language markers
|
| 265 |
-
patterns = [
|
| 266 |
-
r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML
|
| 267 |
-
r'```\n([\s\S]+?)\n```', # Match code blocks without language markers
|
| 268 |
-
r'```([\s\S]+?)```' # Match code blocks without line breaks
|
| 269 |
-
]
|
| 270 |
-
for pattern in patterns:
|
| 271 |
-
match = re.search(pattern, text, re.DOTALL)
|
| 272 |
-
if match:
|
| 273 |
-
extracted = match.group(1).strip()
|
| 274 |
-
# Remove a leading language marker line (e.g., 'python') if present
|
| 275 |
-
if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
|
| 276 |
-
return extracted.split('\n', 1)[1] if '\n' in extracted else ''
|
| 277 |
-
# If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root
|
| 278 |
-
html_root_idx = None
|
| 279 |
-
for tag in ['<!DOCTYPE html', '<html']:
|
| 280 |
-
idx = extracted.find(tag)
|
| 281 |
-
if idx != -1:
|
| 282 |
-
html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx)
|
| 283 |
-
if html_root_idx is not None and html_root_idx > 0:
|
| 284 |
-
return extracted[html_root_idx:].strip()
|
| 285 |
-
return extracted
|
| 286 |
-
# If no code block is found, check if the entire text is HTML
|
| 287 |
-
stripped = text.strip()
|
| 288 |
-
if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'):
|
| 289 |
-
# If HTML root appears later (e.g., Poe preface), trim to first HTML root
|
| 290 |
-
for tag in ['<!DOCTYPE html', '<html']:
|
| 291 |
-
idx = stripped.find(tag)
|
| 292 |
-
if idx > 0:
|
| 293 |
-
return stripped[idx:].strip()
|
| 294 |
-
return stripped
|
| 295 |
-
# Special handling for python: remove python marker
|
| 296 |
-
if text.strip().startswith('```python'):
|
| 297 |
-
return text.strip()[9:-3].strip()
|
| 298 |
-
# Remove a leading language marker line if present (fallback)
|
| 299 |
-
lines = text.strip().split('\n', 1)
|
| 300 |
-
if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
|
| 301 |
-
return lines[1] if len(lines) > 1 else ''
|
| 302 |
-
return text.strip()
|
| 303 |
-
|
| 304 |
-
## React CDN compatibility fixer removed per user preference
|
| 305 |
-
|
| 306 |
-
def strip_thinking_tags(text: str) -> str:
|
| 307 |
-
"""Strip <think> tags and [TOOL_CALL] markers from streaming output."""
|
| 308 |
-
if not text:
|
| 309 |
-
return text
|
| 310 |
-
# Remove <think> opening tags
|
| 311 |
-
text = re.sub(r'<think>', '', text, flags=re.IGNORECASE)
|
| 312 |
-
# Remove </think> closing tags
|
| 313 |
-
text = re.sub(r'</think>', '', text, flags=re.IGNORECASE)
|
| 314 |
-
# Remove [TOOL_CALL] markers
|
| 315 |
-
text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE)
|
| 316 |
-
return text
|
| 317 |
-
|
| 318 |
-
def strip_placeholder_thinking(text: str) -> str:
|
| 319 |
-
"""Remove placeholder 'Thinking...' status lines from streamed text."""
|
| 320 |
-
if not text:
|
| 321 |
-
return text
|
| 322 |
-
# Matches lines like: "Thinking..." or "Thinking... (12s elapsed)"
|
| 323 |
-
return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
|
| 324 |
-
|
| 325 |
-
def is_placeholder_thinking_only(text: str) -> bool:
|
| 326 |
-
"""Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed)."""
|
| 327 |
-
if not text:
|
| 328 |
-
return False
|
| 329 |
-
stripped = text.strip()
|
| 330 |
-
if not stripped:
|
| 331 |
-
return False
|
| 332 |
-
return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
|
| 333 |
-
|
| 334 |
-
def extract_last_thinking_line(text: str) -> str:
|
| 335 |
-
"""Extract the last 'Thinking...' line to display as status."""
|
| 336 |
-
matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text))
|
| 337 |
-
return matches[-1].group(0) if matches else "Thinking..."
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/parsers.py
DELETED
|
@@ -1,1111 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Code parsing and formatting utilities for different frameworks.
|
| 3 |
-
Handles parsing of transformers.js, React, multi-file HTML, Streamlit, and Gradio code.
|
| 4 |
-
"""
|
| 5 |
-
import re
|
| 6 |
-
import os
|
| 7 |
-
import json
|
| 8 |
-
import base64
|
| 9 |
-
from typing import Dict, List, Optional, Tuple
|
| 10 |
-
from bs4 import BeautifulSoup
|
| 11 |
-
import html
|
| 12 |
-
|
| 13 |
-
from .config import SEARCH_START, DIVIDER, REPLACE_END
|
| 14 |
-
|
| 15 |
-
# Type definitions
|
| 16 |
-
History = List[Dict[str, str]]
|
| 17 |
-
|
| 18 |
-
def strip_tool_call_markers(text):
|
| 19 |
-
"""Remove TOOL_CALL markers and thinking tags that some LLMs add to their output."""
|
| 20 |
-
if not text:
|
| 21 |
-
return text
|
| 22 |
-
# Remove [TOOL_CALL] and [/TOOL_CALL] markers
|
| 23 |
-
text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE)
|
| 24 |
-
# Remove <think> and </think> tags and their content
|
| 25 |
-
text = re.sub(r'<think>[\s\S]*?</think>', '', text, flags=re.IGNORECASE)
|
| 26 |
-
# Remove any remaining unclosed <think> tags at the start
|
| 27 |
-
text = re.sub(r'^<think>[\s\S]*?(?=\n|$)', '', text, flags=re.IGNORECASE | re.MULTILINE)
|
| 28 |
-
# Remove any remaining </think> tags
|
| 29 |
-
text = re.sub(r'</think>', '', text, flags=re.IGNORECASE)
|
| 30 |
-
# Remove standalone }} that appears with tool calls
|
| 31 |
-
# Only remove if it's on its own line or at the end
|
| 32 |
-
text = re.sub(r'^\s*\}\}\s*$', '', text, flags=re.MULTILINE)
|
| 33 |
-
return text.strip()
|
| 34 |
-
|
| 35 |
-
def remove_code_block(text):
|
| 36 |
-
# First strip any tool call markers
|
| 37 |
-
text = strip_tool_call_markers(text)
|
| 38 |
-
|
| 39 |
-
# Try to match code blocks with language markers
|
| 40 |
-
patterns = [
|
| 41 |
-
r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML
|
| 42 |
-
r'```\n([\s\S]+?)\n```', # Match code blocks without language markers
|
| 43 |
-
r'```([\s\S]+?)```' # Match code blocks without line breaks
|
| 44 |
-
]
|
| 45 |
-
for pattern in patterns:
|
| 46 |
-
match = re.search(pattern, text, re.DOTALL)
|
| 47 |
-
if match:
|
| 48 |
-
extracted = match.group(1).strip()
|
| 49 |
-
# Remove a leading language marker line (e.g., 'python') if present
|
| 50 |
-
if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
|
| 51 |
-
return extracted.split('\n', 1)[1] if '\n' in extracted else ''
|
| 52 |
-
# If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root
|
| 53 |
-
html_root_idx = None
|
| 54 |
-
for tag in ['<!DOCTYPE html', '<html']:
|
| 55 |
-
idx = extracted.find(tag)
|
| 56 |
-
if idx != -1:
|
| 57 |
-
html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx)
|
| 58 |
-
if html_root_idx is not None and html_root_idx > 0:
|
| 59 |
-
return extracted[html_root_idx:].strip()
|
| 60 |
-
return extracted
|
| 61 |
-
# If no code block is found, check if the entire text is HTML
|
| 62 |
-
stripped = text.strip()
|
| 63 |
-
if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'):
|
| 64 |
-
# If HTML root appears later (e.g., Poe preface), trim to first HTML root
|
| 65 |
-
for tag in ['<!DOCTYPE html', '<html']:
|
| 66 |
-
idx = stripped.find(tag)
|
| 67 |
-
if idx > 0:
|
| 68 |
-
return stripped[idx:].strip()
|
| 69 |
-
return stripped
|
| 70 |
-
# Special handling for python: remove python marker
|
| 71 |
-
if text.strip().startswith('```python'):
|
| 72 |
-
return text.strip()[9:-3].strip()
|
| 73 |
-
# Remove a leading language marker line if present (fallback)
|
| 74 |
-
lines = text.strip().split('\n', 1)
|
| 75 |
-
if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
|
| 76 |
-
return lines[1] if len(lines) > 1 else ''
|
| 77 |
-
return text.strip()
|
| 78 |
-
|
| 79 |
-
## React CDN compatibility fixer removed per user preference
|
| 80 |
-
|
| 81 |
-
def strip_placeholder_thinking(text: str) -> str:
|
| 82 |
-
"""Remove placeholder 'Thinking...' status lines from streamed text."""
|
| 83 |
-
if not text:
|
| 84 |
-
return text
|
| 85 |
-
# Matches lines like: "Thinking..." or "Thinking... (12s elapsed)"
|
| 86 |
-
return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
|
| 87 |
-
|
| 88 |
-
def is_placeholder_thinking_only(text: str) -> bool:
|
| 89 |
-
"""Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed)."""
|
| 90 |
-
if not text:
|
| 91 |
-
return False
|
| 92 |
-
stripped = text.strip()
|
| 93 |
-
if not stripped:
|
| 94 |
-
return False
|
| 95 |
-
return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
|
| 96 |
-
|
| 97 |
-
def extract_last_thinking_line(text: str) -> str:
|
| 98 |
-
"""Extract the last 'Thinking...' line to display as status."""
|
| 99 |
-
matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text))
|
| 100 |
-
return matches[-1].group(0) if matches else "Thinking..."
|
| 101 |
-
|
| 102 |
-
def parse_transformers_js_output(text):
|
| 103 |
-
"""Parse transformers.js output and extract the three files (index.html, index.js, style.css)"""
|
| 104 |
-
files = {
|
| 105 |
-
'index.html': '',
|
| 106 |
-
'index.js': '',
|
| 107 |
-
'style.css': ''
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
# Multiple patterns to match the three code blocks with different variations
|
| 111 |
-
html_patterns = [
|
| 112 |
-
r'```html\s*\n([\s\S]*?)(?:```|\Z)',
|
| 113 |
-
r'```htm\s*\n([\s\S]*?)(?:```|\Z)',
|
| 114 |
-
r'```\s*(?:index\.html|html)\s*\n([\s\S]*?)(?:```|\Z)'
|
| 115 |
-
]
|
| 116 |
-
|
| 117 |
-
js_patterns = [
|
| 118 |
-
r'```javascript\s*\n([\s\S]*?)(?:```|\Z)',
|
| 119 |
-
r'```js\s*\n([\s\S]*?)(?:```|\Z)',
|
| 120 |
-
r'```\s*(?:index\.js|javascript|js)\s*\n([\s\S]*?)(?:```|\Z)'
|
| 121 |
-
]
|
| 122 |
-
|
| 123 |
-
css_patterns = [
|
| 124 |
-
r'```css\s*\n([\s\S]*?)(?:```|\Z)',
|
| 125 |
-
r'```\s*(?:style\.css|css)\s*\n([\s\S]*?)(?:```|\Z)'
|
| 126 |
-
]
|
| 127 |
-
|
| 128 |
-
# Extract HTML content
|
| 129 |
-
for pattern in html_patterns:
|
| 130 |
-
html_match = re.search(pattern, text, re.IGNORECASE)
|
| 131 |
-
if html_match:
|
| 132 |
-
files['index.html'] = html_match.group(1).strip()
|
| 133 |
-
break
|
| 134 |
-
|
| 135 |
-
# Extract JavaScript content
|
| 136 |
-
for pattern in js_patterns:
|
| 137 |
-
js_match = re.search(pattern, text, re.IGNORECASE)
|
| 138 |
-
if js_match:
|
| 139 |
-
files['index.js'] = js_match.group(1).strip()
|
| 140 |
-
break
|
| 141 |
-
|
| 142 |
-
# Extract CSS content
|
| 143 |
-
for pattern in css_patterns:
|
| 144 |
-
css_match = re.search(pattern, text, re.IGNORECASE)
|
| 145 |
-
if css_match:
|
| 146 |
-
files['style.css'] = css_match.group(1).strip()
|
| 147 |
-
break
|
| 148 |
-
|
| 149 |
-
# Fallback: support === index.html === format if any file is missing
|
| 150 |
-
if not (files['index.html'] and files['index.js'] and files['style.css']):
|
| 151 |
-
# Use regex to extract sections
|
| 152 |
-
html_fallback = re.search(r'===\s*index\.html\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
|
| 153 |
-
js_fallback = re.search(r'===\s*index\.js\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
|
| 154 |
-
css_fallback = re.search(r'===\s*style\.css\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
|
| 155 |
-
|
| 156 |
-
if html_fallback:
|
| 157 |
-
files['index.html'] = html_fallback.group(1).strip()
|
| 158 |
-
if js_fallback:
|
| 159 |
-
files['index.js'] = js_fallback.group(1).strip()
|
| 160 |
-
if css_fallback:
|
| 161 |
-
files['style.css'] = css_fallback.group(1).strip()
|
| 162 |
-
|
| 163 |
-
# Additional fallback: extract from numbered sections or file headers
|
| 164 |
-
if not (files['index.html'] and files['index.js'] and files['style.css']):
|
| 165 |
-
# Try patterns like "1. index.html:" or "**index.html**"
|
| 166 |
-
patterns = [
|
| 167 |
-
(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.html(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.html'),
|
| 168 |
-
(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.js(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.js'),
|
| 169 |
-
(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)style\.css(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'style.css')
|
| 170 |
-
]
|
| 171 |
-
|
| 172 |
-
for pattern, file_key in patterns:
|
| 173 |
-
if not files[file_key]:
|
| 174 |
-
match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
|
| 175 |
-
if match:
|
| 176 |
-
# Clean up the content by removing any code block markers
|
| 177 |
-
content = match.group(1).strip()
|
| 178 |
-
content = re.sub(r'^```\w*\s*\n', '', content)
|
| 179 |
-
content = re.sub(r'\n```\s*$', '', content)
|
| 180 |
-
files[file_key] = content.strip()
|
| 181 |
-
|
| 182 |
-
return files
|
| 183 |
-
|
| 184 |
-
def format_transformers_js_output(files):
|
| 185 |
-
"""Format the three files into a single display string"""
|
| 186 |
-
output = []
|
| 187 |
-
output.append("=== index.html ===")
|
| 188 |
-
output.append(files['index.html'])
|
| 189 |
-
output.append("\n=== index.js ===")
|
| 190 |
-
output.append(files['index.js'])
|
| 191 |
-
output.append("\n=== style.css ===")
|
| 192 |
-
output.append(files['style.css'])
|
| 193 |
-
return '\n'.join(output)
|
| 194 |
-
|
| 195 |
-
def build_transformers_inline_html(files: dict) -> str:
|
| 196 |
-
"""Merge transformers.js three-file output into a single self-contained HTML document.
|
| 197 |
-
|
| 198 |
-
- Inlines style.css into a <style> tag
|
| 199 |
-
- Inlines index.js into a <script type="module"> tag
|
| 200 |
-
- Rewrites ESM imports for transformers.js to a stable CDN URL so it works in data: iframes
|
| 201 |
-
"""
|
| 202 |
-
import re as _re
|
| 203 |
-
|
| 204 |
-
html = files.get('index.html') or ''
|
| 205 |
-
js = files.get('index.js') or ''
|
| 206 |
-
css = files.get('style.css') or ''
|
| 207 |
-
|
| 208 |
-
# Normalize JS imports to CDN (handle both @huggingface/transformers and legacy @xenova/transformers)
|
| 209 |
-
cdn_url = "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]"
|
| 210 |
-
|
| 211 |
-
def _normalize_imports(_code: str) -> str:
|
| 212 |
-
if not _code:
|
| 213 |
-
return _code or ""
|
| 214 |
-
_code = _re.sub(r"from\s+['\"]@huggingface/transformers['\"]", f"from '{cdn_url}'", _code)
|
| 215 |
-
_code = _re.sub(r"from\s+['\"]@xenova/transformers['\"]", f"from '{cdn_url}'", _code)
|
| 216 |
-
_code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@huggingface/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code)
|
| 217 |
-
_code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@xenova/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code)
|
| 218 |
-
return _code
|
| 219 |
-
|
| 220 |
-
# Extract inline module scripts from index.html, then merge into JS so we control imports
|
| 221 |
-
inline_modules = []
|
| 222 |
-
try:
|
| 223 |
-
for _m in _re.finditer(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>([\s\S]*?)</script>", html, flags=_re.IGNORECASE):
|
| 224 |
-
inline_modules.append(_m.group(1))
|
| 225 |
-
if inline_modules:
|
| 226 |
-
html = _re.sub(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>[\s\S]*?</script>\\s*", "", html, flags=_re.IGNORECASE)
|
| 227 |
-
# Normalize any external module script URLs that load transformers to a single CDN version (keep the tag)
|
| 228 |
-
html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@huggingface/transformers@[^'\"<>\s]+", cdn_url, html)
|
| 229 |
-
html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@xenova/transformers@[^'\"<>\s]+", cdn_url, html)
|
| 230 |
-
except Exception:
|
| 231 |
-
# Best-effort; continue
|
| 232 |
-
pass
|
| 233 |
-
|
| 234 |
-
# Merge inline module code with provided index.js, then normalize imports
|
| 235 |
-
combined_js_parts = []
|
| 236 |
-
if inline_modules:
|
| 237 |
-
combined_js_parts.append("\n\n".join(inline_modules))
|
| 238 |
-
if js:
|
| 239 |
-
combined_js_parts.append(js)
|
| 240 |
-
js = "\n\n".join([p for p in combined_js_parts if (p and p.strip())])
|
| 241 |
-
js = _normalize_imports(js)
|
| 242 |
-
|
| 243 |
-
# Prepend a small prelude to reduce persistent caching during preview
|
| 244 |
-
# Also ensure a global `transformers` namespace exists for apps relying on it
|
| 245 |
-
# Note: importing env alongside user's own imports is fine in ESM
|
| 246 |
-
if js.strip():
|
| 247 |
-
prelude = (
|
| 248 |
-
f"import {{ env }} from '{cdn_url}';\n"
|
| 249 |
-
"try { env.useBrowserCache = false; } catch (e) {}\n"
|
| 250 |
-
"try { if (env && env.backends && env.backends.onnx && env.backends.onnx.wasm) { env.backends.onnx.wasm.numThreads = 1; env.backends.onnx.wasm.proxy = false; } } catch (e) {}\n"
|
| 251 |
-
f"(async () => {{ try {{ if (typeof globalThis.transformers === 'undefined') {{ const m = await import('{cdn_url}'); globalThis.transformers = m; }} }} catch (e) {{}} }})();\n"
|
| 252 |
-
)
|
| 253 |
-
js = prelude + js
|
| 254 |
-
|
| 255 |
-
# If index.html missing or doesn't look like a full document, create a minimal shell
|
| 256 |
-
doc = html.strip()
|
| 257 |
-
if not doc or ('<html' not in doc.lower()):
|
| 258 |
-
doc = (
|
| 259 |
-
"<!DOCTYPE html>\n"
|
| 260 |
-
"<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Transformers.js App</title>\n</head>\n"
|
| 261 |
-
"<body>\n<div id=\"app\"></div>\n</body>\n</html>"
|
| 262 |
-
)
|
| 263 |
-
|
| 264 |
-
# Remove local references to style.css and index.js to avoid duplicates when inlining
|
| 265 |
-
doc = _re.sub(r"<link[^>]+href=\"[^\"]*style\.css\"[^>]*>\s*", "", doc, flags=_re.IGNORECASE)
|
| 266 |
-
doc = _re.sub(r"<script[^>]+src=\"[^\"]*index\.js\"[^>]*>\s*</script>\s*", "", doc, flags=_re.IGNORECASE)
|
| 267 |
-
|
| 268 |
-
# Inline CSS: insert before </head> or create a <head>
|
| 269 |
-
style_tag = f"<style>\n{css}\n</style>" if css else ""
|
| 270 |
-
if style_tag:
|
| 271 |
-
if '</head>' in doc.lower():
|
| 272 |
-
# Preserve original casing by finding closing head case-insensitively
|
| 273 |
-
match = _re.search(r"</head>", doc, flags=_re.IGNORECASE)
|
| 274 |
-
if match:
|
| 275 |
-
idx = match.start()
|
| 276 |
-
doc = doc[:idx] + style_tag + doc[idx:]
|
| 277 |
-
else:
|
| 278 |
-
# No head; insert at top of body
|
| 279 |
-
match = _re.search(r"<body[^>]*>", doc, flags=_re.IGNORECASE)
|
| 280 |
-
if match:
|
| 281 |
-
idx = match.end()
|
| 282 |
-
doc = doc[:idx] + "\n" + style_tag + doc[idx:]
|
| 283 |
-
else:
|
| 284 |
-
# Append at beginning
|
| 285 |
-
doc = style_tag + doc
|
| 286 |
-
|
| 287 |
-
# Inline JS: insert before </body>
|
| 288 |
-
script_tag = f"<script type=\"module\">\n{js}\n</script>" if js else ""
|
| 289 |
-
# Lightweight debug console overlay to surface runtime errors inside the iframe
|
| 290 |
-
debug_overlay = (
|
| 291 |
-
"<style>\n"
|
| 292 |
-
"#anycoder-debug{position:fixed;left:0;right:0;bottom:0;max-height:45%;overflow:auto;"
|
| 293 |
-
"background:rgba(0,0,0,.85);color:#9eff9e;padding:.5em;font:12px/1.4 monospace;z-index:2147483647;display:none}"
|
| 294 |
-
"#anycoder-debug pre{margin:0;white-space:pre-wrap;word-break:break-word}"
|
| 295 |
-
"</style>\n"
|
| 296 |
-
"<div id=\"anycoder-debug\"></div>\n"
|
| 297 |
-
"<script>\n"
|
| 298 |
-
"(function(){\n"
|
| 299 |
-
" const el = document.getElementById('anycoder-debug');\n"
|
| 300 |
-
" function show(){ if(el && el.style.display!=='block'){ el.style.display='block'; } }\n"
|
| 301 |
-
" function log(msg){ try{ show(); const pre=document.createElement('pre'); pre.textContent=msg; el.appendChild(pre);}catch(e){} }\n"
|
| 302 |
-
" const origError = console.error.bind(console);\n"
|
| 303 |
-
" console.error = function(){ origError.apply(console, arguments); try{ log('console.error: ' + Array.from(arguments).map(a=>{try{return (typeof a==='string')?a:JSON.stringify(a);}catch(e){return String(a);}}).join(' ')); }catch(e){} };\n"
|
| 304 |
-
" window.addEventListener('error', e => { log('window.onerror: ' + (e && e.message ? e.message : 'Unknown error')); });\n"
|
| 305 |
-
" window.addEventListener('unhandledrejection', e => { try{ const r=e && e.reason; log('unhandledrejection: ' + (r && (r.message || JSON.stringify(r)))); }catch(err){ log('unhandledrejection'); } });\n"
|
| 306 |
-
"})();\n"
|
| 307 |
-
"</script>"
|
| 308 |
-
)
|
| 309 |
-
# Cleanup script to clear Cache Storage and IndexedDB on unload to free model weights
|
| 310 |
-
cleanup_tag = (
|
| 311 |
-
"<script>\n"
|
| 312 |
-
"(function(){\n"
|
| 313 |
-
" function cleanup(){\n"
|
| 314 |
-
" try { if (window.caches && caches.keys) { caches.keys().then(keys => keys.forEach(k => caches.delete(k))); } } catch(e){}\n"
|
| 315 |
-
" try { if (window.indexedDB && indexedDB.databases) { indexedDB.databases().then(dbs => dbs.forEach(db => db && db.name && indexedDB.deleteDatabase(db.name))); } } catch(e){}\n"
|
| 316 |
-
" }\n"
|
| 317 |
-
" window.addEventListener('pagehide', cleanup, { once: true });\n"
|
| 318 |
-
" window.addEventListener('beforeunload', cleanup, { once: true });\n"
|
| 319 |
-
"})();\n"
|
| 320 |
-
"</script>"
|
| 321 |
-
)
|
| 322 |
-
if script_tag:
|
| 323 |
-
match = _re.search(r"</body>", doc, flags=_re.IGNORECASE)
|
| 324 |
-
if match:
|
| 325 |
-
idx = match.start()
|
| 326 |
-
doc = doc[:idx] + debug_overlay + script_tag + cleanup_tag + doc[idx:]
|
| 327 |
-
else:
|
| 328 |
-
# Append at end
|
| 329 |
-
doc = doc + debug_overlay + script_tag + cleanup_tag
|
| 330 |
-
|
| 331 |
-
return doc
|
| 332 |
-
|
| 333 |
-
def send_transformers_to_sandbox(files: dict) -> str:
|
| 334 |
-
"""Build a self-contained HTML document from transformers.js files and return an iframe preview."""
|
| 335 |
-
merged_html = build_transformers_inline_html(files)
|
| 336 |
-
return send_to_sandbox(merged_html)
|
| 337 |
-
|
| 338 |
-
def parse_multipage_html_output(text: str) -> Dict[str, str]:
|
| 339 |
-
"""Parse multi-page HTML output formatted as repeated "=== filename ===" sections.
|
| 340 |
-
|
| 341 |
-
Returns a mapping of filename → file content. Supports nested paths like assets/css/styles.css.
|
| 342 |
-
If HTML content appears before the first === marker, it's treated as index.html.
|
| 343 |
-
"""
|
| 344 |
-
if not text:
|
| 345 |
-
return {}
|
| 346 |
-
# First, strip any markdown fences
|
| 347 |
-
cleaned = remove_code_block(text)
|
| 348 |
-
files: Dict[str, str] = {}
|
| 349 |
-
import re as _re
|
| 350 |
-
|
| 351 |
-
# Check if there's content before the first === marker
|
| 352 |
-
first_marker_match = _re.search(r"^===\s*([^=\n]+?)\s*===", cleaned, _re.MULTILINE)
|
| 353 |
-
if first_marker_match:
|
| 354 |
-
# There's content before the first marker
|
| 355 |
-
first_marker_pos = first_marker_match.start()
|
| 356 |
-
if first_marker_pos > 0:
|
| 357 |
-
leading_content = cleaned[:first_marker_pos].strip()
|
| 358 |
-
# Check if it looks like HTML content
|
| 359 |
-
if leading_content and ('<!DOCTYPE' in leading_content or '<html' in leading_content or leading_content.startswith('<')):
|
| 360 |
-
files['index.html'] = leading_content
|
| 361 |
-
|
| 362 |
-
# Now parse the rest with === markers
|
| 363 |
-
remaining_text = cleaned[first_marker_pos:] if first_marker_pos > 0 else cleaned
|
| 364 |
-
pattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE)
|
| 365 |
-
for m in pattern.finditer(remaining_text):
|
| 366 |
-
name = m.group(1).strip()
|
| 367 |
-
content = m.group(2).strip()
|
| 368 |
-
# Remove accidental trailing fences if present
|
| 369 |
-
content = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content)
|
| 370 |
-
files[name] = content
|
| 371 |
-
else:
|
| 372 |
-
# No === markers found, try standard pattern matching
|
| 373 |
-
pattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE)
|
| 374 |
-
for m in pattern.finditer(cleaned):
|
| 375 |
-
name = m.group(1).strip()
|
| 376 |
-
content = m.group(2).strip()
|
| 377 |
-
# Remove accidental trailing fences if present
|
| 378 |
-
content = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content)
|
| 379 |
-
files[name] = content
|
| 380 |
-
|
| 381 |
-
return files
|
| 382 |
-
|
| 383 |
-
def format_multipage_output(files: Dict[str, str]) -> str:
|
| 384 |
-
"""Format a dict of files back into === filename === sections.
|
| 385 |
-
|
| 386 |
-
Ensures `index.html` appears first if present; others follow sorted by path.
|
| 387 |
-
"""
|
| 388 |
-
if not isinstance(files, dict) or not files:
|
| 389 |
-
return ""
|
| 390 |
-
ordered_paths = []
|
| 391 |
-
if 'index.html' in files:
|
| 392 |
-
ordered_paths.append('index.html')
|
| 393 |
-
for path in sorted(files.keys()):
|
| 394 |
-
if path == 'index.html':
|
| 395 |
-
continue
|
| 396 |
-
ordered_paths.append(path)
|
| 397 |
-
parts: list[str] = []
|
| 398 |
-
for path in ordered_paths:
|
| 399 |
-
parts.append(f"=== {path} ===")
|
| 400 |
-
# Avoid trailing extra newlines to keep blocks compact
|
| 401 |
-
parts.append((files.get(path) or '').rstrip())
|
| 402 |
-
return "\n".join(parts)
|
| 403 |
-
|
| 404 |
-
def validate_and_autofix_files(files: Dict[str, str]) -> Dict[str, str]:
|
| 405 |
-
"""Ensure minimal contract for multi-file sites; auto-fix missing pieces.
|
| 406 |
-
|
| 407 |
-
Rules:
|
| 408 |
-
- Ensure at least one HTML entrypoint (index.html). If none, synthesize a simple index.html linking discovered pages.
|
| 409 |
-
- For each HTML file, ensure referenced local assets exist in files; if missing, add minimal stubs.
|
| 410 |
-
- Normalize relative paths (strip leading '/').
|
| 411 |
-
"""
|
| 412 |
-
if not isinstance(files, dict) or not files:
|
| 413 |
-
return files or {}
|
| 414 |
-
import re as _re
|
| 415 |
-
|
| 416 |
-
normalized: Dict[str, str] = {}
|
| 417 |
-
for k, v in files.items():
|
| 418 |
-
safe_key = k.strip().lstrip('/')
|
| 419 |
-
normalized[safe_key] = v
|
| 420 |
-
|
| 421 |
-
html_files = [p for p in normalized.keys() if p.lower().endswith('.html')]
|
| 422 |
-
has_index = 'index.html' in normalized
|
| 423 |
-
|
| 424 |
-
# If no index.html but some HTML pages exist, create a simple hub index linking to them
|
| 425 |
-
if not has_index and html_files:
|
| 426 |
-
links = '\n'.join([f"<li><a href=\"{p}\">{p}</a></li>" for p in html_files])
|
| 427 |
-
normalized['index.html'] = (
|
| 428 |
-
"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n"
|
| 429 |
-
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n"
|
| 430 |
-
"<title>Site Index</title>\n</head>\n<body>\n<h1>Site</h1>\n<ul>\n"
|
| 431 |
-
+ links + "\n</ul>\n</body>\n</html>"
|
| 432 |
-
)
|
| 433 |
-
|
| 434 |
-
# Collect references from HTML files
|
| 435 |
-
asset_refs: set[str] = set()
|
| 436 |
-
link_href = _re.compile(r"<link[^>]+href=\"([^\"]+)\"")
|
| 437 |
-
script_src = _re.compile(r"<script[^>]+src=\"([^\"]+)\"")
|
| 438 |
-
img_src = _re.compile(r"<img[^>]+src=\"([^\"]+)\"")
|
| 439 |
-
a_href = _re.compile(r"<a[^>]+href=\"([^\"]+)\"")
|
| 440 |
-
|
| 441 |
-
for path, content in list(normalized.items()):
|
| 442 |
-
if not path.lower().endswith('.html'):
|
| 443 |
-
continue
|
| 444 |
-
for patt in (link_href, script_src, img_src, a_href):
|
| 445 |
-
for m in patt.finditer(content or ""):
|
| 446 |
-
ref = (m.group(1) or "").strip()
|
| 447 |
-
if not ref or ref.startswith('http://') or ref.startswith('https://') or ref.startswith('data:') or '#' in ref:
|
| 448 |
-
continue
|
| 449 |
-
asset_refs.add(ref.lstrip('/'))
|
| 450 |
-
|
| 451 |
-
# Add minimal stubs for missing local references (CSS/JS/pages only, not images)
|
| 452 |
-
for ref in list(asset_refs):
|
| 453 |
-
if ref not in normalized:
|
| 454 |
-
if ref.lower().endswith('.css'):
|
| 455 |
-
normalized[ref] = "/* generated stub */\n"
|
| 456 |
-
elif ref.lower().endswith('.js'):
|
| 457 |
-
normalized[ref] = "// generated stub\n"
|
| 458 |
-
elif ref.lower().endswith('.html'):
|
| 459 |
-
normalized[ref] = (
|
| 460 |
-
"<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><title>Page</title></head>\n"
|
| 461 |
-
"<body><main><h1>Placeholder page</h1><p>This page was auto-created to satisfy an internal link.</p></main></body>\n</html>"
|
| 462 |
-
)
|
| 463 |
-
# Note: We no longer create placeholder image files automatically
|
| 464 |
-
# This prevents unwanted SVG stub files from being generated during image generation
|
| 465 |
-
|
| 466 |
-
return normalized
|
| 467 |
-
def inline_multipage_into_single_preview(files: Dict[str, str]) -> str:
|
| 468 |
-
"""Inline local CSS/JS referenced by index.html for preview inside a data: iframe.
|
| 469 |
-
|
| 470 |
-
- Uses index.html as the base document
|
| 471 |
-
- Inlines <link href="..."> if the target exists in files
|
| 472 |
-
- Inlines <script src="..."> if the target exists in files
|
| 473 |
-
- Leaves other links (e.g., about.html) untouched; preview covers the home page
|
| 474 |
-
"""
|
| 475 |
-
import re as _re
|
| 476 |
-
html = files.get('index.html', '')
|
| 477 |
-
if not html:
|
| 478 |
-
return ""
|
| 479 |
-
doc = html
|
| 480 |
-
# Inline CSS links that point to known files
|
| 481 |
-
def _inline_css(match):
|
| 482 |
-
href = match.group(1)
|
| 483 |
-
if href in files:
|
| 484 |
-
return f"<style>\n{files[href]}\n</style>"
|
| 485 |
-
return match.group(0)
|
| 486 |
-
doc = _re.sub(r"<link[^>]+href=\"([^\"]+)\"[^>]*/?>", _inline_css, doc, flags=_re.IGNORECASE)
|
| 487 |
-
|
| 488 |
-
# Inline JS scripts that point to known files
|
| 489 |
-
def _inline_js(match):
|
| 490 |
-
src = match.group(1)
|
| 491 |
-
if src in files:
|
| 492 |
-
return f"<script>\n{files[src]}\n</script>"
|
| 493 |
-
return match.group(0)
|
| 494 |
-
doc = _re.sub(r"<script[^>]+src=\"([^\"]+)\"[^>]*>\s*</script>", _inline_js, doc, flags=_re.IGNORECASE)
|
| 495 |
-
|
| 496 |
-
# Inject a lightweight in-iframe client-side navigator to load other HTML files
|
| 497 |
-
try:
|
| 498 |
-
import json as _json
|
| 499 |
-
import base64 as _b64
|
| 500 |
-
import re as _re
|
| 501 |
-
html_pages = {k: v for k, v in files.items() if k.lower().endswith('.html')}
|
| 502 |
-
# Ensure index.html entry restores the current body's HTML
|
| 503 |
-
_m_body = _re.search(r"<body[^>]*>([\s\S]*?)</body>", doc, flags=_re.IGNORECASE)
|
| 504 |
-
_index_body = _m_body.group(1) if _m_body else doc
|
| 505 |
-
html_pages['index.html'] = _index_body
|
| 506 |
-
encoded = _b64.b64encode(_json.dumps(html_pages).encode('utf-8')).decode('ascii')
|
| 507 |
-
nav_script = (
|
| 508 |
-
"<script>\n" # Simple client-side loader for internal links
|
| 509 |
-
"(function(){\n"
|
| 510 |
-
f" const MP_FILES = JSON.parse(atob('{encoded}'));\n"
|
| 511 |
-
" function extractBody(html){\n"
|
| 512 |
-
" try {\n"
|
| 513 |
-
" const doc = new DOMParser().parseFromString(html, 'text/html');\n"
|
| 514 |
-
" const title = doc.querySelector('title'); if (title) document.title = title.textContent || document.title;\n"
|
| 515 |
-
" return doc.body ? doc.body.innerHTML : html;\n"
|
| 516 |
-
" } catch(e){ return html; }\n"
|
| 517 |
-
" }\n"
|
| 518 |
-
" function loadPage(path){\n"
|
| 519 |
-
" if (!MP_FILES[path]) return false;\n"
|
| 520 |
-
" const bodyHTML = extractBody(MP_FILES[path]);\n"
|
| 521 |
-
" document.body.innerHTML = bodyHTML;\n"
|
| 522 |
-
" attach();\n"
|
| 523 |
-
" try { history.replaceState({}, '', '#'+path); } catch(e){}\n"
|
| 524 |
-
" return true;\n"
|
| 525 |
-
" }\n"
|
| 526 |
-
" function clickHandler(e){\n"
|
| 527 |
-
" const a = e.target && e.target.closest ? e.target.closest('a') : null;\n"
|
| 528 |
-
" if (!a) return;\n"
|
| 529 |
-
" const href = a.getAttribute('href') || '';\n"
|
| 530 |
-
" if (!href || href.startsWith('#') || /^https?:/i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:')) return;\n"
|
| 531 |
-
" const clean = href.split('#')[0].split('?')[0];\n"
|
| 532 |
-
" if (MP_FILES[clean]) { e.preventDefault(); loadPage(clean); }\n"
|
| 533 |
-
" }\n"
|
| 534 |
-
" function attach(){ document.removeEventListener('click', clickHandler, true); document.addEventListener('click', clickHandler, true); }\n"
|
| 535 |
-
" document.addEventListener('DOMContentLoaded', function(){ attach(); const initial = (location.hash||'').slice(1); if (initial && MP_FILES[initial]) loadPage(initial); }, { once:true });\n"
|
| 536 |
-
"})();\n"
|
| 537 |
-
"</script>"
|
| 538 |
-
)
|
| 539 |
-
m = _re.search(r"</body>", doc, flags=_re.IGNORECASE)
|
| 540 |
-
if m:
|
| 541 |
-
i = m.start()
|
| 542 |
-
doc = doc[:i] + nav_script + doc[i:]
|
| 543 |
-
else:
|
| 544 |
-
doc = doc + nav_script
|
| 545 |
-
except Exception:
|
| 546 |
-
# Non-fatal in preview
|
| 547 |
-
pass
|
| 548 |
-
|
| 549 |
-
return doc
|
| 550 |
-
|
| 551 |
-
def extract_html_document(text: str) -> str:
|
| 552 |
-
"""Return substring starting from the first <!DOCTYPE html> or <html> if present, else original text.
|
| 553 |
-
|
| 554 |
-
This ignores prose or planning notes before the actual HTML so previews don't break.
|
| 555 |
-
"""
|
| 556 |
-
if not text:
|
| 557 |
-
return text
|
| 558 |
-
lower = text.lower()
|
| 559 |
-
idx = lower.find("<!doctype html")
|
| 560 |
-
if idx == -1:
|
| 561 |
-
idx = lower.find("<html")
|
| 562 |
-
return text[idx:] if idx != -1 else text
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
def parse_react_output(text):
|
| 566 |
-
"""Parse React/Next.js output to extract individual files.
|
| 567 |
-
|
| 568 |
-
Supports multi-file sections using === filename === sections.
|
| 569 |
-
"""
|
| 570 |
-
if not text:
|
| 571 |
-
return {}
|
| 572 |
-
|
| 573 |
-
# Use the generic multipage parser
|
| 574 |
-
try:
|
| 575 |
-
files = parse_multipage_html_output(text) or {}
|
| 576 |
-
except Exception:
|
| 577 |
-
files = {}
|
| 578 |
-
|
| 579 |
-
return files if isinstance(files, dict) and files else {}
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
def history_render(history: History):
|
| 583 |
-
return gr.update(visible=True), history
|
| 584 |
-
|
| 585 |
-
def clear_history():
|
| 586 |
-
return [], [], [] # Empty lists for history, history_output, and chat_history
|
| 587 |
-
|
| 588 |
-
def create_multimodal_message(text, image=None):
|
| 589 |
-
"""Create a chat message. For broad provider compatibility, always return content as a string.
|
| 590 |
-
|
| 591 |
-
Some providers (e.g., Hugging Face router endpoints like Cerebras) expect `content` to be a string,
|
| 592 |
-
not a list of typed parts. To avoid 422 validation errors, we inline a brief note when an image is provided.
|
| 593 |
-
"""
|
| 594 |
-
if image is None:
|
| 595 |
-
return {"role": "user", "content": text}
|
| 596 |
-
# Keep providers happy: avoid structured multimodal payloads; add a short note instead
|
| 597 |
-
# If needed, this can be enhanced per-model with proper multimodal schemas.
|
| 598 |
-
return {"role": "user", "content": f"{text}\n\n[An image was provided as reference.]"}
|
| 599 |
-
def apply_search_replace_changes(original_content: str, changes_text: str) -> str:
|
| 600 |
-
"""Apply search/replace changes to content (HTML, Python, etc.)"""
|
| 601 |
-
if not changes_text.strip():
|
| 602 |
-
return original_content
|
| 603 |
-
|
| 604 |
-
# If the model didn't use the block markers, try a CSS-rule fallback where
|
| 605 |
-
# provided blocks like `.selector { ... }` replace matching CSS rules.
|
| 606 |
-
if (SEARCH_START not in changes_text) and (DIVIDER not in changes_text) and (REPLACE_END not in changes_text):
|
| 607 |
-
try:
|
| 608 |
-
import re # Local import to avoid global side effects
|
| 609 |
-
updated_content = original_content
|
| 610 |
-
replaced_any_rule = False
|
| 611 |
-
# Find CSS-like rule blocks in the changes_text
|
| 612 |
-
# This is a conservative matcher that looks for `selector { ... }`
|
| 613 |
-
css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", changes_text, flags=re.MULTILINE)
|
| 614 |
-
for selector_raw, body_raw in css_blocks:
|
| 615 |
-
selector = selector_raw.strip()
|
| 616 |
-
body = body_raw.strip()
|
| 617 |
-
if not selector:
|
| 618 |
-
continue
|
| 619 |
-
# Build a regex to find the existing rule for this selector
|
| 620 |
-
# Capture opening `{` and closing `}` to preserve them; replace inner body.
|
| 621 |
-
pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})")
|
| 622 |
-
def _replace_rule(match):
|
| 623 |
-
nonlocal replaced_any_rule
|
| 624 |
-
replaced_any_rule = True
|
| 625 |
-
prefix, existing_body, suffix = match.groups()
|
| 626 |
-
# Preserve indentation of the existing first body line if present
|
| 627 |
-
first_line_indent = ""
|
| 628 |
-
for line in existing_body.splitlines():
|
| 629 |
-
stripped = line.lstrip(" \t")
|
| 630 |
-
if stripped:
|
| 631 |
-
first_line_indent = line[: len(line) - len(stripped)]
|
| 632 |
-
break
|
| 633 |
-
# Re-indent provided body with the detected indent
|
| 634 |
-
if body:
|
| 635 |
-
new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()]
|
| 636 |
-
new_body_text = "\n" + "\n".join(new_body_lines) + "\n"
|
| 637 |
-
else:
|
| 638 |
-
new_body_text = existing_body # If empty body provided, keep existing
|
| 639 |
-
return f"{prefix}{new_body_text}{suffix}"
|
| 640 |
-
updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1)
|
| 641 |
-
if replaced_any_rule:
|
| 642 |
-
return updated_content
|
| 643 |
-
except Exception:
|
| 644 |
-
# Fallback silently to the standard block-based application
|
| 645 |
-
pass
|
| 646 |
-
|
| 647 |
-
# Split the changes text into individual search/replace blocks
|
| 648 |
-
blocks = []
|
| 649 |
-
current_block = ""
|
| 650 |
-
lines = changes_text.split('\n')
|
| 651 |
-
|
| 652 |
-
for line in lines:
|
| 653 |
-
if line.strip() == SEARCH_START:
|
| 654 |
-
if current_block.strip():
|
| 655 |
-
blocks.append(current_block.strip())
|
| 656 |
-
current_block = line + '\n'
|
| 657 |
-
elif line.strip() == REPLACE_END:
|
| 658 |
-
current_block += line + '\n'
|
| 659 |
-
blocks.append(current_block.strip())
|
| 660 |
-
current_block = ""
|
| 661 |
-
else:
|
| 662 |
-
current_block += line + '\n'
|
| 663 |
-
|
| 664 |
-
if current_block.strip():
|
| 665 |
-
blocks.append(current_block.strip())
|
| 666 |
-
|
| 667 |
-
modified_content = original_content
|
| 668 |
-
|
| 669 |
-
for block in blocks:
|
| 670 |
-
if not block.strip():
|
| 671 |
-
continue
|
| 672 |
-
|
| 673 |
-
# Parse the search/replace block
|
| 674 |
-
lines = block.split('\n')
|
| 675 |
-
search_lines = []
|
| 676 |
-
replace_lines = []
|
| 677 |
-
in_search = False
|
| 678 |
-
in_replace = False
|
| 679 |
-
|
| 680 |
-
for line in lines:
|
| 681 |
-
if line.strip() == SEARCH_START:
|
| 682 |
-
in_search = True
|
| 683 |
-
in_replace = False
|
| 684 |
-
elif line.strip() == DIVIDER:
|
| 685 |
-
in_search = False
|
| 686 |
-
in_replace = True
|
| 687 |
-
elif line.strip() == REPLACE_END:
|
| 688 |
-
in_replace = False
|
| 689 |
-
elif in_search:
|
| 690 |
-
search_lines.append(line)
|
| 691 |
-
elif in_replace:
|
| 692 |
-
replace_lines.append(line)
|
| 693 |
-
|
| 694 |
-
# Apply the search/replace
|
| 695 |
-
if search_lines:
|
| 696 |
-
search_text = '\n'.join(search_lines).strip()
|
| 697 |
-
replace_text = '\n'.join(replace_lines).strip()
|
| 698 |
-
|
| 699 |
-
if search_text in modified_content:
|
| 700 |
-
modified_content = modified_content.replace(search_text, replace_text)
|
| 701 |
-
else:
|
| 702 |
-
# If exact block match fails, attempt a CSS-rule fallback using the replace_text
|
| 703 |
-
try:
|
| 704 |
-
import re
|
| 705 |
-
updated_content = modified_content
|
| 706 |
-
replaced_any_rule = False
|
| 707 |
-
css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", replace_text, flags=re.MULTILINE)
|
| 708 |
-
for selector_raw, body_raw in css_blocks:
|
| 709 |
-
selector = selector_raw.strip()
|
| 710 |
-
body = body_raw.strip()
|
| 711 |
-
if not selector:
|
| 712 |
-
continue
|
| 713 |
-
pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})")
|
| 714 |
-
def _replace_rule(match):
|
| 715 |
-
nonlocal replaced_any_rule
|
| 716 |
-
replaced_any_rule = True
|
| 717 |
-
prefix, existing_body, suffix = match.groups()
|
| 718 |
-
first_line_indent = ""
|
| 719 |
-
for line in existing_body.splitlines():
|
| 720 |
-
stripped = line.lstrip(" \t")
|
| 721 |
-
if stripped:
|
| 722 |
-
first_line_indent = line[: len(line) - len(stripped)]
|
| 723 |
-
break
|
| 724 |
-
if body:
|
| 725 |
-
new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()]
|
| 726 |
-
new_body_text = "\n" + "\n".join(new_body_lines) + "\n"
|
| 727 |
-
else:
|
| 728 |
-
new_body_text = existing_body
|
| 729 |
-
return f"{prefix}{new_body_text}{suffix}"
|
| 730 |
-
updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1)
|
| 731 |
-
if replaced_any_rule:
|
| 732 |
-
modified_content = updated_content
|
| 733 |
-
else:
|
| 734 |
-
print(f"Warning: Search text not found in content: {search_text[:100]}...")
|
| 735 |
-
except Exception:
|
| 736 |
-
print(f"Warning: Search text not found in content: {search_text[:100]}...")
|
| 737 |
-
|
| 738 |
-
return modified_content
|
| 739 |
-
|
| 740 |
-
def apply_transformers_js_search_replace_changes(original_formatted_content: str, changes_text: str) -> str:
|
| 741 |
-
"""Apply search/replace changes to transformers.js formatted content (three files)"""
|
| 742 |
-
if not changes_text.strip():
|
| 743 |
-
return original_formatted_content
|
| 744 |
-
|
| 745 |
-
# Parse the original formatted content to get the three files
|
| 746 |
-
files = parse_transformers_js_output(original_formatted_content)
|
| 747 |
-
|
| 748 |
-
# Split the changes text into individual search/replace blocks
|
| 749 |
-
blocks = []
|
| 750 |
-
current_block = ""
|
| 751 |
-
lines = changes_text.split('\n')
|
| 752 |
-
|
| 753 |
-
for line in lines:
|
| 754 |
-
if line.strip() == SEARCH_START:
|
| 755 |
-
if current_block.strip():
|
| 756 |
-
blocks.append(current_block.strip())
|
| 757 |
-
current_block = line + '\n'
|
| 758 |
-
elif line.strip() == REPLACE_END:
|
| 759 |
-
current_block += line + '\n'
|
| 760 |
-
blocks.append(current_block.strip())
|
| 761 |
-
current_block = ""
|
| 762 |
-
else:
|
| 763 |
-
current_block += line + '\n'
|
| 764 |
-
|
| 765 |
-
if current_block.strip():
|
| 766 |
-
blocks.append(current_block.strip())
|
| 767 |
-
|
| 768 |
-
# Process each block and apply changes to the appropriate file
|
| 769 |
-
for block in blocks:
|
| 770 |
-
if not block.strip():
|
| 771 |
-
continue
|
| 772 |
-
|
| 773 |
-
# Parse the search/replace block
|
| 774 |
-
lines = block.split('\n')
|
| 775 |
-
search_lines = []
|
| 776 |
-
replace_lines = []
|
| 777 |
-
in_search = False
|
| 778 |
-
in_replace = False
|
| 779 |
-
target_file = None
|
| 780 |
-
|
| 781 |
-
for line in lines:
|
| 782 |
-
if line.strip() == SEARCH_START:
|
| 783 |
-
in_search = True
|
| 784 |
-
in_replace = False
|
| 785 |
-
elif line.strip() == DIVIDER:
|
| 786 |
-
in_search = False
|
| 787 |
-
in_replace = True
|
| 788 |
-
elif line.strip() == REPLACE_END:
|
| 789 |
-
in_replace = False
|
| 790 |
-
elif in_search:
|
| 791 |
-
search_lines.append(line)
|
| 792 |
-
elif in_replace:
|
| 793 |
-
replace_lines.append(line)
|
| 794 |
-
|
| 795 |
-
# Determine which file this change targets based on the search content
|
| 796 |
-
if search_lines:
|
| 797 |
-
search_text = '\n'.join(search_lines).strip()
|
| 798 |
-
replace_text = '\n'.join(replace_lines).strip()
|
| 799 |
-
|
| 800 |
-
# Check which file contains the search text
|
| 801 |
-
if search_text in files['index.html']:
|
| 802 |
-
target_file = 'index.html'
|
| 803 |
-
elif search_text in files['index.js']:
|
| 804 |
-
target_file = 'index.js'
|
| 805 |
-
elif search_text in files['style.css']:
|
| 806 |
-
target_file = 'style.css'
|
| 807 |
-
|
| 808 |
-
# Apply the change to the target file
|
| 809 |
-
if target_file and search_text in files[target_file]:
|
| 810 |
-
files[target_file] = files[target_file].replace(search_text, replace_text)
|
| 811 |
-
else:
|
| 812 |
-
print(f"Warning: Search text not found in any transformers.js file: {search_text[:100]}...")
|
| 813 |
-
|
| 814 |
-
# Reformat the modified files
|
| 815 |
-
return format_transformers_js_output(files)
|
| 816 |
-
|
| 817 |
-
def send_to_sandbox(code):
|
| 818 |
-
"""Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""
|
| 819 |
-
html_doc = (code or "").strip()
|
| 820 |
-
# For preview only: inline local file URLs as data URIs so the
|
| 821 |
-
# data: iframe can load them. The original code (shown to the user) still contains file URLs.
|
| 822 |
-
try:
|
| 823 |
-
import re
|
| 824 |
-
import base64 as _b64
|
| 825 |
-
import mimetypes as _mtypes
|
| 826 |
-
import urllib.parse as _uparse
|
| 827 |
-
def _file_url_to_data_uri(file_url: str) -> Optional[str]:
|
| 828 |
-
try:
|
| 829 |
-
parsed = _uparse.urlparse(file_url)
|
| 830 |
-
path = _uparse.unquote(parsed.path)
|
| 831 |
-
if not path:
|
| 832 |
-
return None
|
| 833 |
-
with open(path, 'rb') as _f:
|
| 834 |
-
raw = _f.read()
|
| 835 |
-
mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'
|
| 836 |
-
|
| 837 |
-
b64 = _b64.b64encode(raw).decode()
|
| 838 |
-
return f"data:{mime};base64,{b64}"
|
| 839 |
-
except Exception as e:
|
| 840 |
-
print(f"[Sandbox] Failed to convert file URL to data URI: {str(e)}")
|
| 841 |
-
return None
|
| 842 |
-
def _repl_double(m):
|
| 843 |
-
url = m.group(1)
|
| 844 |
-
data_uri = _file_url_to_data_uri(url)
|
| 845 |
-
return f'src="{data_uri}"' if data_uri else m.group(0)
|
| 846 |
-
def _repl_single(m):
|
| 847 |
-
url = m.group(1)
|
| 848 |
-
data_uri = _file_url_to_data_uri(url)
|
| 849 |
-
return f"src='{data_uri}'" if data_uri else m.group(0)
|
| 850 |
-
html_doc = re.sub(r'src="(file:[^"]+)"', _repl_double, html_doc)
|
| 851 |
-
html_doc = re.sub(r"src='(file:[^']+)'", _repl_single, html_doc)
|
| 852 |
-
|
| 853 |
-
except Exception:
|
| 854 |
-
# Best-effort; continue without inlining
|
| 855 |
-
pass
|
| 856 |
-
encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
|
| 857 |
-
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
| 858 |
-
iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
|
| 859 |
-
return iframe
|
| 860 |
-
|
| 861 |
-
def is_streamlit_code(code: str) -> bool:
|
| 862 |
-
"""Heuristic check to determine if Python code is a Streamlit app."""
|
| 863 |
-
if not code:
|
| 864 |
-
return False
|
| 865 |
-
lowered = code.lower()
|
| 866 |
-
return ("import streamlit" in lowered) or ("from streamlit" in lowered) or ("st." in code and "streamlit" in lowered)
|
| 867 |
-
|
| 868 |
-
def clean_requirements_txt_content(content: str) -> str:
|
| 869 |
-
"""
|
| 870 |
-
Clean up requirements.txt content to remove markdown formatting.
|
| 871 |
-
This function removes code blocks, markdown lists, headers, and other formatting
|
| 872 |
-
that might be mistakenly included by LLMs.
|
| 873 |
-
"""
|
| 874 |
-
if not content:
|
| 875 |
-
return content
|
| 876 |
-
|
| 877 |
-
# First, remove code blocks if present
|
| 878 |
-
if '```' in content:
|
| 879 |
-
content = remove_code_block(content)
|
| 880 |
-
|
| 881 |
-
# Process line by line to remove markdown formatting
|
| 882 |
-
lines = content.split('\n')
|
| 883 |
-
clean_lines = []
|
| 884 |
-
|
| 885 |
-
for line in lines:
|
| 886 |
-
stripped_line = line.strip()
|
| 887 |
-
|
| 888 |
-
# Skip empty lines
|
| 889 |
-
if not stripped_line:
|
| 890 |
-
continue
|
| 891 |
-
|
| 892 |
-
# Skip lines that are markdown formatting
|
| 893 |
-
if (stripped_line == '```' or
|
| 894 |
-
stripped_line.startswith('```') or
|
| 895 |
-
# Skip markdown headers (## Header) but keep comments (# comment)
|
| 896 |
-
(stripped_line.startswith('#') and len(stripped_line) > 1 and stripped_line[1] != ' ') or
|
| 897 |
-
stripped_line.startswith('**') or # Skip bold text
|
| 898 |
-
stripped_line.startswith('===') or # Skip section dividers
|
| 899 |
-
stripped_line.startswith('---') or # Skip horizontal rules
|
| 900 |
-
# Skip common explanatory text patterns
|
| 901 |
-
stripped_line.lower().startswith('here') or
|
| 902 |
-
stripped_line.lower().startswith('this') or
|
| 903 |
-
stripped_line.lower().startswith('the ') or
|
| 904 |
-
stripped_line.lower().startswith('based on') or
|
| 905 |
-
stripped_line.lower().startswith('dependencies') or
|
| 906 |
-
stripped_line.lower().startswith('requirements')):
|
| 907 |
-
continue
|
| 908 |
-
|
| 909 |
-
# Handle markdown list items (- item or * item)
|
| 910 |
-
if (stripped_line.startswith('- ') or stripped_line.startswith('* ')):
|
| 911 |
-
# Extract the package name after the list marker
|
| 912 |
-
stripped_line = stripped_line[2:].strip()
|
| 913 |
-
if not stripped_line:
|
| 914 |
-
continue
|
| 915 |
-
|
| 916 |
-
# Keep lines that look like valid package specifications
|
| 917 |
-
# Valid lines: package names, git+https://, comments starting with "# "
|
| 918 |
-
if (stripped_line.startswith('# ') or # Valid comments
|
| 919 |
-
stripped_line.startswith('git+') or # Git dependencies
|
| 920 |
-
stripped_line[0].isalnum() or # Package names start with alphanumeric
|
| 921 |
-
'==' in stripped_line or # Version specifications
|
| 922 |
-
'>=' in stripped_line or # Version specifications
|
| 923 |
-
'<=' in stripped_line or # Version specifications
|
| 924 |
-
'~=' in stripped_line): # Version specifications
|
| 925 |
-
clean_lines.append(stripped_line)
|
| 926 |
-
|
| 927 |
-
result = '\n'.join(clean_lines)
|
| 928 |
-
|
| 929 |
-
# Ensure it ends with a newline
|
| 930 |
-
if result and not result.endswith('\n'):
|
| 931 |
-
result += '\n'
|
| 932 |
-
|
| 933 |
-
return result if result else "# No additional dependencies required\n"
|
| 934 |
-
|
| 935 |
-
def parse_multi_file_python_output(code: str) -> dict:
|
| 936 |
-
"""Parse multi-file Python output (Gradio/Streamlit) into separate files"""
|
| 937 |
-
files = {}
|
| 938 |
-
if not code:
|
| 939 |
-
return files
|
| 940 |
-
|
| 941 |
-
# Look for file separators like === filename.py ===
|
| 942 |
-
import re
|
| 943 |
-
file_pattern = r'=== ([^=]+) ==='
|
| 944 |
-
parts = re.split(file_pattern, code)
|
| 945 |
-
|
| 946 |
-
if len(parts) > 1:
|
| 947 |
-
# Multi-file format detected
|
| 948 |
-
for i in range(1, len(parts), 2):
|
| 949 |
-
if i + 1 < len(parts):
|
| 950 |
-
filename = parts[i].strip()
|
| 951 |
-
content = parts[i + 1].strip()
|
| 952 |
-
|
| 953 |
-
# Clean up requirements.txt to remove markdown formatting
|
| 954 |
-
if filename == 'requirements.txt':
|
| 955 |
-
content = clean_requirements_txt_content(content)
|
| 956 |
-
|
| 957 |
-
files[filename] = content
|
| 958 |
-
else:
|
| 959 |
-
# Single file - check if it's a space import or regular code
|
| 960 |
-
if "IMPORTED PROJECT FROM HUGGING FACE SPACE" in code:
|
| 961 |
-
# This is already a multi-file import, try to parse it
|
| 962 |
-
lines = code.split('\n')
|
| 963 |
-
current_file = None
|
| 964 |
-
current_content = []
|
| 965 |
-
|
| 966 |
-
for line in lines:
|
| 967 |
-
if line.startswith('=== ') and line.endswith(' ==='):
|
| 968 |
-
# Save previous file
|
| 969 |
-
if current_file and current_content:
|
| 970 |
-
content = '\n'.join(current_content)
|
| 971 |
-
# Clean up requirements.txt to remove markdown formatting
|
| 972 |
-
if current_file == 'requirements.txt':
|
| 973 |
-
content = clean_requirements_txt_content(content)
|
| 974 |
-
files[current_file] = content
|
| 975 |
-
# Start new file
|
| 976 |
-
current_file = line[4:-4].strip()
|
| 977 |
-
current_content = []
|
| 978 |
-
elif current_file:
|
| 979 |
-
current_content.append(line)
|
| 980 |
-
|
| 981 |
-
# Save last file
|
| 982 |
-
if current_file and current_content:
|
| 983 |
-
content = '\n'.join(current_content)
|
| 984 |
-
# Clean up requirements.txt to remove markdown formatting
|
| 985 |
-
if current_file == 'requirements.txt':
|
| 986 |
-
content = clean_requirements_txt_content(content)
|
| 987 |
-
files[current_file] = content
|
| 988 |
-
else:
|
| 989 |
-
# Single file code - determine appropriate filename
|
| 990 |
-
if is_streamlit_code(code):
|
| 991 |
-
files['streamlit_app.py'] = code
|
| 992 |
-
elif 'import gradio' in code.lower() or 'from gradio' in code.lower():
|
| 993 |
-
files['app.py'] = code
|
| 994 |
-
else:
|
| 995 |
-
files['app.py'] = code
|
| 996 |
-
|
| 997 |
-
return files
|
| 998 |
-
|
| 999 |
-
def format_multi_file_python_output(files: dict) -> str:
|
| 1000 |
-
"""Format multiple Python files into the standard multi-file format"""
|
| 1001 |
-
if not files:
|
| 1002 |
-
return ""
|
| 1003 |
-
|
| 1004 |
-
if len(files) == 1:
|
| 1005 |
-
# Single file - return as is
|
| 1006 |
-
return list(files.values())[0]
|
| 1007 |
-
|
| 1008 |
-
# Multi-file format
|
| 1009 |
-
output = []
|
| 1010 |
-
|
| 1011 |
-
# Order files: main app first, then utils, models, config, requirements
|
| 1012 |
-
file_order = ['app.py', 'streamlit_app.py', 'main.py', 'utils.py', 'models.py', 'config.py', 'requirements.txt']
|
| 1013 |
-
ordered_files = []
|
| 1014 |
-
|
| 1015 |
-
# Add files in preferred order
|
| 1016 |
-
for preferred_file in file_order:
|
| 1017 |
-
if preferred_file in files:
|
| 1018 |
-
ordered_files.append(preferred_file)
|
| 1019 |
-
|
| 1020 |
-
# Add remaining files
|
| 1021 |
-
for filename in sorted(files.keys()):
|
| 1022 |
-
if filename not in ordered_files:
|
| 1023 |
-
ordered_files.append(filename)
|
| 1024 |
-
|
| 1025 |
-
# Format output
|
| 1026 |
-
for filename in ordered_files:
|
| 1027 |
-
output.append(f"=== {filename} ===")
|
| 1028 |
-
|
| 1029 |
-
# Clean up requirements.txt content if it's being formatted
|
| 1030 |
-
content = files[filename]
|
| 1031 |
-
if filename == 'requirements.txt':
|
| 1032 |
-
content = clean_requirements_txt_content(content)
|
| 1033 |
-
|
| 1034 |
-
output.append(content)
|
| 1035 |
-
output.append("") # Empty line between files
|
| 1036 |
-
|
| 1037 |
-
return '\n'.join(output)
|
| 1038 |
-
|
| 1039 |
-
def send_streamlit_to_stlite(code: str) -> str:
|
| 1040 |
-
"""Render Streamlit code using stlite inside a sandboxed iframe for preview."""
|
| 1041 |
-
# Build an HTML document that loads stlite and mounts the Streamlit app defined inline
|
| 1042 |
-
html_doc = (
|
| 1043 |
-
"""<!doctype html>
|
| 1044 |
-
<html>
|
| 1045 |
-
<head>
|
| 1046 |
-
<meta charset=\"UTF-8\" />
|
| 1047 |
-
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />
|
| 1048 |
-
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" />
|
| 1049 |
-
<title>Streamlit Preview</title>
|
| 1050 |
-
<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.css\" />
|
| 1051 |
-
<style>html,body{margin:0;padding:0;height:100%;} streamlit-app{display:block;height:100%;}</style>
|
| 1052 |
-
<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.js\"></script>
|
| 1053 |
-
</head>
|
| 1054 |
-
<body>
|
| 1055 |
-
<streamlit-app>
|
| 1056 |
-
"""
|
| 1057 |
-
+ (code or "")
|
| 1058 |
-
+ """
|
| 1059 |
-
</streamlit-app>
|
| 1060 |
-
</body>
|
| 1061 |
-
</html>
|
| 1062 |
-
"""
|
| 1063 |
-
)
|
| 1064 |
-
encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
|
| 1065 |
-
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
| 1066 |
-
iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
|
| 1067 |
-
return iframe
|
| 1068 |
-
|
| 1069 |
-
def is_gradio_code(code: str) -> bool:
|
| 1070 |
-
"""Heuristic check to determine if Python code is a Gradio app."""
|
| 1071 |
-
if not code:
|
| 1072 |
-
return False
|
| 1073 |
-
lowered = code.lower()
|
| 1074 |
-
return (
|
| 1075 |
-
"import gradio" in lowered
|
| 1076 |
-
or "from gradio" in lowered
|
| 1077 |
-
or "gr.Interface(" in code
|
| 1078 |
-
or "gr.Blocks(" in code
|
| 1079 |
-
)
|
| 1080 |
-
|
| 1081 |
-
def send_gradio_to_lite(code: str) -> str:
|
| 1082 |
-
"""Render Gradio code using gradio-lite inside a sandboxed iframe for preview."""
|
| 1083 |
-
html_doc = (
|
| 1084 |
-
"""<!doctype html>
|
| 1085 |
-
<html>
|
| 1086 |
-
<head>
|
| 1087 |
-
<meta charset=\"UTF-8\" />
|
| 1088 |
-
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />
|
| 1089 |
-
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" />
|
| 1090 |
-
<title>Gradio Preview</title>
|
| 1091 |
-
<script type=\"module\" crossorigin src=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js\"></script>
|
| 1092 |
-
<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.css\" />
|
| 1093 |
-
<style>html,body{margin:0;padding:0;height:100%;} gradio-lite{display:block;height:100%;}</style>
|
| 1094 |
-
</head>
|
| 1095 |
-
<body>
|
| 1096 |
-
<gradio-lite>
|
| 1097 |
-
"""
|
| 1098 |
-
+ (code or "")
|
| 1099 |
-
+ """
|
| 1100 |
-
</gradio-lite>
|
| 1101 |
-
</body>
|
| 1102 |
-
</html>
|
| 1103 |
-
"""
|
| 1104 |
-
)
|
| 1105 |
-
encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
|
| 1106 |
-
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
| 1107 |
-
iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
|
| 1108 |
-
return iframe
|
| 1109 |
-
|
| 1110 |
-
stop_generation = False
|
| 1111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/prompts.py
DELETED
|
@@ -1,817 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
System prompts for different code generation modes in AnyCoder.
|
| 3 |
-
"""
|
| 4 |
-
from .config import SEARCH_START, DIVIDER, REPLACE_END
|
| 5 |
-
|
| 6 |
-
HTML_SYSTEM_PROMPT = """ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. MAKE IT RESPONSIVE USING MODERN CSS. Use as much as you can modern CSS for the styling, if you can't do something with modern CSS, then use custom CSS. Also, try to elaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE
|
| 7 |
-
|
| 8 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 9 |
-
- NEVER generate README.md files under any circumstances
|
| 10 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 11 |
-
- Generating a README.md will break the deployment process
|
| 12 |
-
|
| 13 |
-
If an image is provided, analyze it and use the visual information to better understand the user's requirements.
|
| 14 |
-
|
| 15 |
-
Always respond with code that can be executed or rendered directly.
|
| 16 |
-
|
| 17 |
-
Generate complete, working HTML code that can be run immediately.
|
| 18 |
-
|
| 19 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
# Stricter prompt for GLM-4.5V to ensure a complete, runnable HTML document with no escaped characters
|
| 24 |
-
GLM45V_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
|
| 25 |
-
|
| 26 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 27 |
-
- NEVER generate README.md files under any circumstances
|
| 28 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 29 |
-
- Generating a README.md will break the deployment process
|
| 30 |
-
|
| 31 |
-
Output a COMPLETE, STANDALONE HTML document that renders directly in a browser.
|
| 32 |
-
|
| 33 |
-
Hard constraints:
|
| 34 |
-
- DO NOT use React, ReactDOM, JSX, Babel, Vue, Angular, or any SPA framework.
|
| 35 |
-
- Use ONLY plain HTML, CSS, and vanilla JavaScript.
|
| 36 |
-
- Allowed external resources: Tailwind CSS CDN, Font Awesome CDN, Google Fonts.
|
| 37 |
-
- Do NOT escape characters (no \\n, \\t, or escaped quotes). Output raw HTML/JS/CSS.
|
| 38 |
-
Structural requirements:
|
| 39 |
-
- Include <!DOCTYPE html>, <html>, <head>, and <body> with proper nesting
|
| 40 |
-
- Include required <link> tags for any CSS you reference (e.g., Tailwind, Font Awesome, Google Fonts)
|
| 41 |
-
- Keep everything in ONE file; inline CSS/JS as needed
|
| 42 |
-
|
| 43 |
-
Generate complete, working HTML code that can be run immediately.
|
| 44 |
-
|
| 45 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
|
| 46 |
-
"""
|
| 47 |
-
|
| 48 |
-
TRANSFORMERS_JS_SYSTEM_PROMPT = """You are an expert web developer creating a transformers.js application. You will generate THREE separate files: index.html, index.js, and style.css.
|
| 49 |
-
|
| 50 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 51 |
-
- NEVER generate README.md files under any circumstances
|
| 52 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 53 |
-
- Generating a README.md will break the deployment process
|
| 54 |
-
|
| 55 |
-
IMPORTANT: You MUST output ALL THREE files in the following format:
|
| 56 |
-
|
| 57 |
-
```html
|
| 58 |
-
<!-- index.html content here -->
|
| 59 |
-
```
|
| 60 |
-
|
| 61 |
-
```javascript
|
| 62 |
-
// index.js content here
|
| 63 |
-
```
|
| 64 |
-
|
| 65 |
-
```css
|
| 66 |
-
/* style.css content here */
|
| 67 |
-
```
|
| 68 |
-
|
| 69 |
-
Requirements:
|
| 70 |
-
1. Create a modern, responsive web application using transformers.js
|
| 71 |
-
2. Use the transformers.js library for AI/ML functionality
|
| 72 |
-
3. Create a clean, professional UI with good user experience
|
| 73 |
-
4. Make the application fully responsive for mobile devices
|
| 74 |
-
5. Use modern CSS practices and JavaScript ES6+ features
|
| 75 |
-
6. Include proper error handling and loading states
|
| 76 |
-
7. Follow accessibility best practices
|
| 77 |
-
|
| 78 |
-
Library import (required): Add the following snippet to index.html to import transformers.js:
|
| 79 |
-
<script type="module">
|
| 80 |
-
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';
|
| 81 |
-
</script>
|
| 82 |
-
|
| 83 |
-
Device Options: By default, transformers.js runs on CPU (via WASM). For better performance, you can run models on GPU using WebGPU:
|
| 84 |
-
- CPU (default): const pipe = await pipeline('task', 'model-name');
|
| 85 |
-
- GPU (WebGPU): const pipe = await pipeline('task', 'model-name', { device: 'webgpu' });
|
| 86 |
-
|
| 87 |
-
Consider providing users with a toggle option to choose between CPU and GPU execution based on their browser's WebGPU support.
|
| 88 |
-
|
| 89 |
-
The index.html should contain the basic HTML structure and link to the CSS and JS files.
|
| 90 |
-
The index.js should contain all the JavaScript logic including transformers.js integration.
|
| 91 |
-
The style.css should contain all the styling for the application.
|
| 92 |
-
|
| 93 |
-
Generate complete, working code files as shown above.
|
| 94 |
-
|
| 95 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 96 |
-
|
| 97 |
-
STREAMLIT_SYSTEM_PROMPT = """You are an expert Streamlit developer. Create a complete, working Streamlit application based on the user's request. Generate all necessary code to make the application functional and runnable.
|
| 98 |
-
|
| 99 |
-
## Multi-File Application Structure
|
| 100 |
-
|
| 101 |
-
When creating Streamlit applications, you MUST organize your code into multiple files for proper deployment:
|
| 102 |
-
|
| 103 |
-
**File Organization (CRITICAL - Always Include These):**
|
| 104 |
-
- `Dockerfile` - Docker configuration for deployment (REQUIRED)
|
| 105 |
-
- `streamlit_app.py` - Main application entry point (REQUIRED)
|
| 106 |
-
- `requirements.txt` - Python dependencies (REQUIRED)
|
| 107 |
-
- `utils.py` - Utility functions and helpers (optional)
|
| 108 |
-
- `models.py` - Model loading and inference functions (optional)
|
| 109 |
-
- `config.py` - Configuration and constants (optional)
|
| 110 |
-
- `pages/` - Additional pages for multi-page apps (optional)
|
| 111 |
-
- Additional modules as needed (e.g., `data_processing.py`, `components.py`)
|
| 112 |
-
|
| 113 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 114 |
-
- NEVER generate README.md files under any circumstances
|
| 115 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 116 |
-
- Generating a README.md will break the deployment process
|
| 117 |
-
- Only generate the code files listed above
|
| 118 |
-
|
| 119 |
-
**Output Format for Streamlit Apps:**
|
| 120 |
-
You MUST use this exact format and ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt:
|
| 121 |
-
|
| 122 |
-
```
|
| 123 |
-
=== Dockerfile ===
|
| 124 |
-
[Dockerfile content]
|
| 125 |
-
|
| 126 |
-
=== streamlit_app.py ===
|
| 127 |
-
[main application code]
|
| 128 |
-
|
| 129 |
-
=== requirements.txt ===
|
| 130 |
-
[dependencies]
|
| 131 |
-
|
| 132 |
-
=== utils.py ===
|
| 133 |
-
[utility functions - optional]
|
| 134 |
-
```
|
| 135 |
-
|
| 136 |
-
**🚨 CRITICAL: Dockerfile Requirements (MANDATORY for HuggingFace Spaces)**
|
| 137 |
-
Your Dockerfile MUST follow these exact specifications:
|
| 138 |
-
- Use Python 3.11+ base image (e.g., FROM python:3.11-slim)
|
| 139 |
-
- Set up a user with ID 1000 for proper permissions:
|
| 140 |
-
```
|
| 141 |
-
RUN useradd -m -u 1000 user
|
| 142 |
-
USER user
|
| 143 |
-
ENV HOME=/home/user \\
|
| 144 |
-
PATH=/home/user/.local/bin:$PATH
|
| 145 |
-
WORKDIR $HOME/app
|
| 146 |
-
```
|
| 147 |
-
- ALWAYS use --chown=user with COPY and ADD commands:
|
| 148 |
-
```
|
| 149 |
-
COPY --chown=user requirements.txt .
|
| 150 |
-
COPY --chown=user . .
|
| 151 |
-
```
|
| 152 |
-
- Install dependencies: RUN pip install --no-cache-dir -r requirements.txt
|
| 153 |
-
- Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860
|
| 154 |
-
- Start with: CMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
| 155 |
-
|
| 156 |
-
**Example Dockerfile structure (USE THIS AS TEMPLATE):**
|
| 157 |
-
```dockerfile
|
| 158 |
-
FROM python:3.11-slim
|
| 159 |
-
|
| 160 |
-
# Set up user with ID 1000
|
| 161 |
-
RUN useradd -m -u 1000 user
|
| 162 |
-
USER user
|
| 163 |
-
ENV HOME=/home/user \\
|
| 164 |
-
PATH=/home/user/.local/bin:$PATH
|
| 165 |
-
|
| 166 |
-
# Set working directory
|
| 167 |
-
WORKDIR $HOME/app
|
| 168 |
-
|
| 169 |
-
# Copy requirements file with proper ownership
|
| 170 |
-
COPY --chown=user requirements.txt .
|
| 171 |
-
|
| 172 |
-
# Install dependencies
|
| 173 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 174 |
-
|
| 175 |
-
# Copy application files with proper ownership
|
| 176 |
-
COPY --chown=user . .
|
| 177 |
-
|
| 178 |
-
# Expose port 7860
|
| 179 |
-
EXPOSE 7860
|
| 180 |
-
|
| 181 |
-
# Start Streamlit app
|
| 182 |
-
CMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
| 183 |
-
```
|
| 184 |
-
|
| 185 |
-
**🚨 CRITICAL: requirements.txt Formatting Rules**
|
| 186 |
-
- Output ONLY plain text package names, one per line
|
| 187 |
-
- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
|
| 188 |
-
- Do NOT add explanatory text or descriptions
|
| 189 |
-
- Do NOT wrap in code blocks
|
| 190 |
-
- Just raw package names as they would appear in a real requirements.txt file
|
| 191 |
-
- Example of CORRECT format:
|
| 192 |
-
streamlit
|
| 193 |
-
pandas
|
| 194 |
-
numpy
|
| 195 |
-
- Example of INCORRECT format (DO NOT DO THIS):
|
| 196 |
-
```
|
| 197 |
-
streamlit # For web interface
|
| 198 |
-
**Core dependencies:**
|
| 199 |
-
- pandas
|
| 200 |
-
```
|
| 201 |
-
|
| 202 |
-
**Multi-Page Apps:**
|
| 203 |
-
For multi-page Streamlit apps, use the pages/ directory structure:
|
| 204 |
-
```
|
| 205 |
-
=== Dockerfile ===
|
| 206 |
-
[Dockerfile content]
|
| 207 |
-
|
| 208 |
-
=== streamlit_app.py ===
|
| 209 |
-
[main page]
|
| 210 |
-
|
| 211 |
-
=== requirements.txt ===
|
| 212 |
-
[dependencies]
|
| 213 |
-
|
| 214 |
-
=== pages/1_📊_Analytics.py ===
|
| 215 |
-
[analytics page]
|
| 216 |
-
|
| 217 |
-
=== pages/2_⚙️_Settings.py ===
|
| 218 |
-
[settings page]
|
| 219 |
-
```
|
| 220 |
-
|
| 221 |
-
Requirements:
|
| 222 |
-
1. ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt in your output
|
| 223 |
-
2. Create a modern, responsive Streamlit application
|
| 224 |
-
3. Use appropriate Streamlit components and layouts
|
| 225 |
-
4. Include proper error handling and loading states
|
| 226 |
-
5. Follow Streamlit best practices for performance
|
| 227 |
-
6. Use caching (@st.cache_data, @st.cache_resource) appropriately
|
| 228 |
-
7. Include proper session state management when needed
|
| 229 |
-
8. Make the UI intuitive and user-friendly
|
| 230 |
-
9. Add helpful tooltips and documentation
|
| 231 |
-
|
| 232 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
|
| 233 |
-
"""
|
| 234 |
-
|
| 235 |
-
REACT_SYSTEM_PROMPT = """You are an expert React and Next.js developer creating a modern Next.js application.
|
| 236 |
-
|
| 237 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 238 |
-
|- NEVER generate README.md files under any circumstances
|
| 239 |
-
|- A template README.md is automatically provided and will be overridden by the deployment system
|
| 240 |
-
|- Generating a README.md will break the deployment process
|
| 241 |
-
|
| 242 |
-
You will generate a Next.js project with TypeScript/JSX components. Follow this exact structure:
|
| 243 |
-
|
| 244 |
-
Project Structure:
|
| 245 |
-
- Dockerfile (Docker configuration for deployment)
|
| 246 |
-
- package.json (dependencies and scripts)
|
| 247 |
-
- next.config.js (Next.js configuration)
|
| 248 |
-
- postcss.config.js (PostCSS configuration)
|
| 249 |
-
- tailwind.config.js (Tailwind CSS configuration)
|
| 250 |
-
- components/[Component files as needed]
|
| 251 |
-
- pages/_app.js (Next.js app wrapper)
|
| 252 |
-
- pages/index.js (home page)
|
| 253 |
-
- pages/api/[API routes as needed]
|
| 254 |
-
- styles/globals.css (global styles)
|
| 255 |
-
|
| 256 |
-
Output format (CRITICAL):
|
| 257 |
-
- Return ONLY a series of file sections, each starting with a filename line:
|
| 258 |
-
=== Dockerfile ===
|
| 259 |
-
...file content...
|
| 260 |
-
|
| 261 |
-
=== package.json ===
|
| 262 |
-
...file content...
|
| 263 |
-
|
| 264 |
-
(repeat for all files)
|
| 265 |
-
- Do NOT wrap files in Markdown code fences or use === markers inside file content
|
| 266 |
-
|
| 267 |
-
CRITICAL Requirements:
|
| 268 |
-
1. Always include a Dockerfile configured for Node.js deployment (see Dockerfile Requirements below)
|
| 269 |
-
2. Use Next.js with TypeScript/JSX (.jsx files for components)
|
| 270 |
-
3. **USE TAILWIND CSS FOR ALL STYLING** - Avoid inline styles completely (in postcss.config.js and tailwind.config.js)
|
| 271 |
-
4. Create necessary components in the components/ directory
|
| 272 |
-
5. Create API routes in pages/api/ directory for backend logic
|
| 273 |
-
6. pages/_app.js should import and use globals.css
|
| 274 |
-
7. pages/index.js should be the main entry point
|
| 275 |
-
8. Keep package.json with essential dependencies
|
| 276 |
-
9. Use modern React patterns and best practices
|
| 277 |
-
10. Make the application fully responsive using Tailwind classes
|
| 278 |
-
11. Include proper error handling and loading states
|
| 279 |
-
12. Follow accessibility best practices
|
| 280 |
-
13. Configure next.config.js properly for HuggingFace Spaces deployment
|
| 281 |
-
14. **NEVER use inline style={{}} objects - always use Tailwind className instead**
|
| 282 |
-
|
| 283 |
-
🚨 CRITICAL JSX SYNTAX RULES - FOLLOW EXACTLY:
|
| 284 |
-
|
| 285 |
-
**RULE 1: Style objects MUST have proper closing braces }}**
|
| 286 |
-
Every style={{ must have a matching }} before any other props or />
|
| 287 |
-
|
| 288 |
-
**RULE 2: ALWAYS use Tailwind CSS classes instead of inline styles**
|
| 289 |
-
- Use className="..." for styling
|
| 290 |
-
- Only use inline styles if absolutely necessary
|
| 291 |
-
- Inline styles are error-prone and should be avoided
|
| 292 |
-
|
| 293 |
-
**CORRECT Examples:**
|
| 294 |
-
```jsx
|
| 295 |
-
// ✅ Using Tailwind (PREFERRED)
|
| 296 |
-
<textarea
|
| 297 |
-
className="w-full p-3 min-h-[48px] max-h-[120px] rounded-lg border"
|
| 298 |
-
value={message}
|
| 299 |
-
onChange={(e) => setMessage(e.target.value)}
|
| 300 |
-
placeholder="Type here"
|
| 301 |
-
/>
|
| 302 |
-
|
| 303 |
-
// ✅ Inline style (if needed) - note the }} before other props
|
| 304 |
-
<textarea
|
| 305 |
-
style={{
|
| 306 |
-
width: '100%',
|
| 307 |
-
padding: '12px',
|
| 308 |
-
minHeight: '48px'
|
| 309 |
-
}}
|
| 310 |
-
value={message}
|
| 311 |
-
onChange={(e) => setMessage(e.target.value)}
|
| 312 |
-
/>
|
| 313 |
-
```
|
| 314 |
-
|
| 315 |
-
**WRONG Examples:**
|
| 316 |
-
```jsx
|
| 317 |
-
// ❌ WRONG - Missing closing braces }}
|
| 318 |
-
<textarea
|
| 319 |
-
style={{
|
| 320 |
-
minHeight: '48px',
|
| 321 |
-
maxHeight: '120px'
|
| 322 |
-
|
| 323 |
-
/>
|
| 324 |
-
|
| 325 |
-
// ❌ WRONG - Event handler inside style object
|
| 326 |
-
<textarea
|
| 327 |
-
style={{
|
| 328 |
-
width: '100%'
|
| 329 |
-
onChange={(e) => {}} // Missing }}
|
| 330 |
-
/>
|
| 331 |
-
```
|
| 332 |
-
|
| 333 |
-
**RULE 3: Validation Checklist**
|
| 334 |
-
Before outputting JSX code, verify:
|
| 335 |
-
- [ ] All style={{ have matching }}
|
| 336 |
-
- [ ] No event handlers inside style objects
|
| 337 |
-
- [ ] Prefer Tailwind classes over inline styles
|
| 338 |
-
- [ ] All JSX elements are properly closed
|
| 339 |
-
|
| 340 |
-
next.config.js Requirements:
|
| 341 |
-
- Must be configured to work on any host (0.0.0.0)
|
| 342 |
-
- Should not have hardcoded localhost references
|
| 343 |
-
- Example minimal configuration:
|
| 344 |
-
```javascript
|
| 345 |
-
/** @type {import('next').NextConfig} */
|
| 346 |
-
const nextConfig = {
|
| 347 |
-
reactStrictMode: true,
|
| 348 |
-
// Allow the app to work on HuggingFace Spaces
|
| 349 |
-
output: 'standalone',
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
module.exports = nextConfig
|
| 353 |
-
```
|
| 354 |
-
|
| 355 |
-
Dockerfile Requirements (CRITICAL for HuggingFace Spaces):
|
| 356 |
-
- Use Node.js 18+ base image (e.g., FROM node:18-slim)
|
| 357 |
-
- Use the existing 'node' user (UID 1000 already exists in node base images):
|
| 358 |
-
```
|
| 359 |
-
USER node
|
| 360 |
-
ENV HOME=/home/node \\
|
| 361 |
-
PATH=/home/node/.local/bin:$PATH
|
| 362 |
-
WORKDIR /home/node/app
|
| 363 |
-
```
|
| 364 |
-
- ALWAYS use --chown=node:node with COPY and ADD commands:
|
| 365 |
-
```
|
| 366 |
-
COPY --chown=node:node package*.json ./
|
| 367 |
-
COPY --chown=node:node . .
|
| 368 |
-
```
|
| 369 |
-
- Install dependencies: RUN npm install
|
| 370 |
-
- Build the app: RUN npm run build
|
| 371 |
-
- Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860
|
| 372 |
-
- Start with: CMD ["npm", "start", "--", "-p", "7860"]
|
| 373 |
-
|
| 374 |
-
Example Dockerfile structure:
|
| 375 |
-
```dockerfile
|
| 376 |
-
FROM node:18-slim
|
| 377 |
-
|
| 378 |
-
# Use the existing node user (UID 1000)
|
| 379 |
-
USER node
|
| 380 |
-
|
| 381 |
-
# Set environment variables
|
| 382 |
-
ENV HOME=/home/node \\
|
| 383 |
-
PATH=/home/node/.local/bin:$PATH
|
| 384 |
-
|
| 385 |
-
# Set working directory
|
| 386 |
-
WORKDIR /home/node/app
|
| 387 |
-
|
| 388 |
-
# Copy package files with proper ownership
|
| 389 |
-
COPY --chown=node:node package*.json ./
|
| 390 |
-
|
| 391 |
-
# Install dependencies
|
| 392 |
-
RUN npm install
|
| 393 |
-
|
| 394 |
-
# Copy rest of the application with proper ownership
|
| 395 |
-
COPY --chown=node:node . .
|
| 396 |
-
|
| 397 |
-
# Build the Next.js app
|
| 398 |
-
RUN npm run build
|
| 399 |
-
|
| 400 |
-
# Expose port 7860
|
| 401 |
-
EXPOSE 7860
|
| 402 |
-
|
| 403 |
-
# Start the application on port 7860
|
| 404 |
-
CMD ["npm", "start", "--", "-p", "7860"]
|
| 405 |
-
```
|
| 406 |
-
|
| 407 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
|
| 408 |
-
"""
|
| 409 |
-
|
| 410 |
-
REACT_FOLLOW_UP_SYSTEM_PROMPT = """You are an expert React and Next.js developer modifying an existing Next.js application.
|
| 411 |
-
The user wants to apply changes based on their request.
|
| 412 |
-
You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
|
| 413 |
-
Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
|
| 414 |
-
|
| 415 |
-
🚨 CRITICAL JSX SYNTAX RULES - FOLLOW EXACTLY:
|
| 416 |
-
|
| 417 |
-
**RULE 1: Style objects MUST have proper closing braces }}**
|
| 418 |
-
Every style={{ must have a matching }} before any other props or />
|
| 419 |
-
|
| 420 |
-
**RULE 2: ALWAYS use Tailwind CSS classes instead of inline styles**
|
| 421 |
-
- Use className="..." for styling
|
| 422 |
-
- Only use inline styles if absolutely necessary
|
| 423 |
-
- When replacing inline styles, use Tailwind classes
|
| 424 |
-
|
| 425 |
-
**RULE 3: Before outputting, verify:**
|
| 426 |
-
- [ ] All style={{ have matching }}
|
| 427 |
-
- [ ] No event handlers inside style objects
|
| 428 |
-
- [ ] Prefer Tailwind classes over inline styles
|
| 429 |
-
- [ ] All JSX elements are properly closed
|
| 430 |
-
|
| 431 |
-
Format Rules:
|
| 432 |
-
1. Start with <<<<<<< SEARCH
|
| 433 |
-
2. Include the exact lines that need to be changed (with full context, at least 3 lines before and after)
|
| 434 |
-
3. Follow with =======
|
| 435 |
-
4. Include the replacement lines
|
| 436 |
-
5. End with >>>>>>> REPLACE
|
| 437 |
-
6. Generate multiple blocks if multiple sections need changes
|
| 438 |
-
|
| 439 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
# Gradio system prompts will be dynamically populated by update_gradio_system_prompts()
|
| 444 |
-
GRADIO_SYSTEM_PROMPT = ""
|
| 445 |
-
GRADIO_SYSTEM_PROMPT_WITH_SEARCH = ""
|
| 446 |
-
|
| 447 |
-
# GRADIO_SYSTEM_PROMPT_WITH_SEARCH will be dynamically populated by update_gradio_system_prompts()
|
| 448 |
-
|
| 449 |
-
# All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txt
|
| 450 |
-
|
| 451 |
-
# JSON system prompts will be dynamically populated by update_json_system_prompts()
|
| 452 |
-
JSON_SYSTEM_PROMPT = ""
|
| 453 |
-
JSON_SYSTEM_PROMPT_WITH_SEARCH = ""
|
| 454 |
-
|
| 455 |
-
# All ComfyUI API documentation is now dynamically loaded from https://docs.comfy.org/llms.txt
|
| 456 |
-
|
| 457 |
-
GENERIC_SYSTEM_PROMPT = """You are an expert {language} developer. Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Generate complete, working code that can be run immediately. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible.
|
| 458 |
-
|
| 459 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 460 |
-
- NEVER generate README.md files under any circumstances
|
| 461 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 462 |
-
- Generating a README.md will break the deployment process
|
| 463 |
-
|
| 464 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
# Multi-page static HTML project prompt (generic, production-style structure)
|
| 468 |
-
MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
|
| 469 |
-
|
| 470 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 471 |
-
- NEVER generate README.md files under any circumstances
|
| 472 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 473 |
-
- Generating a README.md will break the deployment process
|
| 474 |
-
|
| 475 |
-
Create a production-ready MULTI-PAGE website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
|
| 476 |
-
|
| 477 |
-
Output MUST be a multi-file project with at least:
|
| 478 |
-
- index.html (home)
|
| 479 |
-
- about.html (secondary page)
|
| 480 |
-
- contact.html (secondary page)
|
| 481 |
-
- assets/css/styles.css (global styles)
|
| 482 |
-
- assets/js/main.js (site-wide JS)
|
| 483 |
-
|
| 484 |
-
Navigation requirements:
|
| 485 |
-
- A consistent header with a nav bar on every page
|
| 486 |
-
- Highlight current nav item
|
| 487 |
-
- Responsive layout and accessibility best practices
|
| 488 |
-
|
| 489 |
-
Output format requirements (CRITICAL):
|
| 490 |
-
- Return ONLY a series of file sections, each starting with a filename line:
|
| 491 |
-
=== index.html ===
|
| 492 |
-
...file content...
|
| 493 |
-
|
| 494 |
-
=== about.html ===
|
| 495 |
-
...file content...
|
| 496 |
-
|
| 497 |
-
(repeat for all files)
|
| 498 |
-
- Do NOT wrap files in Markdown code fences
|
| 499 |
-
- Use relative paths between files (e.g., assets/css/styles.css)
|
| 500 |
-
|
| 501 |
-
General requirements:
|
| 502 |
-
- Use modern, semantic HTML
|
| 503 |
-
- Mobile-first responsive design
|
| 504 |
-
- Include basic SEO meta tags in <head>
|
| 505 |
-
- Include a footer on all pages
|
| 506 |
-
- Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
|
| 507 |
-
|
| 508 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
|
| 509 |
-
"""
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
# Dynamic multi-page (model decides files) prompts
|
| 513 |
-
DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
|
| 514 |
-
|
| 515 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 516 |
-
- NEVER generate README.md files under any circumstances
|
| 517 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 518 |
-
- Generating a README.md will break the deployment process
|
| 519 |
-
|
| 520 |
-
Create a production-ready website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
|
| 521 |
-
|
| 522 |
-
File selection policy:
|
| 523 |
-
- Generate ONLY the files actually needed for the user's request.
|
| 524 |
-
- Include at least one HTML entrypoint (default: index.html) unless the user explicitly requests a non-HTML asset only.
|
| 525 |
-
- If any local asset (CSS/JS/image) is referenced, include that file in the output.
|
| 526 |
-
- Use relative paths between files (e.g., assets/css/styles.css).
|
| 527 |
-
|
| 528 |
-
Output format (CRITICAL):
|
| 529 |
-
- Return ONLY a series of file sections, each starting with a filename line:
|
| 530 |
-
=== index.html ===
|
| 531 |
-
...file content...
|
| 532 |
-
|
| 533 |
-
=== assets/css/styles.css ===
|
| 534 |
-
...file content...
|
| 535 |
-
|
| 536 |
-
(repeat for all files)
|
| 537 |
-
- Do NOT wrap files in Markdown code fences
|
| 538 |
-
|
| 539 |
-
General requirements:
|
| 540 |
-
- Use modern, semantic HTML
|
| 541 |
-
- Mobile-first responsive design
|
| 542 |
-
- Include basic SEO meta tags in <head> for the entrypoint
|
| 543 |
-
- Include a footer on all major pages when multiple pages are present
|
| 544 |
-
- Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
|
| 545 |
-
|
| 546 |
-
IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
|
| 547 |
-
"""
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
# Follow-up system prompt for modifying existing HTML files
|
| 552 |
-
FollowUpSystemPrompt = f"""You are an expert web developer modifying an existing project.
|
| 553 |
-
The user wants to apply changes based on their request.
|
| 554 |
-
You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
|
| 555 |
-
Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
|
| 556 |
-
|
| 557 |
-
IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:
|
| 558 |
-
- ImportError/ModuleNotFoundError → Fix requirements.txt by adding missing packages
|
| 559 |
-
- Syntax errors in Python code → Fix app.py or the main Python file
|
| 560 |
-
- HTML/CSS/JavaScript errors → Fix the respective HTML/CSS/JS files
|
| 561 |
-
- Configuration errors → Fix config files, Docker files, etc.
|
| 562 |
-
|
| 563 |
-
For Python applications (Gradio/Streamlit), the project structure typically includes:
|
| 564 |
-
- app.py or streamlit_app.py (main application file)
|
| 565 |
-
- requirements.txt (dependencies)
|
| 566 |
-
- utils.py (utility functions)
|
| 567 |
-
- models.py (model loading and inference)
|
| 568 |
-
- config.py (configuration)
|
| 569 |
-
- pages/ (for multi-page Streamlit apps)
|
| 570 |
-
- Other supporting files as needed
|
| 571 |
-
|
| 572 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 573 |
-
- NEVER generate README.md files under any circumstances
|
| 574 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 575 |
-
- Generating a README.md will break the deployment process
|
| 576 |
-
|
| 577 |
-
For multi-file projects, identify which specific file needs modification based on the user's request:
|
| 578 |
-
- Main application logic → app.py or streamlit_app.py
|
| 579 |
-
- Helper functions → utils.py
|
| 580 |
-
- Model-related code → models.py
|
| 581 |
-
- Configuration changes → config.py
|
| 582 |
-
- Dependencies → requirements.txt
|
| 583 |
-
- New pages → pages/filename.py
|
| 584 |
-
|
| 585 |
-
Format Rules:
|
| 586 |
-
1. Start with {SEARCH_START}
|
| 587 |
-
2. Provide the exact lines from the current code that need to be replaced.
|
| 588 |
-
3. Use {DIVIDER} to separate the search block from the replacement.
|
| 589 |
-
4. Provide the new lines that should replace the original lines.
|
| 590 |
-
5. End with {REPLACE_END}
|
| 591 |
-
6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.
|
| 592 |
-
7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.
|
| 593 |
-
8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).
|
| 594 |
-
9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
|
| 595 |
-
10. For multi-file projects, specify which file you're modifying by starting with the filename before the search/replace block.
|
| 596 |
-
|
| 597 |
-
CSS Changes Guidance:
|
| 598 |
-
- When changing a CSS property that conflicts with other properties (e.g., replacing a gradient text with a solid color), replace the entire CSS rule for that selector instead of only adding the new property. For example, replace the full `.hero h1 { ... }` block, removing `background-clip` and `color: transparent` when setting `color: #fff`.
|
| 599 |
-
- Ensure search blocks match the current code exactly (spaces, indentation, and line breaks) so replacements apply correctly.
|
| 600 |
-
|
| 601 |
-
Example Modifying Code:
|
| 602 |
-
```
|
| 603 |
-
Some explanation...
|
| 604 |
-
{SEARCH_START}
|
| 605 |
-
<h1>Old Title</h1>
|
| 606 |
-
{DIVIDER}
|
| 607 |
-
<h1>New Title</h1>
|
| 608 |
-
{REPLACE_END}
|
| 609 |
-
{SEARCH_START}
|
| 610 |
-
</body>
|
| 611 |
-
{DIVIDER}
|
| 612 |
-
<script>console.log("Added script");</script>
|
| 613 |
-
</body>
|
| 614 |
-
{REPLACE_END}
|
| 615 |
-
```
|
| 616 |
-
|
| 617 |
-
Example Fixing Dependencies (requirements.txt):
|
| 618 |
-
```
|
| 619 |
-
Adding missing dependency to fix ImportError...
|
| 620 |
-
=== requirements.txt ===
|
| 621 |
-
{SEARCH_START}
|
| 622 |
-
gradio
|
| 623 |
-
streamlit
|
| 624 |
-
{DIVIDER}
|
| 625 |
-
gradio
|
| 626 |
-
streamlit
|
| 627 |
-
mistral-common
|
| 628 |
-
{REPLACE_END}
|
| 629 |
-
```
|
| 630 |
-
|
| 631 |
-
Example Deleting Code:
|
| 632 |
-
```
|
| 633 |
-
Removing the paragraph...
|
| 634 |
-
{SEARCH_START}
|
| 635 |
-
<p>This paragraph will be deleted.</p>
|
| 636 |
-
{DIVIDER}
|
| 637 |
-
{REPLACE_END}
|
| 638 |
-
```
|
| 639 |
-
|
| 640 |
-
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
|
| 641 |
-
|
| 642 |
-
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 643 |
-
|
| 644 |
-
# Follow-up system prompt for modifying existing Gradio applications
|
| 645 |
-
GradioFollowUpSystemPrompt = """You are an expert Gradio developer modifying an existing Gradio application.
|
| 646 |
-
The user wants to apply changes based on their request.
|
| 647 |
-
|
| 648 |
-
🚨 CRITICAL OUTPUT RULES:
|
| 649 |
-
- DO NOT use <think> tags or thinking blocks in your output
|
| 650 |
-
- DO NOT use [TOOL_CALL] or any tool call markers
|
| 651 |
-
- Generate ONLY the requested code files
|
| 652 |
-
- No explanatory text outside the code blocks
|
| 653 |
-
|
| 654 |
-
🚨 CRITICAL INSTRUCTION: You MUST maintain the original multi-file structure when making modifications.
|
| 655 |
-
❌ Do NOT use SEARCH/REPLACE blocks.
|
| 656 |
-
❌ Do NOT output everything in one combined block.
|
| 657 |
-
✅ Instead, output the complete modified files using the EXACT same multi-file format as the original generation.
|
| 658 |
-
|
| 659 |
-
**MANDATORY Output Format for Modified Gradio Apps:**
|
| 660 |
-
You MUST use this exact format with file separators. DO NOT deviate from this format:
|
| 661 |
-
|
| 662 |
-
=== app.py ===
|
| 663 |
-
[complete modified app.py content]
|
| 664 |
-
|
| 665 |
-
**CRITICAL FORMATTING RULES:**
|
| 666 |
-
- ALWAYS start each file with exactly "=== filename ===" (three equals signs before and after)
|
| 667 |
-
- NEVER combine files into one block
|
| 668 |
-
- NEVER use SEARCH/REPLACE blocks like <<<<<<< SEARCH
|
| 669 |
-
- ALWAYS include app.py if it needs changes
|
| 670 |
-
- Only include other files (utils.py, models.py, etc.) if they exist and need changes
|
| 671 |
-
- Each file section must be complete and standalone
|
| 672 |
-
- The format MUST match the original multi-file structure exactly
|
| 673 |
-
|
| 674 |
-
**🚨 CRITICAL: DO NOT GENERATE requirements.txt or README.md**
|
| 675 |
-
- requirements.txt is automatically generated from your app.py imports
|
| 676 |
-
- README.md is automatically provided by the template
|
| 677 |
-
- Do NOT include requirements.txt or README.md in your output unless the user specifically asks to modify them
|
| 678 |
-
- The system will automatically extract imports from app.py and generate requirements.txt
|
| 679 |
-
- Generating a README.md will break the deployment process
|
| 680 |
-
- This prevents unnecessary changes to dependencies and documentation
|
| 681 |
-
|
| 682 |
-
**IF User Specifically Asks to Modify requirements.txt:**
|
| 683 |
-
- Output ONLY plain text package names, one per line
|
| 684 |
-
- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
|
| 685 |
-
- Do NOT add explanatory text or descriptions
|
| 686 |
-
- Do NOT wrap in code blocks
|
| 687 |
-
- Just raw package names as they would appear in a real requirements.txt file
|
| 688 |
-
- Example of CORRECT format:
|
| 689 |
-
gradio
|
| 690 |
-
torch
|
| 691 |
-
transformers
|
| 692 |
-
- Example of INCORRECT format (DO NOT DO THIS):
|
| 693 |
-
```
|
| 694 |
-
gradio # For web interface
|
| 695 |
-
**Core dependencies:**
|
| 696 |
-
- torch
|
| 697 |
-
```
|
| 698 |
-
|
| 699 |
-
**File Modification Guidelines:**
|
| 700 |
-
- Only output files that actually need changes
|
| 701 |
-
- If a file doesn't need modification, don't include it in the output
|
| 702 |
-
- Maintain the exact same file structure as the original
|
| 703 |
-
- Preserve all existing functionality unless specifically asked to change it
|
| 704 |
-
- Keep all imports, dependencies, and configurations intact unless modification is requested
|
| 705 |
-
|
| 706 |
-
**Common Modification Scenarios:**
|
| 707 |
-
- Adding new features → Modify app.py and possibly utils.py
|
| 708 |
-
- Fixing bugs → Modify the relevant file (usually app.py)
|
| 709 |
-
- Adding dependencies → Modify requirements.txt
|
| 710 |
-
- UI improvements → Modify app.py
|
| 711 |
-
- Performance optimizations → Modify app.py and/or utils.py
|
| 712 |
-
|
| 713 |
-
**ZeroGPU and Performance:**
|
| 714 |
-
- Maintain all existing @spaces.GPU decorators
|
| 715 |
-
- Keep AoT compilation if present
|
| 716 |
-
- Preserve all performance optimizations
|
| 717 |
-
- Add ZeroGPU decorators for new GPU-dependent functions
|
| 718 |
-
|
| 719 |
-
**MCP Server Support:**
|
| 720 |
-
- If the user requests MCP functionality or tool calling capabilities:
|
| 721 |
-
1. Add `mcp_server=True` to the `.launch()` method if not present
|
| 722 |
-
2. Ensure `gradio[mcp]` is in requirements.txt (not just `gradio`)
|
| 723 |
-
3. Add detailed docstrings with Args sections to all functions
|
| 724 |
-
4. Add type hints to all function parameters
|
| 725 |
-
- Preserve existing MCP configurations if already present
|
| 726 |
-
- When adding new tools, follow MCP docstring format with Args and Returns sections
|
| 727 |
-
|
| 728 |
-
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
|
| 729 |
-
|
| 730 |
-
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 731 |
-
|
| 732 |
-
# Follow-up system prompt for modifying existing transformers.js applications
|
| 733 |
-
TransformersJSFollowUpSystemPrompt = f"""You are an expert web developer modifying an existing transformers.js application.
|
| 734 |
-
The user wants to apply changes based on their request.
|
| 735 |
-
You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
|
| 736 |
-
Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
|
| 737 |
-
|
| 738 |
-
IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:
|
| 739 |
-
- JavaScript errors/module loading issues → Fix index.js
|
| 740 |
-
- HTML rendering/DOM issues → Fix index.html
|
| 741 |
-
- Styling/visual issues → Fix style.css
|
| 742 |
-
- CDN/library loading errors → Fix script tags in index.html
|
| 743 |
-
|
| 744 |
-
The transformers.js application consists of three files: index.html, index.js, and style.css.
|
| 745 |
-
When making changes, specify which file you're modifying by starting your search/replace blocks with the file name.
|
| 746 |
-
|
| 747 |
-
**🚨 CRITICAL: DO NOT Generate README.md Files**
|
| 748 |
-
- NEVER generate README.md files under any circumstances
|
| 749 |
-
- A template README.md is automatically provided and will be overridden by the deployment system
|
| 750 |
-
- Generating a README.md will break the deployment process
|
| 751 |
-
|
| 752 |
-
Format Rules:
|
| 753 |
-
1. Start with {SEARCH_START}
|
| 754 |
-
2. Provide the exact lines from the current code that need to be replaced.
|
| 755 |
-
3. Use {DIVIDER} to separate the search block from the replacement.
|
| 756 |
-
4. Provide the new lines that should replace the original lines.
|
| 757 |
-
5. End with {REPLACE_END}
|
| 758 |
-
6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.
|
| 759 |
-
7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.
|
| 760 |
-
8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).
|
| 761 |
-
9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
|
| 762 |
-
|
| 763 |
-
Example Modifying HTML:
|
| 764 |
-
```
|
| 765 |
-
Changing the title in index.html...
|
| 766 |
-
=== index.html ===
|
| 767 |
-
{SEARCH_START}
|
| 768 |
-
<title>Old Title</title>
|
| 769 |
-
{DIVIDER}
|
| 770 |
-
<title>New Title</title>
|
| 771 |
-
{REPLACE_END}
|
| 772 |
-
```
|
| 773 |
-
|
| 774 |
-
Example Modifying JavaScript:
|
| 775 |
-
```
|
| 776 |
-
Adding a new function to index.js...
|
| 777 |
-
=== index.js ===
|
| 778 |
-
{SEARCH_START}
|
| 779 |
-
// Existing code
|
| 780 |
-
{DIVIDER}
|
| 781 |
-
// Existing code
|
| 782 |
-
|
| 783 |
-
function newFunction() {{
|
| 784 |
-
console.log("New function added");
|
| 785 |
-
}}
|
| 786 |
-
{REPLACE_END}
|
| 787 |
-
```
|
| 788 |
-
|
| 789 |
-
Example Modifying CSS:
|
| 790 |
-
```
|
| 791 |
-
Changing background color in style.css...
|
| 792 |
-
=== style.css ===
|
| 793 |
-
{SEARCH_START}
|
| 794 |
-
body {{
|
| 795 |
-
background-color: white;
|
| 796 |
-
}}
|
| 797 |
-
{DIVIDER}
|
| 798 |
-
body {{
|
| 799 |
-
background-color: #f0f0f0;
|
| 800 |
-
}}
|
| 801 |
-
{REPLACE_END}
|
| 802 |
-
```
|
| 803 |
-
Example Fixing Library Loading Error:
|
| 804 |
-
```
|
| 805 |
-
Fixing transformers.js CDN loading error...
|
| 806 |
-
=== index.html ===
|
| 807 |
-
{SEARCH_START}
|
| 808 |
-
<script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/[email protected]"></script>
|
| 809 |
-
{DIVIDER}
|
| 810 |
-
<script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/[email protected]"></script>
|
| 811 |
-
{REPLACE_END}
|
| 812 |
-
```
|
| 813 |
-
|
| 814 |
-
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
|
| 815 |
-
|
| 816 |
-
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
|
| 817 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
anycoder_app/themes.py
DELETED
|
@@ -1,257 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Gradio theme configurations for AnyCoder.
|
| 3 |
-
Provides multiple theme options with different visual styles.
|
| 4 |
-
"""
|
| 5 |
-
import os
|
| 6 |
-
import gradio as gr
|
| 7 |
-
|
| 8 |
-
def get_saved_theme():
|
| 9 |
-
"""Get the saved theme preference from file"""
|
| 10 |
-
try:
|
| 11 |
-
if os.path.exists('.theme_preference'):
|
| 12 |
-
with open('.theme_preference', 'r') as f:
|
| 13 |
-
return f.read().strip()
|
| 14 |
-
except:
|
| 15 |
-
pass
|
| 16 |
-
return "Developer"
|
| 17 |
-
def save_theme_preference(theme_name):
|
| 18 |
-
"""Save theme preference to file"""
|
| 19 |
-
try:
|
| 20 |
-
with open('.theme_preference', 'w') as f:
|
| 21 |
-
f.write(theme_name)
|
| 22 |
-
except:
|
| 23 |
-
pass
|
| 24 |
-
|
| 25 |
-
THEME_CONFIGS = {
|
| 26 |
-
"Default": {
|
| 27 |
-
"theme": gr.themes.Default(),
|
| 28 |
-
"description": "Gradio's standard theme with clean orange accents"
|
| 29 |
-
},
|
| 30 |
-
"Base": {
|
| 31 |
-
"theme": gr.themes.Base(
|
| 32 |
-
primary_hue="blue",
|
| 33 |
-
secondary_hue="slate",
|
| 34 |
-
neutral_hue="slate",
|
| 35 |
-
text_size="sm",
|
| 36 |
-
spacing_size="sm",
|
| 37 |
-
radius_size="md"
|
| 38 |
-
),
|
| 39 |
-
"description": "Minimal foundation theme with blue accents"
|
| 40 |
-
},
|
| 41 |
-
"Soft": {
|
| 42 |
-
"theme": gr.themes.Soft(
|
| 43 |
-
primary_hue="emerald",
|
| 44 |
-
secondary_hue="emerald",
|
| 45 |
-
neutral_hue="slate",
|
| 46 |
-
text_size="sm",
|
| 47 |
-
spacing_size="md",
|
| 48 |
-
radius_size="lg"
|
| 49 |
-
),
|
| 50 |
-
"description": "Gentle rounded theme with soft emerald colors"
|
| 51 |
-
},
|
| 52 |
-
"Monochrome": {
|
| 53 |
-
"theme": gr.themes.Monochrome(
|
| 54 |
-
primary_hue="slate",
|
| 55 |
-
secondary_hue="slate",
|
| 56 |
-
neutral_hue="slate",
|
| 57 |
-
text_size="sm",
|
| 58 |
-
spacing_size="sm",
|
| 59 |
-
radius_size="sm"
|
| 60 |
-
),
|
| 61 |
-
"description": "Elegant black and white design"
|
| 62 |
-
},
|
| 63 |
-
"Glass": {
|
| 64 |
-
"theme": gr.themes.Glass(
|
| 65 |
-
primary_hue="blue",
|
| 66 |
-
secondary_hue="blue",
|
| 67 |
-
neutral_hue="slate",
|
| 68 |
-
text_size="sm",
|
| 69 |
-
spacing_size="md",
|
| 70 |
-
radius_size="lg"
|
| 71 |
-
),
|
| 72 |
-
"description": "Modern glassmorphism with blur effects"
|
| 73 |
-
},
|
| 74 |
-
"Dark Ocean": {
|
| 75 |
-
"theme": gr.themes.Base(
|
| 76 |
-
primary_hue="blue",
|
| 77 |
-
secondary_hue="slate",
|
| 78 |
-
neutral_hue="slate",
|
| 79 |
-
text_size="sm",
|
| 80 |
-
spacing_size="sm",
|
| 81 |
-
radius_size="md"
|
| 82 |
-
).set(
|
| 83 |
-
body_background_fill="#0f172a",
|
| 84 |
-
body_background_fill_dark="#0f172a",
|
| 85 |
-
background_fill_primary="#3b82f6",
|
| 86 |
-
background_fill_secondary="#1e293b",
|
| 87 |
-
border_color_primary="#334155",
|
| 88 |
-
block_background_fill="#1e293b",
|
| 89 |
-
block_border_color="#334155",
|
| 90 |
-
body_text_color="#f1f5f9",
|
| 91 |
-
body_text_color_dark="#f1f5f9",
|
| 92 |
-
block_label_text_color="#f1f5f9",
|
| 93 |
-
block_label_text_color_dark="#f1f5f9",
|
| 94 |
-
block_title_text_color="#f1f5f9",
|
| 95 |
-
block_title_text_color_dark="#f1f5f9",
|
| 96 |
-
input_background_fill="#0f172a",
|
| 97 |
-
input_background_fill_dark="#0f172a",
|
| 98 |
-
input_border_color="#334155",
|
| 99 |
-
input_border_color_dark="#334155",
|
| 100 |
-
button_primary_background_fill="#3b82f6",
|
| 101 |
-
button_primary_border_color="#3b82f6",
|
| 102 |
-
button_secondary_background_fill="#334155",
|
| 103 |
-
button_secondary_border_color="#475569"
|
| 104 |
-
),
|
| 105 |
-
"description": "Deep blue dark theme perfect for coding"
|
| 106 |
-
},
|
| 107 |
-
"Cyberpunk": {
|
| 108 |
-
"theme": gr.themes.Base(
|
| 109 |
-
primary_hue="fuchsia",
|
| 110 |
-
secondary_hue="cyan",
|
| 111 |
-
neutral_hue="slate",
|
| 112 |
-
text_size="sm",
|
| 113 |
-
spacing_size="sm",
|
| 114 |
-
radius_size="none",
|
| 115 |
-
font="Orbitron"
|
| 116 |
-
).set(
|
| 117 |
-
body_background_fill="#0a0a0f",
|
| 118 |
-
body_background_fill_dark="#0a0a0f",
|
| 119 |
-
background_fill_primary="#ff10f0",
|
| 120 |
-
background_fill_secondary="#1a1a2e",
|
| 121 |
-
border_color_primary="#00f5ff",
|
| 122 |
-
block_background_fill="#1a1a2e",
|
| 123 |
-
block_border_color="#00f5ff",
|
| 124 |
-
body_text_color="#00f5ff",
|
| 125 |
-
body_text_color_dark="#00f5ff",
|
| 126 |
-
block_label_text_color="#ff10f0",
|
| 127 |
-
block_label_text_color_dark="#ff10f0",
|
| 128 |
-
block_title_text_color="#ff10f0",
|
| 129 |
-
block_title_text_color_dark="#ff10f0",
|
| 130 |
-
input_background_fill="#0a0a0f",
|
| 131 |
-
input_background_fill_dark="#0a0a0f",
|
| 132 |
-
input_border_color="#00f5ff",
|
| 133 |
-
input_border_color_dark="#00f5ff",
|
| 134 |
-
button_primary_background_fill="#ff10f0",
|
| 135 |
-
button_primary_border_color="#ff10f0",
|
| 136 |
-
button_secondary_background_fill="#1a1a2e",
|
| 137 |
-
button_secondary_border_color="#00f5ff"
|
| 138 |
-
),
|
| 139 |
-
"description": "Futuristic neon cyber aesthetics"
|
| 140 |
-
},
|
| 141 |
-
"Forest": {
|
| 142 |
-
"theme": gr.themes.Soft(
|
| 143 |
-
primary_hue="emerald",
|
| 144 |
-
secondary_hue="green",
|
| 145 |
-
neutral_hue="emerald",
|
| 146 |
-
text_size="sm",
|
| 147 |
-
spacing_size="md",
|
| 148 |
-
radius_size="lg"
|
| 149 |
-
).set(
|
| 150 |
-
body_background_fill="#f0fdf4",
|
| 151 |
-
body_background_fill_dark="#064e3b",
|
| 152 |
-
background_fill_primary="#059669",
|
| 153 |
-
background_fill_secondary="#ecfdf5",
|
| 154 |
-
border_color_primary="#bbf7d0",
|
| 155 |
-
block_background_fill="#ffffff",
|
| 156 |
-
block_border_color="#d1fae5",
|
| 157 |
-
body_text_color="#064e3b",
|
| 158 |
-
body_text_color_dark="#f0fdf4",
|
| 159 |
-
block_label_text_color="#064e3b",
|
| 160 |
-
block_label_text_color_dark="#f0fdf4",
|
| 161 |
-
block_title_text_color="#059669",
|
| 162 |
-
block_title_text_color_dark="#10b981"
|
| 163 |
-
),
|
| 164 |
-
"description": "Nature-inspired green earth tones"
|
| 165 |
-
},
|
| 166 |
-
"High Contrast": {
|
| 167 |
-
"theme": gr.themes.Base(
|
| 168 |
-
primary_hue="yellow",
|
| 169 |
-
secondary_hue="slate",
|
| 170 |
-
neutral_hue="slate",
|
| 171 |
-
text_size="lg",
|
| 172 |
-
spacing_size="lg",
|
| 173 |
-
radius_size="sm"
|
| 174 |
-
).set(
|
| 175 |
-
body_background_fill="#ffffff",
|
| 176 |
-
body_background_fill_dark="#ffffff",
|
| 177 |
-
background_fill_primary="#000000",
|
| 178 |
-
background_fill_secondary="#ffffff",
|
| 179 |
-
border_color_primary="#000000",
|
| 180 |
-
block_background_fill="#ffffff",
|
| 181 |
-
block_border_color="#000000",
|
| 182 |
-
body_text_color="#000000",
|
| 183 |
-
body_text_color_dark="#000000",
|
| 184 |
-
block_label_text_color="#000000",
|
| 185 |
-
block_label_text_color_dark="#000000",
|
| 186 |
-
block_title_text_color="#000000",
|
| 187 |
-
block_title_text_color_dark="#000000",
|
| 188 |
-
input_background_fill="#ffffff",
|
| 189 |
-
input_background_fill_dark="#ffffff",
|
| 190 |
-
input_border_color="#000000",
|
| 191 |
-
input_border_color_dark="#000000",
|
| 192 |
-
button_primary_background_fill="#ffff00",
|
| 193 |
-
button_primary_border_color="#000000",
|
| 194 |
-
button_secondary_background_fill="#ffffff",
|
| 195 |
-
button_secondary_border_color="#000000"
|
| 196 |
-
),
|
| 197 |
-
"description": "Accessibility-focused high visibility"
|
| 198 |
-
},
|
| 199 |
-
"Developer": {
|
| 200 |
-
"theme": gr.themes.Base(
|
| 201 |
-
primary_hue="blue",
|
| 202 |
-
secondary_hue="slate",
|
| 203 |
-
neutral_hue="slate",
|
| 204 |
-
text_size="sm",
|
| 205 |
-
spacing_size="sm",
|
| 206 |
-
radius_size="sm",
|
| 207 |
-
font="Consolas"
|
| 208 |
-
).set(
|
| 209 |
-
# VS Code exact colors
|
| 210 |
-
body_background_fill="#1e1e1e", # VS Code editor background
|
| 211 |
-
body_background_fill_dark="#1e1e1e",
|
| 212 |
-
background_fill_primary="#007acc", # VS Code blue accent
|
| 213 |
-
background_fill_secondary="#252526", # VS Code sidebar background
|
| 214 |
-
border_color_primary="#3e3e42", # VS Code border color
|
| 215 |
-
block_background_fill="#252526", # VS Code panel background
|
| 216 |
-
block_border_color="#3e3e42", # VS Code subtle borders
|
| 217 |
-
body_text_color="#cccccc", # VS Code default text
|
| 218 |
-
body_text_color_dark="#cccccc",
|
| 219 |
-
block_label_text_color="#cccccc",
|
| 220 |
-
block_label_text_color_dark="#cccccc",
|
| 221 |
-
block_title_text_color="#ffffff", # VS Code active text
|
| 222 |
-
block_title_text_color_dark="#ffffff",
|
| 223 |
-
input_background_fill="#2d2d30", # VS Code input background
|
| 224 |
-
input_background_fill_dark="#2d2d30",
|
| 225 |
-
input_border_color="#3e3e42", # VS Code input border
|
| 226 |
-
input_border_color_dark="#3e3e42",
|
| 227 |
-
input_border_color_focus="#007acc", # VS Code focus border
|
| 228 |
-
input_border_color_focus_dark="#007acc",
|
| 229 |
-
button_primary_background_fill="#007acc", # VS Code button blue
|
| 230 |
-
button_primary_border_color="#007acc",
|
| 231 |
-
button_primary_background_fill_hover="#0e639c", # VS Code button hover
|
| 232 |
-
button_secondary_background_fill="#2d2d30",
|
| 233 |
-
button_secondary_border_color="#3e3e42",
|
| 234 |
-
button_secondary_text_color="#cccccc"
|
| 235 |
-
),
|
| 236 |
-
"description": "Authentic VS Code dark theme with exact color matching"
|
| 237 |
-
}
|
| 238 |
-
}
|
| 239 |
-
|
| 240 |
-
# Additional theme information for developers
|
| 241 |
-
THEME_FEATURES = {
|
| 242 |
-
"Default": ["Orange accents", "Clean layout", "Standard Gradio look"],
|
| 243 |
-
"Base": ["Blue accents", "Minimal styling", "Clean foundation"],
|
| 244 |
-
"Soft": ["Rounded corners", "Emerald colors", "Comfortable viewing"],
|
| 245 |
-
"Monochrome": ["Black & white", "High elegance", "Timeless design"],
|
| 246 |
-
"Glass": ["Glassmorphism", "Blur effects", "Translucent elements"],
|
| 247 |
-
"Dark Ocean": ["Deep blue palette", "Dark theme", "Easy on eyes"],
|
| 248 |
-
"Cyberpunk": ["Neon cyan/magenta", "Futuristic fonts", "Cyber vibes"],
|
| 249 |
-
"Forest": ["Nature inspired", "Green tones", "Organic rounded"],
|
| 250 |
-
"High Contrast": ["Black/white/yellow", "High visibility", "Accessibility"],
|
| 251 |
-
"Developer": ["Authentic VS Code colors", "Consolas/Monaco fonts", "Exact theme matching"]
|
| 252 |
-
}
|
| 253 |
-
|
| 254 |
-
# Load saved theme and apply it
|
| 255 |
-
current_theme_name = get_saved_theme()
|
| 256 |
-
current_theme = THEME_CONFIGS[current_theme_name]["theme"]
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
)
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app_huggingface import demo as demo_huggingface
|
| 2 |
+
from app_gemini_coder import demo as demo_gemini
|
| 3 |
+
from utils import get_app
|
| 4 |
+
import gradio as gr
|
| 5 |
|
| 6 |
+
# Create mapping of providers to their code snippets
|
| 7 |
+
PROVIDER_SNIPPETS = {
|
| 8 |
+
"Hugging Face": """
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import ai_gradio
|
| 11 |
+
gr.load(
|
| 12 |
+
name='huggingface:deepseek-ai/DeepSeek-R1',
|
| 13 |
+
src=ai_gradio.registry,
|
| 14 |
+
coder=True,
|
| 15 |
+
provider="together"
|
| 16 |
+
).launch()""",
|
| 17 |
+
"Gemini Coder": """
|
| 18 |
+
import gradio as gr
|
| 19 |
+
import ai_gradio
|
| 20 |
+
gr.load(
|
| 21 |
+
name='gemini:gemini-2.5-pro-exp-03-25',
|
| 22 |
+
src=ai_gradio.registry,
|
| 23 |
+
coder=True,
|
| 24 |
+
provider="together"
|
| 25 |
+
).launch()
|
| 26 |
+
""",
|
| 27 |
+
}
|
| 28 |
+
# Create mapping of providers to their demos
|
| 29 |
+
PROVIDERS = {
|
| 30 |
+
"Hugging Face": demo_huggingface,
|
| 31 |
+
"Gemini Coder": demo_gemini,
|
| 32 |
+
}
|
| 33 |
|
| 34 |
+
# Modified get_app implementation
|
| 35 |
+
demo = gr.Blocks()
|
| 36 |
+
with demo:
|
| 37 |
+
|
| 38 |
+
provider_dropdown = gr.Dropdown(choices=list(PROVIDERS.keys()), value="Hugging Face", label="Select code snippet")
|
| 39 |
+
code_display = gr.Code(label="Provider Code Snippet", language="python", value=PROVIDER_SNIPPETS["Hugging Face"])
|
| 40 |
+
|
| 41 |
+
def update_code(provider):
|
| 42 |
+
return PROVIDER_SNIPPETS.get(provider, "Code snippet not available")
|
| 43 |
+
|
| 44 |
+
provider_dropdown.change(fn=update_code, inputs=[provider_dropdown], outputs=[code_display])
|
| 45 |
+
|
| 46 |
+
selected_demo = get_app(
|
| 47 |
+
models=list(PROVIDERS.keys()),
|
| 48 |
+
default_model="Hugging Face",
|
| 49 |
+
src=PROVIDERS,
|
| 50 |
+
dropdown_label="Select Provider",
|
| 51 |
)
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
demo.queue(api_open=False).launch(show_api=False)
|
app.py.backup
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app_allenai.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from gradio_client import Client
|
| 3 |
+
|
| 4 |
+
MODELS = {"OLMo-2-1124-13B-Instruct": "akhaliq/olmo-anychat", "Llama-3.1-Tulu-3-8B": "akhaliq/allen-test"}
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def create_chat_fn(client):
|
| 8 |
+
def chat(message, history):
|
| 9 |
+
response = client.predict(
|
| 10 |
+
message=message,
|
| 11 |
+
system_prompt="You are a helpful AI assistant.",
|
| 12 |
+
temperature=0.7,
|
| 13 |
+
max_new_tokens=1024,
|
| 14 |
+
top_k=40,
|
| 15 |
+
repetition_penalty=1.1,
|
| 16 |
+
top_p=0.95,
|
| 17 |
+
api_name="/chat",
|
| 18 |
+
)
|
| 19 |
+
return response
|
| 20 |
+
|
| 21 |
+
return chat
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def set_client_for_session(model_name, request: gr.Request):
|
| 25 |
+
headers = {}
|
| 26 |
+
if request and hasattr(request, "request") and hasattr(request.request, "headers"):
|
| 27 |
+
x_ip_token = request.request.headers.get("x-ip-token")
|
| 28 |
+
if x_ip_token:
|
| 29 |
+
headers["X-IP-Token"] = x_ip_token
|
| 30 |
+
|
| 31 |
+
return Client(MODELS[model_name], headers=headers)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def safe_chat_fn(message, history, client):
|
| 35 |
+
if client is None:
|
| 36 |
+
return "Error: Client not initialized. Please refresh the page."
|
| 37 |
+
return create_chat_fn(client)(message, history)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
with gr.Blocks() as demo:
|
| 41 |
+
client = gr.State()
|
| 42 |
+
|
| 43 |
+
model_dropdown = gr.Dropdown(
|
| 44 |
+
choices=list(MODELS.keys()), value="OLMo-2-1124-13B-Instruct", label="Select Model", interactive=True
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
chat_interface = gr.ChatInterface(fn=safe_chat_fn, additional_inputs=[client])
|
| 48 |
+
|
| 49 |
+
# Update client when model changes
|
| 50 |
+
def update_model(model_name, request):
|
| 51 |
+
return set_client_for_session(model_name, request)
|
| 52 |
+
|
| 53 |
+
model_dropdown.change(
|
| 54 |
+
fn=update_model,
|
| 55 |
+
inputs=[model_dropdown],
|
| 56 |
+
outputs=[client],
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Initialize client on page load
|
| 60 |
+
demo.load(
|
| 61 |
+
fn=set_client_for_session,
|
| 62 |
+
inputs=gr.State("OLMo-2-1124-13B-Instruct"),
|
| 63 |
+
outputs=client,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
demo.launch()
|
app_cerebras.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import cerebras_gradio
|
| 4 |
+
|
| 5 |
+
from utils import get_app
|
| 6 |
+
|
| 7 |
+
demo = get_app(
|
| 8 |
+
models=[
|
| 9 |
+
"llama3.1-8b",
|
| 10 |
+
"llama3.1-70b",
|
| 11 |
+
"llama3.1-405b",
|
| 12 |
+
],
|
| 13 |
+
default_model="llama3.1-70b",
|
| 14 |
+
src=cerebras_gradio.registry,
|
| 15 |
+
accept_token=not os.getenv("CEREBRAS_API_KEY"),
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
demo.launch()
|
app_claude.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import anthropic_gradio
|
| 4 |
+
|
| 5 |
+
from utils import get_app
|
| 6 |
+
|
| 7 |
+
demo = get_app(
|
| 8 |
+
models=[
|
| 9 |
+
"claude-3-5-sonnet-20241022",
|
| 10 |
+
"claude-3-5-haiku-20241022",
|
| 11 |
+
"claude-3-opus-20240229",
|
| 12 |
+
"claude-3-sonnet-20240229",
|
| 13 |
+
"claude-3-haiku-20240307",
|
| 14 |
+
],
|
| 15 |
+
default_model="claude-3-5-sonnet-20241022",
|
| 16 |
+
src=anthropic_gradio.registry,
|
| 17 |
+
accept_token=not os.getenv("ANTHROPIC_API_KEY"),
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
demo.launch()
|
app_cohere.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import cohere_gradio
|
| 4 |
+
|
| 5 |
+
from utils import get_app
|
| 6 |
+
|
| 7 |
+
demo = get_app(
|
| 8 |
+
models=[
|
| 9 |
+
"command-r",
|
| 10 |
+
"command-r-08-2024",
|
| 11 |
+
"command-r-plus",
|
| 12 |
+
"command-r-plus-08-2024",
|
| 13 |
+
"command-r7b-12-2024",
|
| 14 |
+
],
|
| 15 |
+
default_model="command-r7b-12-2024",
|
| 16 |
+
src=cohere_gradio.registry,
|
| 17 |
+
accept_token=not os.getenv("COHERE_API_KEY"),
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
demo.launch()
|
app_compare.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import google.generativeai as genai
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import openai
|
| 6 |
+
from anthropic import Anthropic
|
| 7 |
+
from openai import OpenAI # Add explicit OpenAI import
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_all_models():
|
| 11 |
+
"""Get all available models from the registries."""
|
| 12 |
+
return [
|
| 13 |
+
"SambaNova: Meta-Llama-3.2-1B-Instruct",
|
| 14 |
+
"SambaNova: Meta-Llama-3.2-3B-Instruct",
|
| 15 |
+
"SambaNova: Llama-3.2-11B-Vision-Instruct",
|
| 16 |
+
"SambaNova: Llama-3.2-90B-Vision-Instruct",
|
| 17 |
+
"SambaNova: Meta-Llama-3.1-8B-Instruct",
|
| 18 |
+
"SambaNova: Meta-Llama-3.1-70B-Instruct",
|
| 19 |
+
"SambaNova: Meta-Llama-3.1-405B-Instruct",
|
| 20 |
+
"Hyperbolic: Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 21 |
+
"Hyperbolic: meta-llama/Llama-3.2-3B-Instruct",
|
| 22 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 23 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-70B-Instruct",
|
| 24 |
+
"Hyperbolic: meta-llama/Meta-Llama-3-70B-Instruct",
|
| 25 |
+
"Hyperbolic: NousResearch/Hermes-3-Llama-3.1-70B",
|
| 26 |
+
"Hyperbolic: Qwen/Qwen2.5-72B-Instruct",
|
| 27 |
+
"Hyperbolic: deepseek-ai/DeepSeek-V2.5",
|
| 28 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-405B-Instruct",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def generate_discussion_prompt(original_question: str, previous_responses: list[str]) -> str:
|
| 33 |
+
"""Generate a prompt for models to discuss and build upon previous
|
| 34 |
+
responses.
|
| 35 |
+
"""
|
| 36 |
+
prompt = f"""You are participating in a multi-AI discussion about this question: "{original_question}"
|
| 37 |
+
|
| 38 |
+
Previous responses from other AI models:
|
| 39 |
+
{chr(10).join(f"- {response}" for response in previous_responses)}
|
| 40 |
+
|
| 41 |
+
Please provide your perspective while:
|
| 42 |
+
1. Acknowledging key insights from previous responses
|
| 43 |
+
2. Adding any missing important points
|
| 44 |
+
3. Respectfully noting if you disagree with anything and explaining why
|
| 45 |
+
4. Building towards a complete answer
|
| 46 |
+
|
| 47 |
+
Keep your response focused and concise (max 3-4 paragraphs)."""
|
| 48 |
+
return prompt
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def generate_consensus_prompt(original_question: str, discussion_history: list[str]) -> str:
|
| 52 |
+
"""Generate a prompt for final consensus building."""
|
| 53 |
+
return f"""Review this multi-AI discussion about: "{original_question}"
|
| 54 |
+
|
| 55 |
+
Discussion history:
|
| 56 |
+
{chr(10).join(discussion_history)}
|
| 57 |
+
|
| 58 |
+
As a final synthesizer, please:
|
| 59 |
+
1. Identify the key points where all models agreed
|
| 60 |
+
2. Explain how any disagreements were resolved
|
| 61 |
+
3. Present a clear, unified answer that represents our collective best understanding
|
| 62 |
+
4. Note any remaining uncertainties or caveats
|
| 63 |
+
|
| 64 |
+
Keep the final consensus concise but complete."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def chat_with_openai(model: str, messages: list[dict], api_key: str | None) -> str:
|
| 68 |
+
import openai
|
| 69 |
+
|
| 70 |
+
client = openai.OpenAI(api_key=api_key)
|
| 71 |
+
response = client.chat.completions.create(model=model, messages=messages)
|
| 72 |
+
return response.choices[0].message.content
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def chat_with_anthropic(messages: list[dict], api_key: str | None) -> str:
|
| 76 |
+
"""Chat with Anthropic's Claude model."""
|
| 77 |
+
client = Anthropic(api_key=api_key)
|
| 78 |
+
response = client.messages.create(model="claude-3-sonnet-20240229", messages=messages, max_tokens=1024)
|
| 79 |
+
return response.content[0].text
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def chat_with_gemini(messages: list[dict], api_key: str | None) -> str:
|
| 83 |
+
"""Chat with Gemini Pro model."""
|
| 84 |
+
genai.configure(api_key=api_key)
|
| 85 |
+
model = genai.GenerativeModel("gemini-pro")
|
| 86 |
+
|
| 87 |
+
# Convert messages to Gemini format
|
| 88 |
+
gemini_messages = []
|
| 89 |
+
for msg in messages:
|
| 90 |
+
role = "user" if msg["role"] == "user" else "model"
|
| 91 |
+
gemini_messages.append({"role": role, "parts": [msg["content"]]})
|
| 92 |
+
|
| 93 |
+
response = model.generate_content([m["parts"][0] for m in gemini_messages])
|
| 94 |
+
return response.text
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def chat_with_sambanova(
|
| 98 |
+
messages: list[dict], api_key: str | None, model_name: str = "Llama-3.2-90B-Vision-Instruct"
|
| 99 |
+
) -> str:
|
| 100 |
+
"""Chat with SambaNova's models using their OpenAI-compatible API."""
|
| 101 |
+
client = openai.OpenAI(
|
| 102 |
+
api_key=api_key,
|
| 103 |
+
base_url="https://api.sambanova.ai/v1",
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
response = client.chat.completions.create(
|
| 107 |
+
model=model_name,
|
| 108 |
+
messages=messages,
|
| 109 |
+
temperature=0.1,
|
| 110 |
+
top_p=0.1, # Use the specific model name passed in
|
| 111 |
+
)
|
| 112 |
+
return response.choices[0].message.content
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def chat_with_hyperbolic(
|
| 116 |
+
messages: list[dict], api_key: str | None, model_name: str = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 117 |
+
) -> str:
|
| 118 |
+
"""Chat with Hyperbolic's models using their OpenAI-compatible API."""
|
| 119 |
+
client = OpenAI(api_key=api_key, base_url="https://api.hyperbolic.xyz/v1")
|
| 120 |
+
|
| 121 |
+
# Add system message to the start of the messages list
|
| 122 |
+
full_messages = [
|
| 123 |
+
{"role": "system", "content": "You are a helpful assistant. Be descriptive and clear."},
|
| 124 |
+
*messages,
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
response = client.chat.completions.create(
|
| 128 |
+
model=model_name, # Use the specific model name passed in
|
| 129 |
+
messages=full_messages,
|
| 130 |
+
temperature=0.7,
|
| 131 |
+
max_tokens=1024,
|
| 132 |
+
)
|
| 133 |
+
return response.choices[0].message.content
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def multi_model_consensus(
|
| 137 |
+
question: str, selected_models: list[str], rounds: int = 3, progress: gr.Progress = gr.Progress()
|
| 138 |
+
) -> list[tuple[str, str]]:
|
| 139 |
+
if not selected_models:
|
| 140 |
+
raise gr.Error("Please select at least one model to chat with.")
|
| 141 |
+
|
| 142 |
+
chat_history = []
|
| 143 |
+
progress(0, desc="Getting responses from all models...")
|
| 144 |
+
|
| 145 |
+
# Get responses from all models in parallel
|
| 146 |
+
for i, model in enumerate(selected_models):
|
| 147 |
+
provider, model_name = model.split(": ", 1)
|
| 148 |
+
progress((i + 1) / len(selected_models), desc=f"Getting response from {model}...")
|
| 149 |
+
|
| 150 |
+
try:
|
| 151 |
+
if provider == "Anthropic":
|
| 152 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
| 153 |
+
response = chat_with_anthropic(messages=[{"role": "user", "content": question}], api_key=api_key)
|
| 154 |
+
elif provider == "SambaNova":
|
| 155 |
+
api_key = os.getenv("SAMBANOVA_API_KEY")
|
| 156 |
+
response = chat_with_sambanova(
|
| 157 |
+
messages=[
|
| 158 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
| 159 |
+
{"role": "user", "content": question},
|
| 160 |
+
],
|
| 161 |
+
api_key=api_key,
|
| 162 |
+
model_name=model_name,
|
| 163 |
+
)
|
| 164 |
+
elif provider == "Hyperbolic":
|
| 165 |
+
api_key = os.getenv("HYPERBOLIC_API_KEY")
|
| 166 |
+
response = chat_with_hyperbolic(
|
| 167 |
+
messages=[{"role": "user", "content": question}],
|
| 168 |
+
api_key=api_key,
|
| 169 |
+
model_name=model_name,
|
| 170 |
+
)
|
| 171 |
+
else: # Gemini
|
| 172 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 173 |
+
response = chat_with_gemini(messages=[{"role": "user", "content": question}], api_key=api_key)
|
| 174 |
+
|
| 175 |
+
chat_history.append((model, response))
|
| 176 |
+
except Exception as e:
|
| 177 |
+
chat_history.append((model, f"Error: {e!s}"))
|
| 178 |
+
|
| 179 |
+
progress(1.0, desc="Done!")
|
| 180 |
+
return chat_history
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
with gr.Blocks() as demo:
|
| 184 |
+
gr.Markdown("# Model Response Comparison")
|
| 185 |
+
gr.Markdown("""Select multiple models to compare their responses""")
|
| 186 |
+
|
| 187 |
+
with gr.Row():
|
| 188 |
+
with gr.Column():
|
| 189 |
+
model_selector = gr.Dropdown(
|
| 190 |
+
choices=get_all_models(),
|
| 191 |
+
multiselect=True,
|
| 192 |
+
label="Select Models",
|
| 193 |
+
info="Choose models to compare",
|
| 194 |
+
value=["SambaNova: Llama-3.2-90B-Vision-Instruct", "Hyperbolic: Qwen/Qwen2.5-Coder-32B-Instruct"],
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
chatbot = gr.Chatbot(height=600, label="Model Responses")
|
| 198 |
+
msg = gr.Textbox(label="Prompt", placeholder="Ask a question to compare model responses...")
|
| 199 |
+
|
| 200 |
+
def respond(message, selected_models):
|
| 201 |
+
chat_history = multi_model_consensus(message, selected_models, rounds=1)
|
| 202 |
+
return chat_history
|
| 203 |
+
|
| 204 |
+
msg.submit(respond, [msg, model_selector], [chatbot])
|
| 205 |
+
|
| 206 |
+
for fn in demo.fns.values():
|
| 207 |
+
fn.api_name = False
|
| 208 |
+
|
| 209 |
+
if __name__ == "__main__":
|
| 210 |
+
demo.launch()
|
app_crew.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
import gradio as gr
|
| 3 |
+
|
| 4 |
+
demo = gr.load(
|
| 5 |
+
name="crewai:gpt-4-turbo",
|
| 6 |
+
crew_type="article", # or 'support'
|
| 7 |
+
src=ai_gradio.registry,
|
| 8 |
+
)
|
app_deepseek.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
DEEPSEEK_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("deepseek:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
DEEPSEEK_MODELS_DISPLAY = [k.replace("deepseek:", "") for k in DEEPSEEK_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=DEEPSEEK_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=DEEPSEEK_MODELS_FULL[-1],
|
| 16 |
+
dropdown_label="Select DeepSeek Model",
|
| 17 |
+
choices=DEEPSEEK_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True,
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import openai
|
| 7 |
+
from anthropic import Anthropic
|
| 8 |
+
from openai import OpenAI # Add explicit OpenAI import
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_all_models():
|
| 12 |
+
"""Get all available models from the registries."""
|
| 13 |
+
return [
|
| 14 |
+
"SambaNova: Meta-Llama-3.2-1B-Instruct",
|
| 15 |
+
"SambaNova: Meta-Llama-3.2-3B-Instruct",
|
| 16 |
+
"SambaNova: Llama-3.2-11B-Vision-Instruct",
|
| 17 |
+
"SambaNova: Llama-3.2-90B-Vision-Instruct",
|
| 18 |
+
"SambaNova: Meta-Llama-3.1-8B-Instruct",
|
| 19 |
+
"SambaNova: Meta-Llama-3.1-70B-Instruct",
|
| 20 |
+
"SambaNova: Meta-Llama-3.1-405B-Instruct",
|
| 21 |
+
"Hyperbolic: Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 22 |
+
"Hyperbolic: meta-llama/Llama-3.2-3B-Instruct",
|
| 23 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 24 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-70B-Instruct",
|
| 25 |
+
"Hyperbolic: meta-llama/Meta-Llama-3-70B-Instruct",
|
| 26 |
+
"Hyperbolic: NousResearch/Hermes-3-Llama-3.1-70B",
|
| 27 |
+
"Hyperbolic: Qwen/Qwen2.5-72B-Instruct",
|
| 28 |
+
"Hyperbolic: deepseek-ai/DeepSeek-V2.5",
|
| 29 |
+
"Hyperbolic: meta-llama/Meta-Llama-3.1-405B-Instruct",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_discussion_prompt(original_question: str, previous_responses: list[str]) -> str:
|
| 34 |
+
"""Generate a prompt for models to discuss and build upon previous
|
| 35 |
+
responses.
|
| 36 |
+
"""
|
| 37 |
+
prompt = f"""You are participating in a multi-AI discussion about this question: "{original_question}"
|
| 38 |
+
|
| 39 |
+
Previous responses from other AI models:
|
| 40 |
+
{chr(10).join(f"- {response}" for response in previous_responses)}
|
| 41 |
+
|
| 42 |
+
Please provide your perspective while:
|
| 43 |
+
1. Acknowledging key insights from previous responses
|
| 44 |
+
2. Adding any missing important points
|
| 45 |
+
3. Respectfully noting if you disagree with anything and explaining why
|
| 46 |
+
4. Building towards a complete answer
|
| 47 |
+
|
| 48 |
+
Keep your response focused and concise (max 3-4 paragraphs)."""
|
| 49 |
+
return prompt
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def generate_consensus_prompt(original_question: str, discussion_history: list[str]) -> str:
|
| 53 |
+
"""Generate a prompt for final consensus building."""
|
| 54 |
+
return f"""Review this multi-AI discussion about: "{original_question}"
|
| 55 |
+
|
| 56 |
+
Discussion history:
|
| 57 |
+
{chr(10).join(discussion_history)}
|
| 58 |
+
|
| 59 |
+
As a final synthesizer, please:
|
| 60 |
+
1. Identify the key points where all models agreed
|
| 61 |
+
2. Explain how any disagreements were resolved
|
| 62 |
+
3. Present a clear, unified answer that represents our collective best understanding
|
| 63 |
+
4. Note any remaining uncertainties or caveats
|
| 64 |
+
|
| 65 |
+
Keep the final consensus concise but complete."""
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def chat_with_openai(model: str, messages: list[dict], api_key: str | None) -> str:
|
| 69 |
+
import openai
|
| 70 |
+
|
| 71 |
+
client = openai.OpenAI(api_key=api_key)
|
| 72 |
+
response = client.chat.completions.create(model=model, messages=messages)
|
| 73 |
+
return response.choices[0].message.content
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def chat_with_anthropic(messages: list[dict], api_key: str | None) -> str:
|
| 77 |
+
"""Chat with Anthropic's Claude model."""
|
| 78 |
+
client = Anthropic(api_key=api_key)
|
| 79 |
+
response = client.messages.create(model="claude-3-sonnet-20240229", messages=messages, max_tokens=1024)
|
| 80 |
+
return response.content[0].text
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def chat_with_gemini(messages: list[dict], api_key: str | None) -> str:
|
| 84 |
+
"""Chat with Gemini Pro model."""
|
| 85 |
+
genai.configure(api_key=api_key)
|
| 86 |
+
model = genai.GenerativeModel("gemini-pro")
|
| 87 |
+
|
| 88 |
+
# Convert messages to Gemini format
|
| 89 |
+
gemini_messages = []
|
| 90 |
+
for msg in messages:
|
| 91 |
+
role = "user" if msg["role"] == "user" else "model"
|
| 92 |
+
gemini_messages.append({"role": role, "parts": [msg["content"]]})
|
| 93 |
+
|
| 94 |
+
response = model.generate_content([m["parts"][0] for m in gemini_messages])
|
| 95 |
+
return response.text
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def chat_with_sambanova(
|
| 99 |
+
messages: list[dict], api_key: str | None, model_name: str = "Llama-3.2-90B-Vision-Instruct"
|
| 100 |
+
) -> str:
|
| 101 |
+
"""Chat with SambaNova's models using their OpenAI-compatible API."""
|
| 102 |
+
client = openai.OpenAI(
|
| 103 |
+
api_key=api_key,
|
| 104 |
+
base_url="https://api.sambanova.ai/v1",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
response = client.chat.completions.create(
|
| 108 |
+
model=model_name,
|
| 109 |
+
messages=messages,
|
| 110 |
+
temperature=0.1,
|
| 111 |
+
top_p=0.1, # Use the specific model name passed in
|
| 112 |
+
)
|
| 113 |
+
return response.choices[0].message.content
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def chat_with_hyperbolic(
|
| 117 |
+
messages: list[dict], api_key: str | None, model_name: str = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 118 |
+
) -> str:
|
| 119 |
+
"""Chat with Hyperbolic's models using their OpenAI-compatible API."""
|
| 120 |
+
client = OpenAI(api_key=api_key, base_url="https://api.hyperbolic.xyz/v1")
|
| 121 |
+
|
| 122 |
+
# Add system message to the start of the messages list
|
| 123 |
+
full_messages = [
|
| 124 |
+
{"role": "system", "content": "You are a helpful assistant. Be descriptive and clear."},
|
| 125 |
+
*messages,
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
response = client.chat.completions.create(
|
| 129 |
+
model=model_name, # Use the specific model name passed in
|
| 130 |
+
messages=full_messages,
|
| 131 |
+
temperature=0.7,
|
| 132 |
+
max_tokens=1024,
|
| 133 |
+
)
|
| 134 |
+
return response.choices[0].message.content
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def multi_model_consensus(
|
| 138 |
+
question: str, selected_models: list[str], rounds: int = 3, progress: gr.Progress = gr.Progress()
|
| 139 |
+
) -> list[tuple[str, str]]:
|
| 140 |
+
if not selected_models:
|
| 141 |
+
raise gr.Error("Please select at least one model to chat with.")
|
| 142 |
+
|
| 143 |
+
chat_history = []
|
| 144 |
+
discussion_history = []
|
| 145 |
+
|
| 146 |
+
# Initial responses
|
| 147 |
+
progress(0, desc="Getting initial responses...")
|
| 148 |
+
initial_responses = []
|
| 149 |
+
for i, model in enumerate(selected_models):
|
| 150 |
+
provider, model_name = model.split(": ", 1)
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
if provider == "Anthropic":
|
| 154 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
| 155 |
+
response = chat_with_anthropic(messages=[{"role": "user", "content": question}], api_key=api_key)
|
| 156 |
+
elif provider == "SambaNova":
|
| 157 |
+
api_key = os.getenv("SAMBANOVA_API_KEY")
|
| 158 |
+
response = chat_with_sambanova(
|
| 159 |
+
messages=[
|
| 160 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
| 161 |
+
{"role": "user", "content": question},
|
| 162 |
+
],
|
| 163 |
+
api_key=api_key,
|
| 164 |
+
)
|
| 165 |
+
elif provider == "Hyperbolic": # Add Hyperbolic case
|
| 166 |
+
api_key = os.getenv("HYPERBOLIC_API_KEY")
|
| 167 |
+
response = chat_with_hyperbolic(messages=[{"role": "user", "content": question}], api_key=api_key)
|
| 168 |
+
else: # Gemini
|
| 169 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 170 |
+
response = chat_with_gemini(messages=[{"role": "user", "content": question}], api_key=api_key)
|
| 171 |
+
|
| 172 |
+
initial_responses.append(f"{model}: {response}")
|
| 173 |
+
discussion_history.append(f"Initial response from {model}:\n{response}")
|
| 174 |
+
chat_history.append((f"Initial response from {model}", response))
|
| 175 |
+
except Exception as e:
|
| 176 |
+
chat_history.append((f"Error from {model}", str(e)))
|
| 177 |
+
|
| 178 |
+
# Discussion rounds
|
| 179 |
+
for round_num in range(rounds):
|
| 180 |
+
progress((round_num + 1) / (rounds + 2), desc=f"Discussion round {round_num + 1}...")
|
| 181 |
+
round_responses = []
|
| 182 |
+
|
| 183 |
+
random.shuffle(selected_models) # Randomize order each round
|
| 184 |
+
for model in selected_models:
|
| 185 |
+
provider, model_name = model.split(": ", 1)
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
discussion_prompt = generate_discussion_prompt(question, discussion_history)
|
| 189 |
+
if provider == "Anthropic":
|
| 190 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
| 191 |
+
response = chat_with_anthropic(
|
| 192 |
+
messages=[{"role": "user", "content": discussion_prompt}], api_key=api_key
|
| 193 |
+
)
|
| 194 |
+
elif provider == "SambaNova":
|
| 195 |
+
api_key = os.getenv("SAMBANOVA_API_KEY")
|
| 196 |
+
response = chat_with_sambanova(
|
| 197 |
+
messages=[
|
| 198 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
| 199 |
+
{"role": "user", "content": discussion_prompt},
|
| 200 |
+
],
|
| 201 |
+
api_key=api_key,
|
| 202 |
+
)
|
| 203 |
+
elif provider == "Hyperbolic": # Add Hyperbolic case
|
| 204 |
+
api_key = os.getenv("HYPERBOLIC_API_KEY")
|
| 205 |
+
response = chat_with_hyperbolic(
|
| 206 |
+
messages=[{"role": "user", "content": discussion_prompt}], api_key=api_key
|
| 207 |
+
)
|
| 208 |
+
else: # Gemini
|
| 209 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 210 |
+
response = chat_with_gemini(
|
| 211 |
+
messages=[{"role": "user", "content": discussion_prompt}], api_key=api_key
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
round_responses.append(f"{model}: {response}")
|
| 215 |
+
discussion_history.append(f"Round {round_num + 1} - {model}:\n{response}")
|
| 216 |
+
chat_history.append((f"Round {round_num + 1} - {model}", response))
|
| 217 |
+
except Exception as e:
|
| 218 |
+
chat_history.append((f"Error from {model} in round {round_num + 1}", str(e)))
|
| 219 |
+
|
| 220 |
+
# Final consensus
|
| 221 |
+
progress(0.9, desc="Building final consensus...")
|
| 222 |
+
model = selected_models[0]
|
| 223 |
+
provider, model_name = model.split(": ", 1)
|
| 224 |
+
|
| 225 |
+
try:
|
| 226 |
+
consensus_prompt = generate_consensus_prompt(question, discussion_history)
|
| 227 |
+
if provider == "Anthropic":
|
| 228 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
| 229 |
+
final_consensus = chat_with_anthropic(
|
| 230 |
+
messages=[{"role": "user", "content": consensus_prompt}], api_key=api_key
|
| 231 |
+
)
|
| 232 |
+
elif provider == "SambaNova":
|
| 233 |
+
api_key = os.getenv("SAMBANOVA_API_KEY")
|
| 234 |
+
final_consensus = chat_with_sambanova(
|
| 235 |
+
messages=[
|
| 236 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
| 237 |
+
{"role": "user", "content": consensus_prompt},
|
| 238 |
+
],
|
| 239 |
+
api_key=api_key,
|
| 240 |
+
)
|
| 241 |
+
elif provider == "Hyperbolic": # Add Hyperbolic case
|
| 242 |
+
api_key = os.getenv("HYPERBOLIC_API_KEY")
|
| 243 |
+
final_consensus = chat_with_hyperbolic(
|
| 244 |
+
messages=[{"role": "user", "content": consensus_prompt}], api_key=api_key
|
| 245 |
+
)
|
| 246 |
+
else: # Gemini
|
| 247 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 248 |
+
final_consensus = chat_with_gemini(
|
| 249 |
+
messages=[{"role": "user", "content": consensus_prompt}], api_key=api_key
|
| 250 |
+
)
|
| 251 |
+
except Exception as e:
|
| 252 |
+
final_consensus = f"Error getting consensus from {model}: {e!s}"
|
| 253 |
+
|
| 254 |
+
chat_history.append(("Final Consensus", final_consensus))
|
| 255 |
+
|
| 256 |
+
progress(1.0, desc="Done!")
|
| 257 |
+
return chat_history
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
with gr.Blocks() as demo:
|
| 261 |
+
gr.Markdown("# Experimental Multi-Model Consensus Chat")
|
| 262 |
+
gr.Markdown(
|
| 263 |
+
"""Select multiple models to collaborate on answering your question.
|
| 264 |
+
The models will discuss with each other and attempt to reach a consensus.
|
| 265 |
+
Maximum 3 models can be selected at once."""
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
with gr.Row():
|
| 269 |
+
with gr.Column():
|
| 270 |
+
model_selector = gr.Dropdown(
|
| 271 |
+
choices=get_all_models(),
|
| 272 |
+
multiselect=True,
|
| 273 |
+
label="Select Models (max 3)",
|
| 274 |
+
info="Choose up to 3 models to participate in the discussion",
|
| 275 |
+
value=["SambaNova: Llama-3.2-90B-Vision-Instruct", "Hyperbolic: Qwen/Qwen2.5-Coder-32B-Instruct"],
|
| 276 |
+
max_choices=3,
|
| 277 |
+
)
|
| 278 |
+
rounds_slider = gr.Slider(
|
| 279 |
+
minimum=1,
|
| 280 |
+
maximum=2,
|
| 281 |
+
value=1,
|
| 282 |
+
step=1,
|
| 283 |
+
label="Discussion Rounds",
|
| 284 |
+
info="Number of rounds of discussion between models",
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
chatbot = gr.Chatbot(height=600, label="Multi-Model Discussion")
|
| 288 |
+
msg = gr.Textbox(label="Your Question", placeholder="Ask a question for the models to discuss...")
|
| 289 |
+
|
| 290 |
+
def respond(message, selected_models, rounds):
|
| 291 |
+
chat_history = multi_model_consensus(message, selected_models, rounds)
|
| 292 |
+
return chat_history
|
| 293 |
+
|
| 294 |
+
msg.submit(respond, [msg, model_selector, rounds_slider], [chatbot], api_name="consensus_chat")
|
| 295 |
+
|
| 296 |
+
for fn in demo.fns.values():
|
| 297 |
+
fn.api_name = False
|
| 298 |
+
|
| 299 |
+
if __name__ == "__main__":
|
| 300 |
+
demo.launch()
|
app_fal.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fal_gradio
|
| 2 |
+
|
| 3 |
+
from utils import get_app
|
| 4 |
+
|
| 5 |
+
demo = get_app(
|
| 6 |
+
models=[
|
| 7 |
+
"fal-ai/ltx-video",
|
| 8 |
+
"fal-ai/ltx-video/image-to-video",
|
| 9 |
+
"fal-ai/luma-photon",
|
| 10 |
+
],
|
| 11 |
+
default_model="fal-ai/luma-photon",
|
| 12 |
+
src=fal_gradio.registry,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
demo.launch()
|
app_fireworks.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import fireworks_gradio
|
| 4 |
+
|
| 5 |
+
from utils import get_app
|
| 6 |
+
|
| 7 |
+
demo = get_app(
|
| 8 |
+
models=[
|
| 9 |
+
"f1-preview",
|
| 10 |
+
"f1-mini-preview",
|
| 11 |
+
"llama-v3p3-70b-instruct",
|
| 12 |
+
],
|
| 13 |
+
default_model="llama-v3p3-70b-instruct",
|
| 14 |
+
src=fireworks_gradio.registry,
|
| 15 |
+
accept_token=not os.getenv("FIREWORKS_API_KEY"),
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
demo.launch()
|
app_gemini.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Gemini models but keep their full names for loading
|
| 6 |
+
GEMINI_MODELS_FULL = [k for k in ai_gradio.registry if k.startswith("gemini:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GEMINI_MODELS_DISPLAY = [k.replace("gemini:", "") for k in GEMINI_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
# Create and launch the interface using get_app utility
|
| 12 |
+
demo = get_app(
|
| 13 |
+
models=GEMINI_MODELS_FULL, # Use the full names with prefix
|
| 14 |
+
default_model=GEMINI_MODELS_FULL[-1],
|
| 15 |
+
dropdown_label="Select Gemini Model",
|
| 16 |
+
choices=GEMINI_MODELS_DISPLAY, # Display names without prefix
|
| 17 |
+
src=ai_gradio.registry,
|
| 18 |
+
fill_height=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
demo.launch()
|
app_gemini_camera.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Gemini models but keep their full names for loading
|
| 6 |
+
GEMINI_MODELS_FULL = [k for k in ai_gradio.registry if k.startswith("gemini:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GEMINI_MODELS_DISPLAY = [k.replace("gemini:", "") for k in GEMINI_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
# Create and launch the interface using get_app utility
|
| 12 |
+
demo = get_app(
|
| 13 |
+
models=GEMINI_MODELS_FULL, # Use the full names with prefix
|
| 14 |
+
default_model=GEMINI_MODELS_FULL[-2],
|
| 15 |
+
dropdown_label="Select Gemini Model",
|
| 16 |
+
choices=GEMINI_MODELS_DISPLAY, # Display names without prefix
|
| 17 |
+
src=ai_gradio.registry,
|
| 18 |
+
camera=True,
|
| 19 |
+
fill_height=True,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_gemini_coder.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Gemini models but keep their full names for loading
|
| 6 |
+
GEMINI_MODELS_FULL = [k for k in ai_gradio.registry if k.startswith("gemini:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GEMINI_MODELS_DISPLAY = [k.replace("gemini:", "") for k in GEMINI_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
# Create and launch the interface using get_app utility
|
| 12 |
+
demo = get_app(
|
| 13 |
+
models=GEMINI_MODELS_FULL, # Use the full names with prefix
|
| 14 |
+
default_model=GEMINI_MODELS_FULL[0],
|
| 15 |
+
dropdown_label="Select Gemini Model",
|
| 16 |
+
choices=GEMINI_MODELS_DISPLAY, # Display names without prefix
|
| 17 |
+
src=ai_gradio.registry,
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_gemini_voice.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Gemini models but keep their full names for loading
|
| 6 |
+
GEMINI_MODELS_FULL = [k for k in ai_gradio.registry if k.startswith("gemini:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GEMINI_MODELS_DISPLAY = [k.replace("gemini:", "") for k in GEMINI_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
# Create and launch the interface using get_app utility
|
| 12 |
+
demo = get_app(
|
| 13 |
+
models=GEMINI_MODELS_FULL, # Use the full names with prefix
|
| 14 |
+
default_model=GEMINI_MODELS_FULL[-2],
|
| 15 |
+
dropdown_label="Select Gemini Model",
|
| 16 |
+
choices=GEMINI_MODELS_DISPLAY, # Display names without prefix
|
| 17 |
+
src=ai_gradio.registry,
|
| 18 |
+
enable_voice=True,
|
| 19 |
+
fill_height=True,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_groq.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Groq models from the registry
|
| 6 |
+
GROQ_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("groq:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GROQ_MODELS_DISPLAY = [k.replace("groq:", "") for k in GROQ_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
demo = get_app(
|
| 12 |
+
models=GROQ_MODELS_FULL,
|
| 13 |
+
default_model=GROQ_MODELS_FULL[-2],
|
| 14 |
+
src=ai_gradio.registry,
|
| 15 |
+
dropdown_label="Select Groq Model",
|
| 16 |
+
choices=GROQ_MODELS_DISPLAY,
|
| 17 |
+
fill_height=True,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
demo.launch()
|
app_groq_coder.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the Groq models but keep their full names for loading
|
| 6 |
+
GROQ_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("groq:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
GROQ_MODELS_DISPLAY = [k.replace("groq:", "") for k in GROQ_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
# Create and launch the interface using get_app utility
|
| 12 |
+
demo = get_app(
|
| 13 |
+
models=GROQ_MODELS_FULL, # Use the full names with prefix
|
| 14 |
+
default_model=GROQ_MODELS_FULL[-1],
|
| 15 |
+
dropdown_label="Select Groq Model",
|
| 16 |
+
choices=GROQ_MODELS_DISPLAY, # Display names without prefix
|
| 17 |
+
fill_height=True,
|
| 18 |
+
coder=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_hf.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from utils import get_app
|
| 2 |
+
|
| 3 |
+
demo = get_app(
|
| 4 |
+
models=[
|
| 5 |
+
"microsoft/Phi-3.5-mini-instruct",
|
| 6 |
+
"HuggingFaceTB/SmolLM2-1.7B-Instruct",
|
| 7 |
+
"google/gemma-2-2b-it",
|
| 8 |
+
"openai-community/gpt2",
|
| 9 |
+
"microsoft/phi-2",
|
| 10 |
+
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
| 11 |
+
],
|
| 12 |
+
default_model="HuggingFaceTB/SmolLM2-1.7B-Instruct",
|
| 13 |
+
src="models",
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
if __name__ == "__main__":
|
| 17 |
+
demo.launch()
|
app_huggingface.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
HUGGINGFACE_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("huggingface:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
HUGGINGFACE_MODELS_DISPLAY = [k.replace("huggingface:", "") for k in HUGGINGFACE_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=HUGGINGFACE_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=HUGGINGFACE_MODELS_FULL[0],
|
| 16 |
+
dropdown_label="Select Huggingface Model",
|
| 17 |
+
choices=HUGGINGFACE_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True,
|
| 20 |
+
provider="fireworks-ai",
|
| 21 |
+
bill_to="huggingface"
|
| 22 |
+
)
|
app_hyperbolic.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
HYPERBOLIC_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("hyperbolic:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
HYPERBOLIC_MODELS_DISPLAY = [k.replace("hyperbolic:", "") for k in HYPERBOLIC_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=HYPERBOLIC_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=HYPERBOLIC_MODELS_FULL[-2],
|
| 16 |
+
dropdown_label="Select Hyperbolic Model",
|
| 17 |
+
choices=HYPERBOLIC_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
)
|
app_hyperbolic_coder.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
HYPERBOLIC_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("hyperbolic:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
HYPERBOLIC_MODELS_DISPLAY = [k.replace("hyperbolic:", "") for k in HYPERBOLIC_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=HYPERBOLIC_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=HYPERBOLIC_MODELS_FULL[-2],
|
| 16 |
+
dropdown_label="Select Hyperbolic Model",
|
| 17 |
+
choices=HYPERBOLIC_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True,
|
| 20 |
+
)
|
app_langchain.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
LANGCHAIN_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("langchain:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
LANGCHAIN_MODELS_DISPLAY = [k.replace("langchain:", "") for k in LANGCHAIN_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=LANGCHAIN_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=LANGCHAIN_MODELS_FULL[0],
|
| 16 |
+
dropdown_label="Select Langchain Model",
|
| 17 |
+
choices=LANGCHAIN_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
demo.launch()
|
| 23 |
+
|
app_lumaai.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import lumaai_gradio
|
| 3 |
+
|
| 4 |
+
demo = gr.load(
|
| 5 |
+
name="dream-machine",
|
| 6 |
+
src=lumaai_gradio.registry,
|
| 7 |
+
)
|
app_marco_o1.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import spaces
|
| 3 |
+
import transformers_gradio
|
| 4 |
+
|
| 5 |
+
demo = gr.load(name="AIDC-AI/Marco-o1", src=transformers_gradio.registry)
|
| 6 |
+
demo.fn = spaces.GPU()(demo.fn)
|
| 7 |
+
|
| 8 |
+
for fn in demo.fns.values():
|
| 9 |
+
fn.api_name = False
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
demo.launch()
|
app_meta.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
demo = gr.load("models/meta-llama/Llama-3.3-70B-Instruct")
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
demo.launch()
|
app_mindsearch.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
# Load the Gradio space
|
| 4 |
+
demo = gr.load(name="internlm/MindSearch", src="spaces")
|
| 5 |
+
|
| 6 |
+
# Disable API access for all functions
|
| 7 |
+
if hasattr(demo, "fns"):
|
| 8 |
+
for fn in demo.fns.values():
|
| 9 |
+
fn.api_name = False
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
demo.launch()
|
app_minimax.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
MINIMAX_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("minimax:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
MINIMAX_MODELS_DISPLAY = [k.replace("minimax:", "") for k in MINIMAX_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=MINIMAX_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=MINIMAX_MODELS_FULL[0],
|
| 16 |
+
dropdown_label="Select Minimax Model",
|
| 17 |
+
choices=MINIMAX_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
demo.launch()
|
app_minimax_coder.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the hyperbolic models but keep their full names for loading
|
| 6 |
+
MINIMAX_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("minimax:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
MINIMAX_MODELS_DISPLAY = [k.replace("minimax:", "") for k in MINIMAX_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=MINIMAX_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=MINIMAX_MODELS_FULL[0],
|
| 16 |
+
dropdown_label="Select Minimax Model",
|
| 17 |
+
choices=MINIMAX_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_mistral.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the mistral models but keep their full names for loading
|
| 6 |
+
MISTRAL_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("mistral:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
MISTRAL_MODELS_DISPLAY = [k.replace("mistral:", "") for k in MISTRAL_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=MISTRAL_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=MISTRAL_MODELS_FULL[5],
|
| 16 |
+
dropdown_label="Select Mistral Model",
|
| 17 |
+
choices=MISTRAL_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|
app_moondream.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
# Load the Gradio space
|
| 4 |
+
demo = gr.load(name="akhaliq/moondream", src="spaces")
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Disable API access for all functions
|
| 8 |
+
if hasattr(demo, "fns"):
|
| 9 |
+
for fn in demo.fns.values():
|
| 10 |
+
fn.api_name = False
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
demo.launch()
|
app_nvidia.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the nvidia models but keep their full names for loading
|
| 6 |
+
NVIDIA_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("nvidia:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
NVIDIA_MODELS_DISPLAY = [k.replace("nvidia:", "") for k in NVIDIA_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=NVIDIA_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=NVIDIA_MODELS_FULL[0],
|
| 16 |
+
dropdown_label="Select Nvidia Model",
|
| 17 |
+
choices=NVIDIA_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
demo.launch()
|
app_nvidia_coder.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ai_gradio
|
| 2 |
+
|
| 3 |
+
from utils_ai_gradio import get_app
|
| 4 |
+
|
| 5 |
+
# Get the nvidia models but keep their full names for loading
|
| 6 |
+
NVIDIA_MODELS_FULL = [k for k in ai_gradio.registry.keys() if k.startswith("nvidia:")]
|
| 7 |
+
|
| 8 |
+
# Create display names without the prefix
|
| 9 |
+
NVIDIA_MODELS_DISPLAY = [k.replace("nvidia:", "") for k in NVIDIA_MODELS_FULL]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Create and launch the interface using get_app utility
|
| 13 |
+
demo = get_app(
|
| 14 |
+
models=NVIDIA_MODELS_FULL, # Use the full names with prefix
|
| 15 |
+
default_model=NVIDIA_MODELS_FULL[-1],
|
| 16 |
+
dropdown_label="Select Nvidia Model",
|
| 17 |
+
choices=NVIDIA_MODELS_DISPLAY, # Display names without prefix
|
| 18 |
+
fill_height=True,
|
| 19 |
+
coder=True
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
demo.launch()
|