add fastrtc docs
Browse files78 unmodified lines79808182838414 unmodified lines9910010110210310466 unmodified lines17117217317417517614 unmodified lines19119219319419519644 unmodified lines24124224324424524680 unmodified lines327328329330331332333334335336337537 unmodified lines87587687787887988071 unmodified lines9529539549559569579136 unmodified lines10094100951009610097100981009978 unmodified lines_comfyui_docs_content: str | None = None_comfyui_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> str | None:"""Fetch the latest Gradio documentation from llms.txt"""try:14 unmodified linesprint(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_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:66 unmodified linesexcept Exception as e:print(f"Warning: Failed to save ComfyUI docs cache: {e}")def get_last_update_time() -> Optional[datetime]:"""Get the last update time from file"""try:14 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)def force_update_gradio_docs():"""Force an update of Gradio documentation (useful when app is updated).44 unmodified linesprint("β Failed to update ComfyUI documentation")return Falsedef get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched80 unmodified linesreturn _comfyui_docs_content or ""def update_gradio_system_prompts():"""Update the global Gradio system prompts with latest documentation"""global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCHdocs_content = get_gradio_docs_content()# Base system promptbase_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.537 unmodified lines"""# Update the promptsGRADIO_SYSTEM_PROMPT = base_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: 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"GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: 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"71 unmodified linesexcept Exception as e:print(f"Warning: Failed to initialize ComfyUI documentation: {e}")# ConfigurationHTML_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 FILE9136 unmodified lines# Initialize ComfyUI documentation systeminitialize_comfyui_docs()# Clean up any orphaned temporary files from previous runscleanup_all_temp_media_on_startup()78 unmodified lines7980818283848586878889909192939414 unmodified lines10911011111211311411511611711811912012112212312466 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521614 unmodified lines23123223323423523623723823924024144 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531680 unmodified lines397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451537 unmodified lines989990991992993994995996997998999100010011002100310041005100610071008100971 unmodified lines108110821083108410851086108710881089109010911092109310941095109610971098109911009136 unmodified lines10237102381023910240102411024210243102441024578 unmodified lines_comfyui_docs_content: str | None = None_comfyui_docs_last_fetched: Optional[datetime] = None# FastRTC Documentation Auto-Update SystemFASTRTC_LLMS_TXT_URL = "https://fastrtc.org/llms.txt"FASTRTC_DOCS_CACHE_FILE = ".fastrtc_docs_cache.txt"FASTRTC_DOCS_LAST_UPDATE_FILE = ".fastrtc_docs_last_update.txt"FASTRTC_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer# Global variable to store the current FastRTC documentation_fastrtc_docs_content: str | None = None_fastrtc_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> str | None:"""Fetch the latest Gradio documentation from llms.txt"""try:14 unmodified linesprint(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")return Nonedef fetch_fastrtc_docs() -> str | None:"""Fetch the latest FastRTC documentation from llms.txt"""try:response = requests.get(FASTRTC_LLMS_TXT_URL, timeout=10)response.raise_for_status()return response.textexcept Exception as e:print(f"Warning: Failed to fetch FastRTC docs from {FASTRTC_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:66 unmodified linesexcept Exception as e:print(f"Warning: Failed to save ComfyUI docs cache: {e}")def load_fastrtc_docs_cache() -> str | None:"""Load FastRTC documentation from cache file"""try:if os.path.exists(FASTRTC_DOCS_CACHE_FILE):with open(FASTRTC_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:return f.read()except Exception as e:print(f"Warning: Failed to load cached FastRTC docs: {e}")return Nonedef save_fastrtc_docs_cache(content: str):"""Save FastRTC documentation to cache file"""try:with open(FASTRTC_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:f.write(content)with open(FASTRTC_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 FastRTC docs cache: {e}")def get_last_update_time() -> Optional[datetime]:"""Get the last update time from file"""try:14 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)def should_update_fastrtc_docs() -> bool:"""Check if FastRTC documentation should be updated"""# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(FASTRTC_DOCS_CACHE_FILE)def force_update_gradio_docs():"""Force an update of Gradio documentation (useful when app is updated).44 unmodified linesprint("β Failed to update ComfyUI documentation")return Falsedef force_update_fastrtc_docs():"""Force an update of FastRTC documentation (useful when app is updated).To manually refresh docs, you can call this function or simply delete the cache file:rm .fastrtc_docs_cache.txt && restart the app"""global _fastrtc_docs_content, _fastrtc_docs_last_fetchedprint("π Forcing FastRTC documentation update...")latest_content = fetch_fastrtc_docs()if latest_content:# Filter out problematic instructions that cause early terminationfiltered_content = filter_problematic_instructions(latest_content)_fastrtc_docs_content = filtered_content_fastrtc_docs_last_fetched = datetime.now()save_fastrtc_docs_cache(filtered_content)update_gradio_system_prompts()print("β FastRTC documentation updated successfully")return Trueelse:print("β Failed to update FastRTC documentation")return Falsedef get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched80 unmodified linesreturn _comfyui_docs_content or ""def get_fastrtc_docs_content() -> str:"""Get the current FastRTC documentation content, updating if necessary"""global _fastrtc_docs_content, _fastrtc_docs_last_fetched# Check if we need to updateif (_fastrtc_docs_content is None or_fastrtc_docs_last_fetched is None orshould_update_fastrtc_docs()):print("Updating FastRTC documentation...")# Try to fetch latest contentlatest_content = fetch_fastrtc_docs()if latest_content:# Filter out problematic instructions that cause early terminationfiltered_content = filter_problematic_instructions(latest_content)_fastrtc_docs_content = filtered_content_fastrtc_docs_last_fetched = datetime.now()save_fastrtc_docs_cache(filtered_content)print("β FastRTC documentation updated successfully")else:# Fallback to cached contentcached_content = load_fastrtc_docs_cache()if cached_content:_fastrtc_docs_content = cached_content_fastrtc_docs_last_fetched = datetime.now()print("β οΈ Using cached FastRTC documentation (network fetch failed)")else:# Fallback to minimal content_fastrtc_docs_content = """# FastRTC 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 FastRTC usage: Stream class, handlers, real-time audio/video processing.Use Stream(handler, modality, mode) for real-time communication apps."""print("β Using minimal fallback documentation")return _fastrtc_docs_content or ""def update_gradio_system_prompts():"""Update the global Gradio system prompts with latest documentation"""global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCHdocs_content = get_gradio_docs_content()fastrtc_content = get_fastrtc_docs_content()# Base system promptbase_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.537 unmodified lines"""# Add FastRTC documentation if availableif fastrtc_content.strip():fastrtc_section = f"""## FastRTC Reference DocumentationWhen building real-time audio/video applications with Gradio, use this FastRTC reference:{fastrtc_content}This reference is automatically synced from https://fastrtc.org/llms.txt to ensure accuracy."""base_prompt += fastrtc_sectionsearch_prompt += fastrtc_section# Update the promptsGRADIO_SYSTEM_PROMPT = base_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: 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"GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: 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"71 unmodified linesexcept Exception as e:print(f"Warning: Failed to initialize ComfyUI documentation: {e}")# Initialize FastRTC documentation on startupdef initialize_fastrtc_docs():"""Initialize FastRTC documentation on application startup"""try:# FastRTC docs are integrated into Gradio system prompts# So we call update_gradio_system_prompts to include FastRTC contentupdate_gradio_system_prompts()if should_update_fastrtc_docs():print("π FastRTC documentation system initialized (fetched fresh content)")else:print("π FastRTC documentation system initialized (using cached content)")except Exception as e:print(f"Warning: Failed to initialize FastRTC documentation: {e}")# ConfigurationHTML_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 FILE9136 unmodified lines# Initialize ComfyUI documentation systeminitialize_comfyui_docs()# Initialize FastRTC documentation systeminitialize_fastrtc_docs()# Clean up any orphaned temporary files from previous runscleanup_all_temp_media_on_startup()
app.py+146