update
Browse filesFiles changed (2)
- backend_docs_manager.py+198-5
- backend_prompts.py+17-70
19 unmodified lines202122232425262728297 unmodified lines37383940414251 unmodified lines94959697989939 unmodified lines13914014114214314464 unmodified lines2092102112122132141 unmodified line21621721821922022122222322422522622719 unmodified linesGRADIO_DOCS_CACHE_FILE = ".backend_gradio_docs_cache.txt"GRADIO_DOCS_LAST_UPDATE_FILE = ".backend_gradio_docs_last_update.txt"# Global variable to store the current Gradio documentation_gradio_docs_content: Optional[str] = None_gradio_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> Optional[str]:"""Fetch the latest Gradio documentation from llms.txt"""if not HAS_REQUESTS:7 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")return Nonedef filter_problematic_instructions(content: str) -> str:"""Filter out problematic instructions that cause LLM to stop generation prematurely"""if not content:51 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(GRADIO_DOCS_CACHE_FILE)def get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched39 unmodified linesreturn _gradio_docs_content or ""def build_gradio_system_prompt() -> str:"""Build the complete Gradio system prompt with full documentation"""64 unmodified lines- Generate production-ready code that follows all best practices- Always include the "Built with anycoder" attribution in the header"""return full_prompt + final_instructions1 unmodified linedef initialize_backend_docs():"""Initialize backend documentation system on startup"""try:# Pre-load the documentationdocs = get_gradio_docs_content()if docs:print(f"🚀 Backend documentation system initialized ({len(docs)} chars loaded)")else:print("⚠️ Backend documentation system initialized with fallback content")except Exception as e:print(f"Warning: Failed to initialize backend documentation: {e}")19 unmodified lines2021222324252627282930313233343536377 unmodified lines4546474849505152535455565758596061626351 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414539 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624764 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983991 unmodified line40140240340440540640740840941041141241341441541641741841942019 unmodified linesGRADIO_DOCS_CACHE_FILE = ".backend_gradio_docs_cache.txt"GRADIO_DOCS_LAST_UPDATE_FILE = ".backend_gradio_docs_last_update.txt"TRANSFORMERSJS_DOCS_URL = "https://huggingface.co/docs/transformers.js/llms.txt"TRANSFORMERSJS_DOCS_CACHE_FILE = ".backend_transformersjs_docs_cache.txt"TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE = ".backend_transformersjs_docs_last_update.txt"# Global variable to store the current Gradio documentation_gradio_docs_content: Optional[str] = None_gradio_docs_last_fetched: Optional[datetime] = None# Global variable to store the current transformers.js documentation_transformersjs_docs_content: Optional[str] = None_transformersjs_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> Optional[str]:"""Fetch the latest Gradio documentation from llms.txt"""if not HAS_REQUESTS:7 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")return Nonedef fetch_transformersjs_docs() -> Optional[str]:"""Fetch the latest transformers.js documentation from llms.txt"""if not HAS_REQUESTS:return Nonetry:response = requests.get(TRANSFORMERSJS_DOCS_URL, timeout=10)response.raise_for_status()return response.textexcept Exception as e:print(f"Warning: Failed to fetch transformers.js docs from {TRANSFORMERSJS_DOCS_URL}: {e}")return Nonedef filter_problematic_instructions(content: str) -> str:"""Filter out problematic instructions that cause LLM to stop generation prematurely"""if not content:51 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(GRADIO_DOCS_CACHE_FILE)def load_cached_transformersjs_docs() -> Optional[str]:"""Load cached transformers.js documentation from file"""try:if os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE):with open(TRANSFORMERSJS_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:return f.read()except Exception as e:print(f"Warning: Failed to load cached transformers.js docs: {e}")return Nonedef save_transformersjs_docs_cache(content: str):"""Save transformers.js documentation to cache file"""try:with open(TRANSFORMERSJS_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:f.write(content)with open(TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:f.write(datetime.now().isoformat())except Exception as e:print(f"Warning: Failed to save transformers.js docs cache: {e}")def should_update_transformersjs_docs() -> bool:"""Check if transformers.js documentation should be updated"""# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE)def get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched39 unmodified linesreturn _gradio_docs_content or ""def get_transformersjs_docs_content() -> str:"""Get the current transformers.js documentation content, updating if necessary"""global _transformersjs_docs_content, _transformersjs_docs_last_fetched# Check if we need to updateif (_transformersjs_docs_content is None or_transformersjs_docs_last_fetched is None orshould_update_transformersjs_docs()):print("📚 Loading transformers.js documentation...")# Try to fetch latest contentlatest_content = fetch_transformersjs_docs()if latest_content:# Filter out problematic instructions that cause early terminationfiltered_content = filter_problematic_instructions(latest_content)_transformersjs_docs_content = filtered_content_transformersjs_docs_last_fetched = datetime.now()save_transformersjs_docs_cache(filtered_content)print(f"✅ transformers.js documentation loaded successfully ({len(filtered_content)} chars)")else:# Fallback to cached contentcached_content = load_cached_transformersjs_docs()if cached_content:_transformersjs_docs_content = cached_content_transformersjs_docs_last_fetched = datetime.now()print(f"⚠️ Using cached transformers.js documentation (network fetch failed) ({len(cached_content)} chars)")else:# Fallback to minimal content_transformersjs_docs_content = """# Transformers.js API Reference (Offline Fallback)This is a minimal fallback when documentation cannot be fetched.Please check your internet connection for the latest API reference.Transformers.js allows you to run 🤗 Transformers models directly in the browser using ONNX Runtime.Key features:- pipeline() API for common tasks (sentiment-analysis, text-generation, etc.)- Support for custom models via model ID or path- WebGPU support for GPU acceleration- Quantization support (fp32, fp16, q8, q4)Basic usage:```javascriptimport { pipeline } from '@huggingface/transformers';const pipe = await pipeline('sentiment-analysis');const out = await pipe('I love transformers!');```For the latest documentation, visit: https://huggingface.co/docs/transformers.js"""print("❌ Using minimal fallback transformers.js documentation")return _transformersjs_docs_content or ""def build_gradio_system_prompt() -> str:"""Build the complete Gradio system prompt with full documentation"""64 unmodified lines- Generate production-ready code that follows all best practices- Always include the "Built with anycoder" attribution in the header"""return full_prompt + final_instructionsdef build_transformersjs_system_prompt() -> str:"""Build the complete transformers.js system prompt with full documentation"""# Get the full transformers.js documentationdocs_content = get_transformersjs_docs_content()# Base system prompt with anycoder-specific instructionsbase_prompt = """You are an expert transformers.js developer. Create a complete, working browser-based ML application using transformers.js based on the user's request. Generate all necessary code to make the application functional and runnable in the browser.## Multi-File Application StructureWhen creating transformers.js applications, organize your code into multiple files for proper deployment:**File Organization:**- `index.html` - Main HTML entry point (REQUIRED)- `app.js` - Main JavaScript application logic (REQUIRED)- `styles.css` - Styling (optional)- `worker.js` - Web Worker for model loading (recommended for better performance)- `package.json` - Node.js dependencies if using bundler (optional)**Output Format:**You MUST use this exact format with file separators:=== index.html ===[complete HTML content]=== app.js ===[complete JavaScript content]=== worker.js ===[web worker content - if needed]**🚨 CRITICAL: Best Practices**- Use CDN for transformers.js: https://cdn.jsdelivr.net/npm/@huggingface/transformers- Implement loading states and progress indicators- Use Web Workers for model loading to avoid blocking UI- Handle errors gracefully with user-friendly messages- Show model download progress when applicable- Use quantized models (q8, q4) for faster loading in browserRequirements:1. Create a modern, responsive web application2. Use appropriate transformers.js pipelines and models3. Include proper error handling and loading states4. Implement progress indicators for model loading5. Add helpful descriptions and examples6. Follow browser best practices (async/await, Web Workers, etc.)7. Make the UI user-friendly with clear labels8. Include proper comments in codeIMPORTANT: 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---## Complete transformers.js DocumentationBelow is the complete, official transformers.js documentation automatically synced from https://huggingface.co/docs/transformers.js/llms.txt:"""# Combine base prompt with full documentationfull_prompt = base_prompt + docs_content# Add final instructionsfinal_instructions = """---## Final Instructions- Always use the exact function signatures and patterns from the transformers.js documentation above- Use the pipeline() API for common tasks- Implement WebGPU support when appropriate for better performance- Use quantized models by default (q8 or q4) for faster browser loading- Generate production-ready code that follows all best practices- Always include the "Built with anycoder" attribution in the header- Consider using Web Workers for heavy computation to keep UI responsive"""return full_prompt + final_instructions1 unmodified linedef initialize_backend_docs():"""Initialize backend documentation system on startup"""try:# Pre-load the Gradio documentationgradio_docs = get_gradio_docs_content()if gradio_docs:print(f"🚀 Gradio documentation initialized ({len(gradio_docs)} chars loaded)")else:print("⚠️ Gradio documentation initialized with fallback content")# Pre-load the transformers.js documentationtransformersjs_docs = get_transformersjs_docs_content()if transformersjs_docs:print(f"🚀 transformers.js documentation initialized ({len(transformersjs_docs)} chars loaded)")else:print("⚠️ transformers.js documentation initialized with fallback content")except Exception as e:print(f"Warning: Failed to initialize backend documentation: {e}")
2 unmodified lines345678910111213141511 unmodified lines2728293031323342 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111125 unmodified lines1181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471482 unmodified lines1511521531541551561571581591601611621 unmodified line1641651661671681691701711721731741751761771781791801811821831841852 unmodified linesNo dependencies on Gradio or other heavy libraries."""# Import the backend documentation manager for Gradio 6 docstry:from backend_docs_manager import build_gradio_system_promptHAS_BACKEND_DOCS = Trueexcept ImportError:HAS_BACKEND_DOCS = Falseprint("Warning: backend_docs_manager not available, using fallback Gradio prompt")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 FILE11 unmodified linesIMPORTANT: 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"""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.**🚨 CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances42 unmodified lines7. Each file must be complete and ready to deploy - no placeholders or "// TODO" comments8. **AVOID EMOJIS in the generated code** (HTML/JS/CSS files) - use text or unicode symbols instead for deployment compatibility**WRONG FORMAT (DO NOT DO THIS):**<!DOCTYPE html><html>...=== index.js ===...**CORRECT FORMAT (DO THIS):**=== index.html ===<!DOCTYPE html><html>...=== index.js ===...**Example of CORRECT format:**=== index.html ===<!DOCTYPE html><html><head>...</head><body>...</body></html>=== index.js ===import { pipeline } from '...';// Complete working code=== style.css ===body { margin: 0; }/* Complete styling */Requirements:1. Create a modern, responsive web application using transformers.js2. Use the transformers.js library for AI/ML functionality5 unmodified lines**Transformers.js Library Usage:**Import via CDN (use in index.html or index.js):```javascript<script type="module">import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';</script>```**Pipeline API - Quick Tour:**Pipelines group together a pretrained model with preprocessing and postprocessing. Example:```javascriptimport { pipeline } from '@huggingface/transformers';// Allocate a pipeline for sentiment-analysisconst pipe = await pipeline('sentiment-analysis');const out = await pipe('I love transformers!');// [{'label': 'POSITIVE', 'score': 0.999817686}]// Use a different model by specifying model idconst pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');```**Device Options:**By default, models run on CPU (via WASM). For better performance, use WebGPU:```javascript// Run on WebGPU (GPU)const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {2 unmodified lines```**Quantization Options:**In resource-constrained environments (browsers), use quantized models:- "fp32" (default for WebGPU)- "fp16"- "q8" (default for WASM)- "q4" (4-bit quantization for smaller size)```javascript// Run at 4-bit quantization for better performanceconst pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {1 unmodified line});```Consider providing users with options to choose device (CPU/GPU) and quantization level based on their needs.**File Content Requirements:**- **index.html**: Complete HTML structure with proper DOCTYPE, meta tags, links to CSS/JS files, and full body content- **index.js**: Complete JavaScript logic with transformers.js imports and ALL functionality implemented- **style.css**: Complete styling for the entire application - NO empty or placeholder styles**🚨 FINAL REMINDERS:**1. Use the === filename === markers EXACTLY as shown in the examples2. DO NOT use markdown code blocks (```html, ```js, ```css)3. ALL THREE files must be complete and functional - no placeholders or "TODO" comments4. Start each file's content immediately on the line after the === marker5. Ensure each file has actual content - empty files will cause deployment failure6. AVOID using emojis in the generated code files - use text or HTML entities insteadIMPORTANT: 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"""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.2 unmodified lines345678910111213141511 unmodified lines272829303132333435363738394042 unmodified lines8384858687885 unmodified lines9495969798991001011021031041051061071081091101111122 unmodified lines1151161171181191201 unmodified line1221231241251261271281291301311322 unmodified linesNo dependencies on Gradio or other heavy libraries."""# Import the backend documentation manager for Gradio 6 docs and transformers.js docstry:from backend_docs_manager import build_gradio_system_prompt, build_transformersjs_system_promptHAS_BACKEND_DOCS = Trueexcept ImportError:HAS_BACKEND_DOCS = Falseprint("Warning: backend_docs_manager not available, using fallback prompts")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 FILE11 unmodified linesIMPORTANT: 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"""# Transformers.js system prompt - dynamically loaded with full transformers.js documentationdef get_transformersjs_system_prompt() -> str:"""Get the complete transformers.js system prompt with full documentation"""if HAS_BACKEND_DOCS:return build_transformersjs_system_prompt()else:# Fallback prompt if documentation manager is not availablereturn """You are an expert web developer creating a transformers.js application. You will generate THREE separate files: index.html, index.js, and style.css.**🚨 CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances42 unmodified lines7. Each file must be complete and ready to deploy - no placeholders or "// TODO" comments8. **AVOID EMOJIS in the generated code** (HTML/JS/CSS files) - use text or unicode symbols instead for deployment compatibilityRequirements:1. Create a modern, responsive web application using transformers.js2. Use the transformers.js library for AI/ML functionality5 unmodified lines**Transformers.js Library Usage:**Import via CDN:```javascriptimport { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';```**Pipeline API - Quick Tour:**```javascript// Allocate a pipeline for sentiment-analysisconst pipe = await pipeline('sentiment-analysis');const out = await pipe('I love transformers!');```**Device Options:**```javascript// Run on WebGPU (GPU)const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {2 unmodified lines```**Quantization Options:**```javascript// Run at 4-bit quantization for better performanceconst pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {1 unmodified line});```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"""# Legacy variable for backward compatibility - now dynamically generatedTRANSFORMERS_JS_SYSTEM_PROMPT = get_transformersjs_system_prompt()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.
backend_docs_manager.py+198-5
backend_prompts.py+17-70