require login
Browse files65 unmodified lines666768697071727374753 unmodified lines79808182838485808 unmodified lines8948958968978988999002 unmodified lines90390490590690790890942 unmodified lines9529539549559569579582 unmodified lines9619629639649659669671593 unmodified lines2561256225632564256525662567213 unmodified lines27812782278327842785278627872 unmodified lines279027912792279327942795279682 unmodified lines2879288028812882288328842885439 unmodified lines3325332633273328332933303331120 unmodified lines345234533454345534563457345863 unmodified lines3522352335243525352635273528101 unmodified lines3630363136323633363436353636205 unmodified lines3842384338443845384638473848330 unmodified lines4179418041814182418341844185104 unmodified lines4290429142924293429442954296133 unmodified lines443044314432443344344435443679 unmodified lines451645174518451945204521452280 unmodified lines46034604460546064607460846094 unmodified lines46144615461646174618461946201216 unmodified lines58375838583958405841584258431184 unmodified lines7028702970307031703270337034229 unmodified lines726472657266726772687269727010 unmodified lines72817282728372847285728672879 unmodified lines729772987299730073017302730331 unmodified lines7335733673377338733973407341437 unmodified lines7779778077817782778377846 unmodified lines77917792779377947795779670 unmodified lines78677868786978707871787278737874787532 unmodified lines7908790979107911791279137914746 unmodified lines866186628663866486658666866734 unmodified lines8702870387048705870687078708266 unmodified lines8975897689778978897989808981753 unmodified lines97359736973797389739974065 unmodified linesGRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer# 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"""try:response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10)3 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")return Nonedef load_cached_gradio_docs() -> Optional[str]:"""Load cached Gradio documentation from file"""try:if os.path.exists(GRADIO_DOCS_CACHE_FILE):808 unmodified linespassdef _register_video_for_session(session_id: Optional[str], file_path: str) -> None:if not session_id or not file_path:returnwith _VIDEO_FILES_LOCK:2 unmodified lines_SESSION_VIDEO_FILES[session_id].append(file_path)def cleanup_session_videos(session_id: Optional[str]) -> None:if not session_id:returnwith _VIDEO_FILES_LOCK:42 unmodified linespassdef _register_audio_for_session(session_id: Optional[str], file_path: str) -> None:if not session_id or not file_path:returnwith _AUDIO_FILES_LOCK:2 unmodified lines_SESSION_AUDIO_FILES[session_id].append(file_path)def cleanup_session_audio(session_id: Optional[str]) -> None:if not session_id:returnwith _AUDIO_FILES_LOCK:1593 unmodified linesreturn depsdef build_svelte_package_json(existing_json_text: Optional[str], detected_dependencies: Dict[str, str]) -> str:"""Create or merge a package.json for Svelte spaces.- If existing_json_text is provided, merge detected deps into its dependencies.213 unmodified linesexcept Exception:passdef track_session_media_file(session_id: Optional[str], file_path: str) -> None:"""Track a media file for session-based cleanup."""if not session_id or not file_path:return2 unmodified lines_SESSION_MEDIA_FILES[session_id] = []_SESSION_MEDIA_FILES[session_id].append(file_path)def cleanup_session_media(session_id: Optional[str]) -> None:"""Clean up media files for a specific session."""if not session_id:return82 unmodified lines# Register shutdown cleanup handleratexit.register(cleanup_all_temp_media_on_shutdown)def create_temp_media_url(media_bytes: bytes, filename: str, media_type: str = "image", session_id: Optional[str] = None) -> str:"""Create a temporary file and return a local URL for preview.Args:439 unmodified linesprint(f"Image-to-image generation error: {str(e)}")return f"Error generating image (image-to-image): {str(e)}"def generate_video_from_image(input_image_data, prompt: str, session_id: Optional[str] = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from an input image and prompt using Hugging Face InferenceClient.Returns an HTML <video> tag whose source points to a local file URL (file://...).120 unmodified linesprint(f"Image-to-video generation error: {str(e)}")return f"Error generating video (image-to-video): {str(e)}"def generate_video_from_text(prompt: str, session_id: Optional[str] = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from a text prompt using Hugging Face InferenceClient.Returns an HTML <video> tag with compressed data URI for deployment compatibility.63 unmodified linesprint(f"Text-to-video generation error: {str(e)}")return f"Error generating video (text-to-video): {str(e)}"def generate_video_from_video(input_video_data, prompt: str, session_id: Optional[str] = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from an input video and prompt using Decart AI's Lucy Pro V2V API.Returns an HTML <video> tag whose source points to a temporary file URL.101 unmodified linesprint(f"Video-to-video generation error: {str(e)}")return f"Error generating video (video-to-video): {str(e)}"def generate_music_from_text(prompt: str, music_length_ms: int = 30000, session_id: Optional[str] = None, token: gr.OAuthToken | None = None) -> str:"""Generate music from a text prompt using ElevenLabs Music API and return an HTML <audio> tag.Returns compressed data URI for deployment compatibility.205 unmodified linesprint(f"[WanAnimate] {error_msg}")return None, error_msgdef generate_animation_from_image_video(input_image_data, input_video_data, prompt: str, model_id: str = "wan2.2-animate-move", model: str = "wan-pro", session_id: Optional[str] = None, token: gr.OAuthToken | None = None) -> str:"""Generate animated video from reference image and template video using Wan2.2-Animate.Returns an HTML <video> tag whose source points to a temporary file URL.330 unmodified lines# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{image_html}\n{REPLACE_END}"def create_video_replacement_blocks_text_to_video(html_content: str, prompt: str, session_id: Optional[str] = None) -> str:"""Create search/replace blocks that generate and insert ONLY ONE text-to-video result.Replaces the first detected <img> placeholder; if none found, inserts one video near the top of <body>.104 unmodified lines# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def create_music_replacement_blocks_text_to_music(html_content: str, prompt: str, session_id: Optional[str] = None) -> str:"""Create search/replace blocks that insert ONE generated <audio> near the top of <body>.Unlike images/videos which replace placeholders, music doesn't map to an <img> tag.133 unmodified linesreturn '\n\n'.join(replacement_blocks)def create_video_replacement_blocks_from_input_image(html_content: str, user_prompt: str, input_image_data, session_id: Optional[str] = None) -> str:"""Create search/replace blocks that replace the first <img> (or placeholder) with a generated <video>.Uses generate_video_from_image to produce a single video and swaps it in.79 unmodified linesprint("[Image2Video] No <body> tag; appending video via replacement block")return f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def create_video_replacement_blocks_from_input_video(html_content: str, user_prompt: str, input_video_data, session_id: Optional[str] = None) -> str:"""Create search/replace blocks that replace the first <video> (or placeholder) with a generated <video>.Uses generate_video_from_video to produce a single video and swaps it in.80 unmodified linesprint("[Video2Video] No <body> tag; appending video via replacement block")return f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def apply_generated_media_to_html(html_content: str, user_prompt: str, enable_text_to_image: bool, enable_image_to_image: bool, input_image_data, image_to_image_prompt: str | None = None, text_to_image_prompt: str | None = None, enable_image_to_video: bool = False, image_to_video_prompt: str | None = None, session_id: Optional[str] = None, enable_text_to_video: bool = False, text_to_video_prompt: Optional[str] = None, enable_video_to_video: bool = False, video_to_video_prompt: Optional[str] = None, input_video_data = None, enable_text_to_music: bool = False, text_to_music_prompt: Optional[str] = None, enable_image_video_to_animation: bool = False, animation_mode: str = "wan2.2-animate-move", animation_quality: str = "wan-pro", animation_video_data = None, token: gr.OAuthToken | None = None) -> str:"""Apply text/image/video/music replacements to HTML content.- Works with single-document HTML strings4 unmodified lines# Detect multi-page sections and choose an entry HTML to modifyis_multipage = Falsemultipage_files: Dict[str, str] = {}entry_html_path: Optional[str] = Nonetry:multipage_files = parse_multipage_html_output(html_content) or {}if multipage_files:1216 unmodified linesstop_generation = Falsedef generation_code(query: Optional[str], vlm_image: Optional[gr.Image], gen_image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False, language: str = "html", provider: str = "auto", enable_image_generation: bool = False, enable_image_to_image: bool = False, image_to_image_prompt: Optional[str] = None, text_to_image_prompt: Optional[str] = None, enable_image_to_video: bool = False, image_to_video_prompt: Optional[str] = None, enable_text_to_video: bool = False, text_to_video_prompt: Optional[str] = None, enable_video_to_video: bool = False, video_to_video_prompt: Optional[str] = None, input_video_data = None, enable_text_to_music: bool = False, text_to_music_prompt: Optional[str] = None, enable_image_video_to_animation: bool = False, animation_mode: str = "wan2.2-animate-move", animation_quality: str = "wan-pro", animation_video_data = None):if query is None:query = ''if _history is None:1184 unmodified linesfull_url = f"{base_url}?{params}&{files_params}"webbrowser.open_new_tab(full_url)def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:"""Check if URL is a valid Hugging Face Spaces URL and extract username/project"""import re229 unmodified linespassreturn "unknown", Nonedef _fetch_hf_model_readme(repo_id: str) -> Optional[str]:"""Fetch README.md (model card) for a Hugging Face model repo."""try:api = HfApi()10 unmodified linesexcept Exception:return Nonedef _fetch_github_readme(owner: str, repo: str) -> Optional[str]:"""Fetch README.md from a GitHub repo via raw URLs, trying HEAD/main/master."""bases = [f"https://raw.githubusercontent.com/{owner}/{repo}/HEAD/README.md",9 unmodified linescontinuereturn Nonedef _extract_transformers_or_diffusers_snippet(markdown_text: str) -> Tuple[Optional[str], Optional[str]]:"""Extract the most relevant Python code block referencing transformers/diffusers from markdown.Returns (language, code). If not found, returns (None, None).31 unmodified linesreturn scored[0][0] or None, scored[0][1]return None, Nonedef _infer_task_from_context(snippet: Optional[str], pipeline_tag: Optional[str]) -> str:"""Infer a task string for transformers pipeline; fall back to provided pipeline_tag or 'text-generation'."""if pipeline_tag:return pipeline_tag437 unmodified lines#beta_chat .message.user {background: rgba(70, 70, 70, 0.95);}""") as demo:history = gr.State([])6 unmodified lineswith gr.Sidebar() as sidebar:login_button = gr.LoginButton()beta_toggle = gr.Checkbox(value=False,label="Beta: Chat UI",70 unmodified linesinput = gr.Textbox(label="What would you like to build?",placeholder="Describe your application...",lines=3,visible=True)# Language dropdown for code generation (add Streamlit and Gradio as first-class options)language_choices = [32 unmodified linesvisible=False)with gr.Row():btn = gr.Button("Generate", variant="primary", size="lg", scale=2, visible=True)clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True)# --- Move deploy/app name/sdk here, right before web search ---space_name_input = gr.Textbox(746 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt, image_video_to_animation_toggle, animation_mode_dropdown, animation_quality_dropdown, animation_video_input],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,34 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,266 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt, image_video_to_animation_toggle, animation_mode_dropdown, animation_quality_dropdown, animation_video_input],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,753 unmodified lines)# Keep the old deploy method as fallback (if not logged in, user can still use the old method)# Optionally, you can keep the old deploy_btn.click for the default method as a secondary button.if __name__ == "__main__":# Initialize Gradio documentation system65 unmodified lines666768697071727374753 unmodified lines79808182838485808 unmodified lines8948958968978988999002 unmodified lines90390490590690790890942 unmodified lines9529539549559569579582 unmodified lines9619629639649659669671593 unmodified lines2561256225632564256525662567213 unmodified lines27812782278327842785278627872 unmodified lines279027912792279327942795279682 unmodified lines2879288028812882288328842885439 unmodified lines3325332633273328332933303331120 unmodified lines345234533454345534563457345863 unmodified lines3522352335243525352635273528101 unmodified lines3630363136323633363436353636205 unmodified lines3842384338443845384638473848330 unmodified lines4179418041814182418341844185104 unmodified lines4290429142924293429442954296133 unmodified lines443044314432443344344435443679 unmodified lines451645174518451945204521452280 unmodified lines46034604460546064607460846094 unmodified lines46144615461646174618461946201216 unmodified lines583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758981184 unmodified lines7083708470857086708770887089229 unmodified lines731973207321732273237324732510 unmodified lines73367337733873397340734173429 unmodified lines735273537354735573567357735831 unmodified lines7390739173927393739473957396437 unmodified lines7834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678576 unmodified lines7864786578667867786878697870787178727873787478757876787770 unmodified lines794879497950795179527953795479557956795732 unmodified lines7990799179927993799479957996746 unmodified lines874387448745874687478748874934 unmodified lines8784878587868787878887898790266 unmodified lines9057905890599060906190629063753 unmodified lines98179818981998209821982298239824982598269827982898299830983198329833983498359836983765 unmodified linesGRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer# Global variable to store the current Gradio documentation_gradio_docs_content: str | None = None_gradio_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> str | None:"""Fetch the latest Gradio documentation from llms.txt"""try:response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10)3 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")return Nonedef load_cached_gradio_docs() -> str | None:"""Load cached Gradio documentation from file"""try:if os.path.exists(GRADIO_DOCS_CACHE_FILE):808 unmodified linespassdef _register_video_for_session(session_id: str | None, file_path: str) -> None:if not session_id or not file_path:returnwith _VIDEO_FILES_LOCK:2 unmodified lines_SESSION_VIDEO_FILES[session_id].append(file_path)def cleanup_session_videos(session_id: str | None) -> None:if not session_id:returnwith _VIDEO_FILES_LOCK:42 unmodified linespassdef _register_audio_for_session(session_id: str | None, file_path: str) -> None:if not session_id or not file_path:returnwith _AUDIO_FILES_LOCK:2 unmodified lines_SESSION_AUDIO_FILES[session_id].append(file_path)def cleanup_session_audio(session_id: str | None) -> None:if not session_id:returnwith _AUDIO_FILES_LOCK:1593 unmodified linesreturn depsdef build_svelte_package_json(existing_json_text: str | None, detected_dependencies: Dict[str, str]) -> str:"""Create or merge a package.json for Svelte spaces.- If existing_json_text is provided, merge detected deps into its dependencies.213 unmodified linesexcept Exception:passdef track_session_media_file(session_id: str | None, file_path: str) -> None:"""Track a media file for session-based cleanup."""if not session_id or not file_path:return2 unmodified lines_SESSION_MEDIA_FILES[session_id] = []_SESSION_MEDIA_FILES[session_id].append(file_path)def cleanup_session_media(session_id: str | None) -> None:"""Clean up media files for a specific session."""if not session_id:return82 unmodified lines# Register shutdown cleanup handleratexit.register(cleanup_all_temp_media_on_shutdown)def create_temp_media_url(media_bytes: bytes, filename: str, media_type: str = "image", session_id: str | None = None) -> str:"""Create a temporary file and return a local URL for preview.Args:439 unmodified linesprint(f"Image-to-image generation error: {str(e)}")return f"Error generating image (image-to-image): {str(e)}"def generate_video_from_image(input_image_data, prompt: str, session_id: str | None = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from an input image and prompt using Hugging Face InferenceClient.Returns an HTML <video> tag whose source points to a local file URL (file://...).120 unmodified linesprint(f"Image-to-video generation error: {str(e)}")return f"Error generating video (image-to-video): {str(e)}"def generate_video_from_text(prompt: str, session_id: str | None = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from a text prompt using Hugging Face InferenceClient.Returns an HTML <video> tag with compressed data URI for deployment compatibility.63 unmodified linesprint(f"Text-to-video generation error: {str(e)}")return f"Error generating video (text-to-video): {str(e)}"def generate_video_from_video(input_video_data, prompt: str, session_id: str | None = None, token: gr.OAuthToken | None = None) -> str:"""Generate a video from an input video and prompt using Decart AI's Lucy Pro V2V API.Returns an HTML <video> tag whose source points to a temporary file URL.101 unmodified linesprint(f"Video-to-video generation error: {str(e)}")return f"Error generating video (video-to-video): {str(e)}"def generate_music_from_text(prompt: str, music_length_ms: int = 30000, session_id: str | None = None, token: gr.OAuthToken | None = None) -> str:"""Generate music from a text prompt using ElevenLabs Music API and return an HTML <audio> tag.Returns compressed data URI for deployment compatibility.205 unmodified linesprint(f"[WanAnimate] {error_msg}")return None, error_msgdef generate_animation_from_image_video(input_image_data, input_video_data, prompt: str, model_id: str = "wan2.2-animate-move", model: str = "wan-pro", session_id: str | None = None, token: gr.OAuthToken | None = None) -> str:"""Generate animated video from reference image and template video using Wan2.2-Animate.Returns an HTML <video> tag whose source points to a temporary file URL.330 unmodified lines# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{image_html}\n{REPLACE_END}"def create_video_replacement_blocks_text_to_video(html_content: str, prompt: str, session_id: str | None = None) -> str:"""Create search/replace blocks that generate and insert ONLY ONE text-to-video result.Replaces the first detected <img> placeholder; if none found, inserts one video near the top of <body>.104 unmodified lines# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def create_music_replacement_blocks_text_to_music(html_content: str, prompt: str, session_id: str | None = None) -> str:"""Create search/replace blocks that insert ONE generated <audio> near the top of <body>.Unlike images/videos which replace placeholders, music doesn't map to an <img> tag.133 unmodified linesreturn '\n\n'.join(replacement_blocks)def create_video_replacement_blocks_from_input_image(html_content: str, user_prompt: str, input_image_data, session_id: str | None = None) -> str:"""Create search/replace blocks that replace the first <img> (or placeholder) with a generated <video>.Uses generate_video_from_image to produce a single video and swaps it in.79 unmodified linesprint("[Image2Video] No <body> tag; appending video via replacement block")return f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def create_video_replacement_blocks_from_input_video(html_content: str, user_prompt: str, input_video_data, session_id: str | None = None) -> str:"""Create search/replace blocks that replace the first <video> (or placeholder) with a generated <video>.Uses generate_video_from_video to produce a single video and swaps it in.80 unmodified linesprint("[Video2Video] No <body> tag; appending video via replacement block")return f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def apply_generated_media_to_html(html_content: str, user_prompt: str, enable_text_to_image: bool, enable_image_to_image: bool, input_image_data, image_to_image_prompt: str | None = None, text_to_image_prompt: str | None = None, enable_image_to_video: bool = False, image_to_video_prompt: str | None = None, session_id: str | None = None, enable_text_to_video: bool = False, text_to_video_prompt: str | None = None, enable_video_to_video: bool = False, video_to_video_prompt: str | None = None, input_video_data = None, enable_text_to_music: bool = False, text_to_music_prompt: str | None = None, enable_image_video_to_animation: bool = False, animation_mode: str = "wan2.2-animate-move", animation_quality: str = "wan-pro", animation_video_data = None, token: gr.OAuthToken | None = None) -> str:"""Apply text/image/video/music replacements to HTML content.- Works with single-document HTML strings4 unmodified lines# Detect multi-page sections and choose an entry HTML to modifyis_multipage = Falsemultipage_files: Dict[str, str] = {}entry_html_path: str | None = Nonetry:multipage_files = parse_multipage_html_output(html_content) or {}if multipage_files:1216 unmodified linesstop_generation = Falsedef check_authentication(profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None) -> tuple[bool, str]:"""Check if user is authenticated and return status with message."""if not profile or not token:return False, "Please log in with your Hugging Face account to use AnyCoder."if not token.token:return False, "Authentication token is invalid. Please log in again."return True, f"Authenticated as {profile.username}"def update_ui_for_auth_status(profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None):"""Update UI components based on authentication status."""is_authenticated, auth_message = check_authentication(profile, token)if is_authenticated:# User is authenticated - enable all componentsreturn {# Enable main input and buttoninput: gr.update(interactive=True, placeholder="Describe your application..."),btn: gr.update(interactive=True, variant="primary"),# Show authentication statusauth_status: gr.update(value=f"β {auth_message}",visible=True)}else:# User not authenticated - disable main componentsreturn {# Disable main input and button with clear messaginginput: gr.update(interactive=False,placeholder="π Please log in with Hugging Face to use AnyCoder..."),btn: gr.update(interactive=False, variant="secondary"),# Show authentication requirementauth_status: gr.update(value=f"π {auth_message}",visible=True)}def generation_code(query: str | None, vlm_image: Optional[gr.Image], gen_image: Optional[gr.Image], file: str | None, website_url: str | None, _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False, language: str = "html", provider: str = "auto", enable_image_generation: bool = False, enable_image_to_image: bool = False, image_to_image_prompt: str | None = None, text_to_image_prompt: str | None = None, enable_image_to_video: bool = False, image_to_video_prompt: str | None = None, enable_text_to_video: bool = False, text_to_video_prompt: str | None = None, enable_video_to_video: bool = False, video_to_video_prompt: str | None = None, input_video_data = None, enable_text_to_music: bool = False, text_to_music_prompt: str | None = None, enable_image_video_to_animation: bool = False, animation_mode: str = "wan2.2-animate-move", animation_quality: str = "wan-pro", animation_video_data = None, profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None):# Check authentication firstis_authenticated, auth_message = check_authentication(profile, token)if not is_authenticated:error_message = f"π Authentication Required\n\n{auth_message}\n\nPlease click the 'Sign in with Hugging Face' button in the sidebar to continue."yield {code_output: error_message,history_output: history_to_chatbot_messages(_history or []),sandbox: f"<div style='padding:2em;text-align:center;color:#e74c3c;font-size:1.2em;'><h3>π Authentication Required</h3><p>{auth_message}</p><p>Please log in to use AnyCoder.</p></div>",}returnif query is None:query = ''if _history is None:1184 unmodified linesfull_url = f"{base_url}?{params}&{files_params}"webbrowser.open_new_tab(full_url)def check_hf_space_url(url: str) -> Tuple[bool, str | None, str | None]:"""Check if URL is a valid Hugging Face Spaces URL and extract username/project"""import re229 unmodified linespassreturn "unknown", Nonedef _fetch_hf_model_readme(repo_id: str) -> str | None:"""Fetch README.md (model card) for a Hugging Face model repo."""try:api = HfApi()10 unmodified linesexcept Exception:return Nonedef _fetch_github_readme(owner: str, repo: str) -> str | None:"""Fetch README.md from a GitHub repo via raw URLs, trying HEAD/main/master."""bases = [f"https://raw.githubusercontent.com/{owner}/{repo}/HEAD/README.md",9 unmodified linescontinuereturn Nonedef _extract_transformers_or_diffusers_snippet(markdown_text: str) -> Tuple[str | None, str | None]:"""Extract the most relevant Python code block referencing transformers/diffusers from markdown.Returns (language, code). If not found, returns (None, None).31 unmodified linesreturn scored[0][0] or None, scored[0][1]return None, Nonedef _infer_task_from_context(snippet: str | None, pipeline_tag: str | None) -> str:"""Infer a task string for transformers pipeline; fall back to provided pipeline_tag or 'text-generation'."""if pipeline_tag:return pipeline_tag437 unmodified lines#beta_chat .message.user {background: rgba(70, 70, 70, 0.95);}/* Authentication status styling */.auth-status {padding: 8px 12px;border-radius: 6px;margin: 8px 0;font-weight: 500;text-align: center;}.auth-status:has-text("π") {background: rgba(231, 76, 60, 0.1);border: 1px solid rgba(231, 76, 60, 0.3);color: #e74c3c;}.auth-status:has-text("β ") {background: rgba(46, 204, 113, 0.1);border: 1px solid rgba(46, 204, 113, 0.3);color: #2ecc71;}""") as demo:history = gr.State([])6 unmodified lineswith gr.Sidebar() as sidebar:login_button = gr.LoginButton()# Authentication status displayauth_status = gr.Markdown(value="π Please log in with your Hugging Face account to use AnyCoder.",visible=True,elem_classes=["auth-status"])beta_toggle = gr.Checkbox(value=False,label="Beta: Chat UI",70 unmodified linesinput = gr.Textbox(label="What would you like to build?",placeholder="π Please log in with Hugging Face to use AnyCoder...",lines=3,visible=True,interactive=False)# Language dropdown for code generation (add Streamlit and Gradio as first-class options)language_choices = [32 unmodified linesvisible=False)with gr.Row():btn = gr.Button("Generate", variant="secondary", size="lg", scale=2, visible=True, interactive=False)clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True)# --- Move deploy/app name/sdk here, right before web search ---space_name_input = gr.Textbox(746 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt, image_video_to_animation_toggle, animation_mode_dropdown, animation_quality_dropdown, animation_video_input, login_button, login_button],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,34 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt, login_button, login_button],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,266 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, generation_image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state, image_generation_toggle, image_to_image_toggle, image_to_image_prompt, text_to_image_prompt, image_to_video_toggle, image_to_video_prompt, text_to_video_toggle, text_to_video_prompt, video_to_video_toggle, video_to_video_prompt, video_input, text_to_music_toggle, text_to_music_prompt, image_video_to_animation_toggle, animation_mode_dropdown, animation_quality_dropdown, animation_video_input, login_button, login_button],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,753 unmodified lines)# Keep the old deploy method as fallback (if not logged in, user can still use the old method)# Optionally, you can keep the old deploy_btn.click for the default method as a secondary button.# Handle login status changes to update UIlogin_button.login(update_ui_for_auth_status,inputs=[login_button, login_button],outputs=[input, btn, auth_status],queue=False)login_button.logout(update_ui_for_auth_status,inputs=[login_button, login_button],outputs=[input, btn, auth_status],queue=False)if __name__ == "__main__":# Initialize Gradio documentation system
app.py+131-34