gradio 6 support
Browse filesFiles changed (4)
- .gitignore+10
- backend_api.py+4-1
- backend_docs_manager.pyAdded+235
- backend_prompts.py+19-1
70 unmodified lines71727374757670 unmodified lineslog/logs/# System files.DS_StoreThumbs.db70 unmodified lines7172737475767778798081828384858670 unmodified lineslog/logs/# Documentation cache files (backend).backend_gradio_docs_cache.txt.backend_gradio_docs_last_update.txt.gradio_docs_cache.txt.gradio_docs_last_update.txt.comfyui_docs_cache.txt.comfyui_docs_last_update.txt.fastrtc_docs_cache.txt.fastrtc_docs_last_update.txt# System files.DS_StoreThumbs.db
41 unmodified lines424344454647484950515241 unmodified linesTRANSFORMERS_JS_SYSTEM_PROMPT,STREAMLIT_SYSTEM_PROMPT,REACT_SYSTEM_PROMPT,GRADIO_SYSTEM_PROMPT,JSON_SYSTEM_PROMPT,GENERIC_SYSTEM_PROMPT)print("[Startup] β All system prompts loaded successfully from backend_prompts.py")except Exception as e:import tracebackprint(f"[Startup] β ERROR: Could not import from backend_prompts: {e}")41 unmodified lines424344454647484950515253545541 unmodified linesTRANSFORMERS_JS_SYSTEM_PROMPT,STREAMLIT_SYSTEM_PROMPT,REACT_SYSTEM_PROMPT,get_gradio_system_prompt, # Import the function to get dynamic promptJSON_SYSTEM_PROMPT,GENERIC_SYSTEM_PROMPT)# Get the Gradio system prompt (includes full Gradio 6 documentation)GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()print("[Startup] β All system prompts loaded successfully from backend_prompts.py")print(f"[Startup] π Gradio system prompt loaded with full documentation ({len(GRADIO_SYSTEM_PROMPT)} chars)")except Exception as e:import tracebackprint(f"[Startup] β ERROR: Could not import from backend_prompts: {e}")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235"""Documentation management for backend system prompts.Handles fetching, caching, and updating documentation from llms.txt files.No dependencies on Gradio or other heavy libraries - pure Python only."""import osimport refrom datetime import datetimefrom typing import Optional
try: import requests HAS_REQUESTS = Trueexcept ImportError: HAS_REQUESTS = False print("Warning: requests library not available, using minimal fallback")
# ConfigurationGRADIO_LLMS_TXT_URL = "https://www.gradio.app/llms.txt"GRADIO_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] = None
def fetch_gradio_docs() -> Optional[str]: """Fetch the latest Gradio documentation from llms.txt""" if not HAS_REQUESTS: return None try: response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10) response.raise_for_status() return response.text except Exception as e: print(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}") return None
def filter_problematic_instructions(content: str) -> str: """Filter out problematic instructions that cause LLM to stop generation prematurely""" if not content: return content # List of problematic phrases that cause early termination when LLM encounters ``` in user code problematic_patterns = [ r"Output ONLY the code inside a ``` code block, and do not include any explanations or extra text", r"output only the code inside a ```.*?``` code block", r"Always output only the.*?code.*?inside.*?```.*?```.*?block", r"Return ONLY the code inside a.*?```.*?``` code block", r"Do NOT add the language name at the top of the code output", r"do not include any explanations or extra text", r"Always output only the.*?code blocks.*?shown above, and do not include any explanations", r"Output.*?ONLY.*?code.*?inside.*?```.*?```", r"Return.*?ONLY.*?code.*?inside.*?```.*?```", r"Generate.*?ONLY.*?code.*?inside.*?```.*?```", r"Provide.*?ONLY.*?code.*?inside.*?```.*?```", ] # Remove problematic patterns filtered_content = content for pattern in problematic_patterns: # Use case-insensitive matching filtered_content = re.sub(pattern, "", filtered_content, flags=re.IGNORECASE | re.DOTALL) # Clean up any double newlines or extra whitespace left by removals filtered_content = re.sub(r'\n\s*\n\s*\n', '\n\n', filtered_content) filtered_content = re.sub(r'^\s+', '', filtered_content, flags=re.MULTILINE) return filtered_content
def load_cached_gradio_docs() -> Optional[str]: """Load cached Gradio documentation from file""" try: if os.path.exists(GRADIO_DOCS_CACHE_FILE): with open(GRADIO_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f: return f.read() except Exception as e: print(f"Warning: Failed to load cached Gradio docs: {e}") return None
def save_gradio_docs_cache(content: str): """Save Gradio documentation to cache file""" try: with open(GRADIO_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f: f.write(content) with open(GRADIO_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 Gradio docs cache: {e}")
def should_update_gradio_docs() -> bool: """Check if Gradio documentation should be updated""" # 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_fetched # Check if we need to update if (_gradio_docs_content is None or _gradio_docs_last_fetched is None or should_update_gradio_docs()): print("π Loading Gradio 6 documentation...") # Try to fetch latest content latest_content = fetch_gradio_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_content = filter_problematic_instructions(latest_content) _gradio_docs_content = filtered_content _gradio_docs_last_fetched = datetime.now() save_gradio_docs_cache(filtered_content) print(f"β
Gradio 6 documentation loaded successfully ({len(filtered_content)} chars)") else: # Fallback to cached content cached_content = load_cached_gradio_docs() if cached_content: _gradio_docs_content = cached_content _gradio_docs_last_fetched = datetime.now() print(f"β οΈ Using cached Gradio documentation (network fetch failed) ({len(cached_content)} chars)") else: # Fallback to minimal content _gradio_docs_content = """# Gradio API Reference (Offline Fallback)
This is a minimal fallback when documentation cannot be fetched.Please check your internet connection for the latest API reference.
Basic Gradio components: Button, Textbox, Slider, Image, Audio, Video, File, etc.Use gr.Blocks() for custom layouts and gr.Interface() for simple apps.
For the latest documentation, visit: https://www.gradio.app/llms.txt""" print("β Using minimal fallback documentation") return _gradio_docs_content or ""
def build_gradio_system_prompt() -> str: """Build the complete Gradio system prompt with full documentation""" # Get the full Gradio 6 documentation docs_content = get_gradio_docs_content() # Base system prompt with anycoder-specific instructions 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.
## Multi-File Application Structure
When creating Gradio applications, organize your code into multiple files for proper deployment:
**File Organization:**- `app.py` - Main application entry point (REQUIRED)- `requirements.txt` - Python dependencies (REQUIRED, auto-generated from imports)- `utils.py` - Utility functions and helpers (optional)- `models.py` - Model loading and inference functions (optional)- `config.py` - Configuration and constants (optional)
**Output Format:**You MUST use this exact format with file separators:
=== app.py ===[complete app.py content]
=== utils.py ===[utility functions - if needed]
**π¨ CRITICAL: DO NOT GENERATE requirements.txt or README.md**- requirements.txt is automatically generated from your app.py imports- README.md is automatically provided by the template- Generating these files will break the deployment process
Requirements:1. Create a modern, intuitive Gradio application2. Use appropriate Gradio components (gr.Textbox, gr.Slider, etc.)3. Include proper error handling and loading states4. Use gr.Interface or gr.Blocks as appropriate5. Add helpful descriptions and examples6. Follow Gradio best practices7. Make the UI user-friendly with clear labels8. Include proper documentation in docstrings
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
---
## Complete Gradio 6 Documentation
Below is the complete, official Gradio 6 documentation automatically synced from https://www.gradio.app/llms.txt:
""" # Combine base prompt with full documentation full_prompt = base_prompt + docs_content # Add final instructions final_instructions = """
---
## Final Instructions
- Always use the exact function signatures and patterns from the Gradio 6 documentation above- Follow Gradio 6 migration guidelines if you're familiar with older versions- Use modern Gradio 6 API patterns (e.g., footer_links instead of show_api, api_visibility instead of show_api in events)- Generate production-ready code that follows all best practices- Always include the "Built with anycoder" attribution in the header
""" return full_prompt + final_instructions
def initialize_backend_docs(): """Initialize backend documentation system on startup""" try: # Pre-load the documentation docs = 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}")
# Initialize on importif __name__ != "__main__": # Only initialize if being imported (not run directly) try: initialize_backend_docs() except Exception as e: print(f"Warning: Failed to auto-initialize backend docs: {e}")
2 unmodified lines345678178 unmodified lines18718818919019119219333 unmodified lines2272282292302312322 unmodified linesNo dependencies on Gradio or other heavy libraries."""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**π¨ CRITICAL: DO NOT Generate README.md Files**178 unmodified lines"""GRADIO_SYSTEM_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.## Multi-File Application Structure33 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"""JSON_SYSTEM_PROMPT = """You are an expert at generating JSON configurations for ComfyUI workflows. Create valid, well-structured JSON that can be loaded into ComfyUI.2 unmodified lines345678910111213141516178 unmodified lines19519619719819920020120220320420520620720833 unmodified lines2422432442452462472482492502 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 FILE**π¨ CRITICAL: DO NOT Generate README.md Files**178 unmodified lines"""# Gradio system prompt - dynamically loaded with full Gradio 6 documentationdef get_gradio_system_prompt() -> str:"""Get the complete Gradio system prompt with full Gradio 6 documentation"""if HAS_BACKEND_DOCS:return build_gradio_system_prompt()else:# Fallback prompt if documentation manager is not availablereturn """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.## Multi-File Application Structure33 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"""# Legacy variable for backward compatibility - now dynamically generatedGRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()JSON_SYSTEM_PROMPT = """You are an expert at generating JSON configurations for ComfyUI workflows. Create valid, well-structured JSON that can be loaded into ComfyUI.
.gitignore+10
backend_api.py+4-1
backend_docs_manager.pyAdded+235
backend_prompts.py+19-1