beta chat ui
Browse files4639 unmodified lines4640464146424643464446456 unmodified lines46524653465446554656465713 unmodified lines46714672467346744675467646774678115 unmodified lines47944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648273 unmodified lines4831483248334834483548364837222 unmodified lines50605061506250635064506550665067506850695070507117 unmodified lines5089509050915092509350944639 unmodified linesmargin: 8px 0;text-align: center;}""") as demo:history = gr.State([])6 unmodified lineswith gr.Sidebar() as sidebar:login_button = gr.LoginButton()# Theme Selector (hidden for end users, developers can modify code)with gr.Column(visible=False):13 unmodified lineslabel="Project URL",placeholder="https://huggingface.co/spaces/user/space OR https://huggingface.co/user/model OR https://github.com/owner/repo",lines=1)load_project_btn = gr.Button("Import Project", variant="secondary", size="sm")load_project_status = gr.Markdown(visible=False)input = gr.Textbox(115 unmodified linesvisible=False)def on_image_to_image_toggle(toggled):# Show generation image input and its prompt when image-to-image is enabledreturn gr.update(visible=bool(toggled)), gr.update(visible=bool(toggled))def on_text_to_image_toggle(toggled):return gr.update(visible=bool(toggled))image_to_image_toggle.change(on_image_to_image_toggle,inputs=[image_to_image_toggle],outputs=[generation_image_input, image_to_image_prompt])def on_image_to_video_toggle(toggled):return gr.update(visible=bool(toggled)), gr.update(visible=bool(toggled))image_to_video_toggle.change(on_image_to_video_toggle,inputs=[image_to_video_toggle],outputs=[generation_image_input, image_to_video_prompt])image_generation_toggle.change(on_text_to_image_toggle,inputs=[image_generation_toggle],outputs=[text_to_image_prompt])text_to_video_toggle.change(on_text_to_image_toggle,inputs=[text_to_video_toggle],outputs=[text_to_video_prompt])model_dropdown = gr.Dropdown(3 unmodified linesvisible=True)provider_state = gr.State("auto")gr.Markdown("**Quick start**", visible=True)with gr.Column(visible=True) as quick_examples_col:for i, demo_item in enumerate(DEMO_LIST[:3]):demo_card = gr.Button(222 unmodified lines)def begin_generation_ui():# Hide only the sidebar; keep main UI visible; do not show any status textreturn [gr.update(visible=False), gr.update(visible=False)]def end_generation_ui():# Keep sidebar visible but collapsed; hide the statusreturn [gr.update(visible=True, open=False), gr.update(visible=False)]btn.click(begin_generation_ui,17 unmodified linesinputs=[history],outputs=[space_name_input, deploy_btn])# Update preview when code or language changescode_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)4639 unmodified lines464046414642464346444645464646474648464946504651465246536 unmodified lines46604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471613 unmodified lines47304731473247334734473547364737115 unmodified lines48534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848893 unmodified lines4893489448954896489748984899222 unmodified lines51225123512451255126512751285129513051315132513317 unmodified lines5151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454354639 unmodified linesmargin: 8px 0;text-align: center;}/* Darker chat bubbles for better contrast in dark theme */#beta_chat .message.user, #beta_chat .message.assistant {background: rgba(60, 60, 60, 0.85);color: #f5f5f5;}#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",info="Switch to the new chat-based sidebar interface")# Simple chat-based controller for sidebarsidebar_chatbot = gr.Chatbot(type="messages",show_label=False,height=320,layout="bubble",bubble_full_width=True,group_consecutive_messages=True,visible=False,elem_id="beta_chat")sidebar_msg = gr.MultimodalTextbox(placeholder=("Describe what to build. Examples: 'use streamlit', 'text to video: <prompt>'. ""See Advanced Commands below for the full list."),submit_btn=True,stop_btn=False,show_label=False,sources=["upload", "microphone"],visible=False)chat_clear_btn = gr.ClearButton([sidebar_msg, sidebar_chatbot], visible=False)# Collapsed Advanced Commands referencewith gr.Accordion(label="Advanced Commands", open=False, visible=False) as advanced_commands:gr.Markdown(value=("### Command Reference\n""- **Language**: 'use streamlit' | 'use gradio' | 'use html'\n""- **Web search**: 'enable web search' | 'disable web search'\n""- **Model**: 'model <name>' (exact match to items in the Model dropdown)\n""- **Website redesign**: include a URL in your message (e.g., 'https://example.com')\n""- **Text → Image**: 'generate images: <prompt>' or 'text to image: <prompt>'\n""- **Image → Image**: 'image to image: <prompt>' (attach an image)\n""- **Image → Video**: 'image to video: <prompt>' (attach an image)\n""- **Text → Video**: 'text to video: <prompt>' or 'generate video: <prompt>'\n""- **Files & media**: attach documents or images directly; the first image is used for generation, the first non-image is treated as a reference file\n""- **Multiple directives**: separate with commas. The first segment is the main build prompt.\n\n""Examples:\n""- anycoder coffee shop, text to video: coffee pouring into cup\n""- redesign https://example.com, use streamlit, enable web search\n""- dashboard ui, generate images: minimalist pastel hero"))# Theme Selector (hidden for end users, developers can modify code)with gr.Column(visible=False):13 unmodified lineslabel="Project URL",placeholder="https://huggingface.co/spaces/user/space OR https://huggingface.co/user/model OR https://github.com/owner/repo",lines=1, visible=True)load_project_btn = gr.Button("Import Project", variant="secondary", size="sm", visible=True)load_project_status = gr.Markdown(visible=False)input = gr.Textbox(115 unmodified linesvisible=False)def on_image_to_image_toggle(toggled, beta_enabled):# Only show in classic mode (beta disabled)vis = bool(toggled) and not bool(beta_enabled)return gr.update(visible=vis), gr.update(visible=vis)def on_text_to_image_toggle(toggled, beta_enabled):vis = bool(toggled) and not bool(beta_enabled)return gr.update(visible=vis)image_to_image_toggle.change(on_image_to_image_toggle,inputs=[image_to_image_toggle, beta_toggle],outputs=[generation_image_input, image_to_image_prompt])def on_image_to_video_toggle(toggled, beta_enabled):vis = bool(toggled) and not bool(beta_enabled)return gr.update(visible=vis), gr.update(visible=vis)image_to_video_toggle.change(on_image_to_video_toggle,inputs=[image_to_video_toggle, beta_toggle],outputs=[generation_image_input, image_to_video_prompt])image_generation_toggle.change(on_text_to_image_toggle,inputs=[image_generation_toggle, beta_toggle],outputs=[text_to_image_prompt])text_to_video_toggle.change(on_text_to_image_toggle,inputs=[text_to_video_toggle, beta_toggle],outputs=[text_to_video_prompt])model_dropdown = gr.Dropdown(3 unmodified linesvisible=True)provider_state = gr.State("auto")quick_start_md = gr.Markdown("**Quick start**", visible=True)with gr.Column(visible=True) as quick_examples_col:for i, demo_item in enumerate(DEMO_LIST[:3]):demo_card = gr.Button(222 unmodified lines)def begin_generation_ui():# If beta chat UI is active, keep sidebar visible; otherwise, default behaviorreturn [gr.update(), gr.update(visible=False)]def end_generation_ui():# Keep sidebar as is; hide the statusreturn [gr.update(), gr.update(visible=False)]btn.click(begin_generation_ui,17 unmodified linesinputs=[history],outputs=[space_name_input, deploy_btn])# --- Chat-based sidebar controller logic ---def _find_model_by_name(name: str):for m in AVAILABLE_MODELS:if m["name"].lower() == name.lower():return mreturn Nonedef _extract_url(text: str) -> str | None:import rematch = re.search(r"https?://[^\s]+", text or "")return match.group(0) if match else Nonedef apply_chat_command(message, chat_messages):# Support plain text or dict from MultimodalTextboxtext = message if isinstance(message, str) else (message.get("text", "") if isinstance(message, dict) else "")files = []if isinstance(message, dict):files = message.get("files", []) or []# Defaults to skip updates where unchangedupd_input = gr.skip()upd_language = gr.skip()upd_url = gr.skip()upd_file = gr.skip()upd_image_for_gen = gr.skip()upd_search = gr.skip()upd_img_gen = gr.skip()upd_t2i_prompt = gr.skip()upd_i2i_toggle = gr.skip()upd_i2i_prompt = gr.skip()upd_i2v_toggle = gr.skip()upd_i2v_prompt = gr.skip()upd_t2v_toggle = gr.skip()upd_t2v_prompt = gr.skip()upd_model_dropdown = gr.skip()upd_current_model = gr.skip()# Split by comma to separate main prompt and directivessegments = [seg.strip() for seg in (text or "").split(",") if seg.strip()]main_prompt = segments[0] if segments else text# Helper to get text after ':' in original casingdef after_colon(original_segment: str) -> str:parts = original_segment.split(":", 1)return parts[1].strip() if len(parts) == 2 else ""# Process directives from all segments (including first if user puts directives there),# but always set the main build prompt from the first segment onlyfor seg in segments:seg_norm = seg.lower()# Languageif "use streamlit" in seg_norm:upd_language = gr.update(value="streamlit")elif "use gradio" in seg_norm:upd_language = gr.update(value="gradio")elif "use html" in seg_norm or "as html" in seg_norm:upd_language = gr.update(value="html")# Web searchif ("enable web search" in seg_normor "web search on" in seg_normor "with web search" in seg_normor "search the web" in seg_norm):upd_search = gr.update(value=True)if ("disable web search" in seg_normor "no web search" in seg_normor "web search off" in seg_norm):upd_search = gr.update(value=False)# Text-to-imageif ("generate images" in seg_norm) or ("text to image" in seg_norm) or ("text-to-image" in seg_norm):upd_img_gen = gr.update(value=True)p = after_colon(seg)if p:upd_t2i_prompt = gr.update(value=p)# Image-to-imageif ("image to image" in seg_norm) or ("image-to-image" in seg_norm) or ("transform image" in seg_norm):upd_i2i_toggle = gr.update(value=True)p = after_colon(seg)if p:upd_i2i_prompt = gr.update(value=p)# Image-to-videoif ("image to video" in seg_norm) or ("image-to-video" in seg_norm):upd_i2v_toggle = gr.update(value=True)p = after_colon(seg)if p:upd_i2v_prompt = gr.update(value=p)# Text-to-videoif ("text to video" in seg_norm) or ("text-to-video" in seg_norm) or ("generate video" in seg_norm):upd_t2v_toggle = gr.update(value=True)p = after_colon(seg)if p:upd_t2v_prompt = gr.update(value=p)# URL (website redesign)url = _extract_url(seg)if url:upd_url = gr.update(value=url)# Model selectionif "model " in seg_norm:try:model_name = seg.split("model", 1)[1].strip()except Exception:model_name = ""if model_name:model_obj = _find_model_by_name(model_name)if model_obj is not None:upd_model_dropdown = gr.update(value=model_obj["name"]) # keep dropdown in syncupd_current_model = model_obj # pass directly to State for immediate effect# Files: attach first non-image to file_input; image to generation_image_inputimg_assigned = Falsenon_img_assigned = Falsefor f in files:try:path = f["path"] if isinstance(f, dict) and "path" in f else fexcept Exception:path = Noneif not path:continueif not img_assigned and any(str(path).lower().endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff", ".tif"]):upd_image_for_gen = gr.update(value=path)img_assigned = Trueelif not non_img_assigned:upd_file = gr.update(value=path)non_img_assigned = True# Set main build intent from first segment (if present), otherwise full textif main_prompt:upd_input = gr.update(value=main_prompt)# Build assistant acknowledgementack = "Configured. Running generation with your latest instructions."if not chat_messages:chat_messages = []chat_messages.append({"role": "user", "content": text})chat_messages.append({"role": "assistant", "content": ack})return ("",gr.update(value=chat_messages, visible=True),upd_input,upd_language,upd_url,upd_file,upd_image_for_gen,upd_search,upd_img_gen,upd_t2i_prompt,upd_i2i_toggle,upd_i2i_prompt,upd_i2v_toggle,upd_i2v_prompt,upd_t2v_toggle,upd_t2v_prompt,upd_model_dropdown,upd_current_model,)# Wire chat submit -> apply settings -> run generationsidebar_msg.submit(apply_chat_command,inputs=[sidebar_msg, sidebar_chatbot],outputs=[sidebar_msg,sidebar_chatbot,input,language_dropdown,website_url_input,file_input,generation_image_input,search_toggle,image_generation_toggle,text_to_image_prompt,image_to_image_toggle,image_to_image_prompt,image_to_video_toggle,image_to_video_prompt,text_to_video_toggle,text_to_video_prompt,model_dropdown,current_model,],queue=False,).then(begin_generation_ui,inputs=None,outputs=[sidebar, generating_status],show_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],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,inputs=None,outputs=[sidebar, generating_status]).then(show_deploy_components,None,[space_name_input, sdk_dropdown, deploy_btn]).then(preserve_space_info_for_followup,inputs=[history],outputs=[space_name_input, deploy_btn])# Toggle between classic controls and beta chat UIdef toggle_beta(checked: bool, t2i: bool, i2i: bool, i2v: bool, t2v: bool):# Prompts only visible in classic mode and when their toggles are ont2i_vis = (not checked) and bool(t2i)i2i_vis = (not checked) and bool(i2i)i2v_vis = (not checked) and bool(i2v)t2v_vis = (not checked) and bool(t2v)return (# Chat UI groupgr.update(visible=checked), # sidebar_chatbotgr.update(visible=checked), # sidebar_msggr.update(visible=checked), # advanced_commandsgr.update(visible=checked), # chat_clear_btn# Classic controlsgr.update(visible=not checked), # inputgr.update(visible=not checked), # language_dropdowngr.update(visible=not checked), # website_url_inputgr.update(visible=not checked), # file_inputgr.update(visible=not checked), # btngr.update(visible=not checked), # clear_btngr.update(visible=not checked), # search_togglegr.update(visible=not checked), # image_generation_togglegr.update(visible=t2i_vis), # text_to_image_promptgr.update(visible=not checked), # image_to_image_togglegr.update(visible=i2i_vis), # image_to_image_promptgr.update(visible=not checked), # image_to_video_togglegr.update(visible=i2v_vis), # image_to_video_promptgr.update(visible=not checked), # text_to_video_togglegr.update(visible=t2v_vis), # text_to_video_promptgr.update(visible=not checked), # model_dropdowngr.update(visible=not checked), # quick_start_mdgr.update(visible=not checked), # quick_examples_col)beta_toggle.change(toggle_beta,inputs=[beta_toggle, image_generation_toggle, image_to_image_toggle, image_to_video_toggle, text_to_video_toggle],outputs=[sidebar_chatbot,sidebar_msg,advanced_commands,chat_clear_btn,input,language_dropdown,website_url_input,file_input,btn,clear_btn,search_toggle,image_generation_toggle,text_to_image_prompt,image_to_image_toggle,image_to_image_prompt,image_to_video_toggle,image_to_video_prompt,text_to_video_toggle,text_to_video_prompt,model_dropdown,quick_start_md,quick_examples_col,],)# Update preview when code or language changescode_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
app.py+359-18