WIP: text-to-music feature
Browse files145 unmodified lines1461471481491501511372 unmodified lines152415251526152715281529286 unmodified lines181618171818181918201821166 unmodified lines19881989199019911992199319942 unmodified lines199719981999200020012002200331 unmodified lines203520362037203820392040842 unmodified lines288328842885288628872888288933 unmodified lines292329242925292629272928292993 unmodified lines3023302430253026302730283029303030315 unmodified lines303730383039304030413042147 unmodified lines3190319131923193319431953196319731985 unmodified lines3204320532063207320832093 unmodified lines3213321432153216321732183219322032216 unmodified lines322832293230323132323233381 unmodified lines3615361636173618361936203621362236236 unmodified lines3630363136323633363436358 unmodified lines3644364536463647364836493650365136526 unmodified lines3659366036613662366336641188 unmodified lines48534854485548564857485827 unmodified lines488648874888488948904891244 unmodified lines513651375138513951405141514245 unmodified lines51885189519051915192519359 unmodified lines52535254525552565257525858 unmodified lines53175318531953205321532219 unmodified lines5342534353445345534653473 unmodified lines535153525353535453555356535710 unmodified lines53685369537053715372537353745375537653775378537917 unmodified lines5397539853995400540154021 unmodified line540454055406540754085409541014 unmodified lines542554265427542854295430145 unmodified lines# Temp dir might not exist or be accessible; ignorepassTRANSFORMERS_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.IMPORTANT: You MUST output ALL THREE files in the following format:1372 unmodified linesprint(f"Text-to-video generation error: {str(e)}")return f"Error generating video (text-to-video): {str(e)}"def extract_image_prompts_from_text(text: str, num_images_needed: int = 1) -> list:"""Extract image generation prompts from the full text based on number of images needed"""# Use the entire text as the base prompt for image generation286 unmodified lines# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{video_html}\n{REPLACE_END}"def create_image_replacement_blocks_from_input_image(html_content: str, user_prompt: str, input_image_data, max_images: int = 1) -> str:"""Create search/replace blocks using image-to-image generation with a provided input image.166 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 apply_generated_images_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: str | None = None) -> str:"""Apply text-to-image and/or image-to-image replacements to HTML content.If both toggles are enabled, text-to-image replacements run first, then image-to-image.2 unmodified linestry:print(f"[MediaApply] enable_i2v={enable_image_to_video}, enable_i2i={enable_image_to_image}, "f"enable_t2i={enable_text_to_image}, has_image={input_image_data is not None}")# If image-to-video is enabled, replace the first image with a generated video and return.if enable_image_to_video and input_image_data is not None and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):31 unmodified linesprint("[MediaApply] No t2v replacement blocks generated")return result# If an input image is provided and image-to-image is enabled, we only replace one image# and skip text-to-image to satisfy the requirement to replace exactly the number of uploaded images.if enable_image_to_image and input_image_data is not None and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):842 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):if query is None:query = ''if _history is None:33 unmodified lines# On each generate, reap old global files and cleanup previous session filestry:cleanup_session_videos(session_id)reap_old_videos()except Exception:pass93 unmodified linesclean_code = remove_code_block(content)# Apply image generation (text→image and/or image→image)print("[Generate] Applying post-generation media to GLM-4.5 HTML output")final_content = apply_generated_images_to_html(content,query,enable_text_to_image=enable_image_generation,5 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,)_history.append([query, final_content])147 unmodified linesmodified_content = apply_search_replace_changes(last_content, clean_code)clean_content = remove_code_block(modified_content)# Apply image generation (text→image and/or image→image)print("[Generate] Applying post-generation media to modified HTML content")clean_content = apply_generated_images_to_html(clean_content,query,enable_text_to_image=enable_image_generation,5 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,)yield {3 unmodified lineshistory_output: history_to_chatbot_messages(_history),}else:# Apply image generation (text→image and/or image→image)print("[Generate] Applying post-generation media to new HTML content")final_content = apply_generated_images_to_html(clean_code,query,enable_text_to_image=enable_image_generation,6 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,)preview_val = None381 unmodified linesmodified_content = apply_search_replace_changes(last_content, final_code)clean_content = remove_code_block(modified_content)# Apply image generation (text→image and/or image→image)print("[Generate] Applying post-generation media to follow-up HTML content")clean_content = apply_generated_images_to_html(clean_content,query,enable_text_to_image=enable_image_generation,6 unmodified linestext_to_image_prompt=text_to_image_prompt,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,)# Update history with the cleaned content8 unmodified lines# Regular generation - use the content as isfinal_content = remove_code_block(content)# Apply image generation (text→image and/or image→image)print("[Generate] Applying post-generation media to final HTML content")final_content = apply_generated_images_to_html(final_content,query,enable_text_to_image=enable_image_generation,6 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,)_history.append([query, final_content])1188 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)27 unmodified linesinputs=[text_to_video_toggle, beta_toggle],outputs=[text_to_video_prompt])model_dropdown = gr.Dropdown(choices=[model['name'] for model in AVAILABLE_MODELS],value=DEFAULT_MODEL_NAME,244 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],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,45 unmodified linesupd_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()]59 unmodified linesif p:upd_t2v_prompt = gr.update(value=p)# URL (website redesign)url = _extract_url(seg)if url:58 unmodified linesupd_t2v_prompt,upd_model_dropdown,upd_current_model,)# Wire chat submit -> apply settings -> run generation19 unmodified linestext_to_video_prompt,model_dropdown,current_model,],queue=False,).then(3 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],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,10 unmodified lines)# 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 group17 unmodified linesgr.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_col1 unmodified linebeta_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,14 unmodified linesimage_to_video_prompt,text_to_video_toggle,text_to_video_prompt,model_dropdown,quick_start_md,quick_examples_col,145 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052061372 unmodified lines15791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646286 unmodified lines19331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985166 unmodified lines21522153215421552156215721582 unmodified lines216121622163216421652166216731 unmodified lines219922002201220222032204220522062207220822092210221122122213221422152216842 unmodified lines305930603061306230633064306533 unmodified lines30993100310131023103310431053106310793 unmodified lines3201320232033204320532063207320832095 unmodified lines32153216321732183219322032213222147 unmodified lines3370337133723373337433753376337733785 unmodified lines338433853386338733883389339033913 unmodified lines3395339633973398339934003401340234036 unmodified lines34103411341234133414341534163417381 unmodified lines3799380038013802380338043805380638076 unmodified lines381438153816381738183819382038218 unmodified lines3830383138323833383438353836383738386 unmodified lines384538463847384838493850385138521188 unmodified lines5041504250435044504550465047504850495050505150525053505450555056505750585059506027 unmodified lines50885089509050915092509350945095509650975098244 unmodified lines534353445345534653475348534945 unmodified lines5395539653975398539954005401540259 unmodified lines546254635464546554665467546854695470547154725473547458 unmodified lines5533553455355536553755385539554019 unmodified lines556055615562556355645565556655673 unmodified lines557155725573557455755576557710 unmodified lines558855895590559155925593559455955596559755985599560017 unmodified lines561856195620562156225623562456251 unmodified line562756285629563056315632563314 unmodified lines56485649565056515652565356545655145 unmodified lines# Temp dir might not exist or be accessible; ignorepass# ---------------------------------------------------------------------------# Audio temp-file management (per-session tracking and cleanup)# ---------------------------------------------------------------------------AUDIO_TEMP_DIR = os.path.join(tempfile.gettempdir(), "anycoder_audio")AUDIO_FILE_TTL_SECONDS = 6 * 60 * 60 # 6 hours_SESSION_AUDIO_FILES: Dict[str, List[str]] = {}_AUDIO_FILES_LOCK = threading.Lock()def _ensure_audio_dir_exists() -> None:try:os.makedirs(AUDIO_TEMP_DIR, exist_ok=True)except Exception:passdef _register_audio_for_session(session_id: Optional[str], file_path: str) -> None:if not session_id or not file_path:returnwith _AUDIO_FILES_LOCK:if session_id not in _SESSION_AUDIO_FILES:_SESSION_AUDIO_FILES[session_id] = []_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:file_list = _SESSION_AUDIO_FILES.pop(session_id, [])for path in file_list:try:if path and os.path.exists(path):os.unlink(path)except Exception:passdef reap_old_audio(ttl_seconds: int = AUDIO_FILE_TTL_SECONDS) -> None:try:_ensure_audio_dir_exists()now_ts = time.time()for name in os.listdir(AUDIO_TEMP_DIR):path = os.path.join(AUDIO_TEMP_DIR, name)try:if not os.path.isfile(path):continuemtime = os.path.getmtime(path)if now_ts - mtime > ttl_seconds:os.unlink(path)except Exception:passexcept Exception:passTRANSFORMERS_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.IMPORTANT: You MUST output ALL THREE files in the following format:1372 unmodified linesprint(f"Text-to-video generation error: {str(e)}")return f"Error generating video (text-to-video): {str(e)}"def generate_music_from_text(prompt: str, music_length_ms: int = 30000, session_id: Optional[str] = None) -> str:"""Generate music from a text prompt using ElevenLabs Music API and return an HTML <audio> tag.Saves audio to a temp file and references it via file:// URL similar to videos.Requires ELEVENLABS_API_KEY in the environment."""try:api_key = os.getenv('ELEVENLABS_API_KEY')if not api_key:return "Error: ELEVENLABS_API_KEY environment variable is not set."headers = {'Content-Type': 'application/json','xi-api-key': api_key,}payload = {'prompt': (prompt or 'Epic orchestral theme with soaring strings and powerful brass'),'music_length_ms': int(music_length_ms) if music_length_ms else 30000,}resp = requests.post('https://api.elevenlabs.io/v1/music/compose', headers=headers, json=payload)try:resp.raise_for_status()except Exception as e:return f"Error generating music: {getattr(e, 'response', resp).text if hasattr(e, 'response') else resp.text}"# Persist audio to temp file and return an <audio> element using file:// URL_ensure_audio_dir_exists()file_name = f"{uuid.uuid4()}.wav"file_path = os.path.join(AUDIO_TEMP_DIR, file_name)try:with open(file_path, 'wb') as f:f.write(resp.content)_register_audio_for_session(session_id, file_path)except Exception as save_exc:return f"Error generating music: could not save audio file ({save_exc})"# Build file URItry:from pathlib import Pathfile_url = Path(file_path).as_uri()except Exception:if file_path.startswith('/'):file_url = f"file:///{file_path.lstrip('/')}"else:file_url = f"file:///{file_path}"audio_html = ("<div class=\"anycoder-music\" style=\"max-width:420px;margin:16px auto;padding:12px 16px;border:1px solid #e5e7eb;border-radius:12px;background:linear-gradient(180deg,#fafafa,#f3f4f6);box-shadow:0 2px 8px rgba(0,0,0,0.06)\">"" <div style=\"font-size:13px;color:#374151;margin-bottom:8px;display:flex;align-items:center;gap:6px\">"" <span>🎵 Generated music</span>"" </div>"f" <audio controls autoplay loop style=\"width:100%;outline:none;\">"f" <source src=\"{file_url}\" type=\"audio/wav\" />"" Your browser does not support the audio element."" </audio>""</div>")return audio_htmlexcept Exception as e:return f"Error generating music: {str(e)}"def extract_image_prompts_from_text(text: str, num_images_needed: int = 1) -> list:"""Extract image generation prompts from the full text based on number of images needed"""# Use the entire text as the base prompt for image generation286 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.We simply insert an <audio> player after the opening <body>."""if not prompt or not prompt.strip():return ""audio_html = generate_music_from_text(prompt, session_id=session_id)if audio_html.startswith("Error"):return ""# Prefer inserting after the first <section>...</section> if present; else after <body>import resection_match = re.search(r"<section\b[\s\S]*?</section>", html_content, flags=re.IGNORECASE)if section_match:section_html = section_match.group(0)section_clean = re.sub(r"\s+", " ", section_html.strip())variations = [section_html,section_clean,section_clean.replace('"', "'"),section_clean.replace("'", '"'),re.sub(r"\s+", " ", section_clean),]blocks = []for v in variations:blocks.append(f"""{SEARCH_START}{v}{DIVIDER}{v}\n {audio_html}{REPLACE_END}""")return "\n\n".join(blocks)if '<body' in html_content:body_end = html_content.find('>', html_content.find('<body')) + 1insertion_point = html_content[:body_end] + '\n 'return f"""{SEARCH_START}{insertion_point}{DIVIDER}{insertion_point}{audio_html}{REPLACE_END}"""# If no <body>, just appendreturn f"{SEARCH_START}\n\n{DIVIDER}\n{audio_html}\n{REPLACE_END}"def create_image_replacement_blocks_from_input_image(html_content: str, user_prompt: str, input_image_data, max_images: int = 1) -> str:"""Create search/replace blocks using image-to-image generation with a provided input image.166 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 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: str | None = None, enable_text_to_music: bool = False, text_to_music_prompt: str | None = None) -> str:"""Apply text-to-image and/or image-to-image replacements to HTML content.If both toggles are enabled, text-to-image replacements run first, then image-to-image.2 unmodified linestry:print(f"[MediaApply] enable_i2v={enable_image_to_video}, enable_i2i={enable_image_to_image}, "f"enable_t2i={enable_text_to_image}, enable_t2v={enable_text_to_video}, enable_t2m={enable_text_to_music}, has_image={input_image_data is not None}")# If image-to-video is enabled, replace the first image with a generated video and return.if enable_image_to_video and input_image_data is not None and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):31 unmodified linesprint("[MediaApply] No t2v replacement blocks generated")return result# If text-to-music is enabled, insert a generated audio player near the top of body and return.if enable_text_to_music and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):t2m_prompt = (text_to_music_prompt or user_prompt or "").strip()print(f"[MediaApply] Running text-to-music with prompt len={len(t2m_prompt)}")blocks_tm = create_music_replacement_blocks_text_to_music(result, t2m_prompt, session_id=session_id)if blocks_tm:print("[MediaApply] Applying text-to-music replacement blocks")result = apply_search_replace_changes(result, blocks_tm)else:print("[MediaApply] No t2m replacement blocks generated")return result# If an input image is provided and image-to-image is enabled, we only replace one image# and skip text-to-image to satisfy the requirement to replace exactly the number of uploaded images.if enable_image_to_image and input_image_data is not None and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):842 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_text_to_music: bool = False, text_to_music_prompt: Optional[str] = None):if query is None:query = ''if _history is None:33 unmodified lines# On each generate, reap old global files and cleanup previous session filestry:cleanup_session_videos(session_id)cleanup_session_audio(session_id)reap_old_videos()reap_old_audio()except Exception:pass93 unmodified linesclean_code = remove_code_block(content)# Apply media generation (images/video/music)print("[Generate] Applying post-generation media to GLM-4.5 HTML output")final_content = apply_generated_media_to_html(content,query,enable_text_to_image=enable_image_generation,5 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,enable_text_to_music=enable_text_to_music,text_to_music_prompt=text_to_music_prompt,)_history.append([query, final_content])147 unmodified linesmodified_content = apply_search_replace_changes(last_content, clean_code)clean_content = remove_code_block(modified_content)# Apply media generation (images/video/music)print("[Generate] Applying post-generation media to modified HTML content")clean_content = apply_generated_media_to_html(clean_content,query,enable_text_to_image=enable_image_generation,5 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,enable_text_to_music=enable_text_to_music,text_to_music_prompt=text_to_music_prompt,)yield {3 unmodified lineshistory_output: history_to_chatbot_messages(_history),}else:# Apply media generation (images/video/music)print("[Generate] Applying post-generation media to new HTML content")final_content = apply_generated_media_to_html(clean_code,query,enable_text_to_image=enable_image_generation,6 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,enable_text_to_music=enable_text_to_music,text_to_music_prompt=text_to_music_prompt,)preview_val = None381 unmodified linesmodified_content = apply_search_replace_changes(last_content, final_code)clean_content = remove_code_block(modified_content)# Apply media generation (images/video/music)print("[Generate] Applying post-generation media to follow-up HTML content")clean_content = apply_generated_media_to_html(clean_content,query,enable_text_to_image=enable_image_generation,6 unmodified linestext_to_image_prompt=text_to_image_prompt,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,enable_text_to_music=enable_text_to_music,text_to_music_prompt=text_to_music_prompt,)# Update history with the cleaned content8 unmodified lines# Regular generation - use the content as isfinal_content = remove_code_block(content)# Apply media generation (images/video/music)print("[Generate] Applying post-generation media to final HTML content")final_content = apply_generated_media_to_html(final_content,query,enable_text_to_image=enable_image_generation,6 unmodified linessession_id=session_id,enable_text_to_video=enable_text_to_video,text_to_video_prompt=text_to_video_prompt,enable_text_to_music=enable_text_to_music,text_to_music_prompt=text_to_music_prompt,)_history.append([query, final_content])1188 unmodified linesvisible=False)# Text-to-Musictext_to_music_toggle = gr.Checkbox(label="🎵 Generate Music (text → music)",value=False,visible=True,info="Compose short music from your prompt using ElevenLabs Music")text_to_music_prompt = gr.Textbox(label="Text-to-Music Prompt",placeholder="Describe the music to generate (e.g., 'Epic orchestral theme with soaring strings and powerful brass')",lines=2,visible=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)27 unmodified linesinputs=[text_to_video_toggle, beta_toggle],outputs=[text_to_video_prompt])text_to_music_toggle.change(on_text_to_image_toggle,inputs=[text_to_music_toggle, beta_toggle],outputs=[text_to_music_prompt])model_dropdown = gr.Dropdown(choices=[model['name'] for model in AVAILABLE_MODELS],value=DEFAULT_MODEL_NAME,244 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, text_to_music_toggle, text_to_music_prompt],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,45 unmodified linesupd_t2v_prompt = gr.skip()upd_model_dropdown = gr.skip()upd_current_model = gr.skip()upd_t2m_toggle = gr.skip()upd_t2m_prompt = gr.skip()# Split by comma to separate main prompt and directivessegments = [seg.strip() for seg in (text or "").split(",") if seg.strip()]59 unmodified linesif p:upd_t2v_prompt = gr.update(value=p)# Text-to-musicif ("text to music" in seg_norm) or ("text-to-music" in seg_norm) or ("generate music" in seg_norm) or ("compose music" in seg_norm):upd_t2m_toggle = gr.update(value=True)p = after_colon(seg)if p:upd_t2m_prompt = gr.update(value=p)# URL (website redesign)url = _extract_url(seg)if url:58 unmodified linesupd_t2v_prompt,upd_model_dropdown,upd_current_model,upd_t2m_toggle,upd_t2m_prompt,)# Wire chat submit -> apply settings -> run generation19 unmodified linestext_to_video_prompt,model_dropdown,current_model,text_to_music_toggle,text_to_music_prompt,],queue=False,).then(3 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, text_to_music_toggle, text_to_music_prompt],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,10 unmodified lines)# Toggle between classic controls and beta chat UIdef toggle_beta(checked: bool, t2i: bool, i2i: bool, i2v: bool, t2v: bool, t2m: 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)t2m_vis = (not checked) and bool(t2m)return (# Chat UI group17 unmodified linesgr.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), # text_to_music_togglegr.update(visible=t2m_vis), # text_to_music_promptgr.update(visible=not checked), # model_dropdowngr.update(visible=not checked), # quick_start_mdgr.update(visible=not checked), # quick_examples_col1 unmodified linebeta_toggle.change(toggle_beta,inputs=[beta_toggle, image_generation_toggle, image_to_image_toggle, image_to_video_toggle, text_to_video_toggle, text_to_music_toggle],outputs=[sidebar_chatbot,sidebar_msg,14 unmodified linesimage_to_video_prompt,text_to_video_toggle,text_to_video_prompt,text_to_music_toggle,text_to_music_prompt,model_dropdown,quick_start_md,quick_examples_col,
app.py+242-17