Merge branch 'feature/text-to-music'
Browse files145 unmodified lines1461471481491501511377 unmodified lines152915301531153215331534286 unmodified lines182118221823182418251826166 unmodified lines19931994199519961997199819992 unmodified lines200220032004200520062007200831 unmodified lines204020412042204320442045842 unmodified lines288828892890289128922893289433 unmodified lines292829292930293129322933293493 unmodified lines3028302930303031303230333034303530365 unmodified lines304230433044304530463047147 unmodified lines3195319631973198319932003201320232035 unmodified lines3209321032113212321332143 unmodified lines3218321932203221322232233224322532266 unmodified lines323332343235323632373238381 unmodified lines3620362136223623362436253626362736286 unmodified lines3635363636373638363936408 unmodified lines3649365036513652365336543655365636576 unmodified lines3664366536663667366836691188 unmodified lines48584859486048614862486327 unmodified lines489148924893489448954896244 unmodified lines514151425143514451455146514769 unmodified lines52175218521952205221522259 unmodified lines52825283528452855286528758 unmodified lines53465347534853495350535119 unmodified lines5371537253735374537553763 unmodified lines538053815382538353845385538610 unmodified lines53975398539954005401540254035404540554065407540817 unmodified lines5426542754285429543054311 unmodified line543354345435543654375438543914 unmodified lines545454555456545754585459145 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:1377 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,69 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 lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052061377 unmodified lines15841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651286 unmodified lines19381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990166 unmodified lines21572158215921602161216221632 unmodified lines216621672168216921702171217231 unmodified lines220422052206220722082209221022112212221322142215221622172218221922202221842 unmodified lines306430653066306730683069307033 unmodified lines31043105310631073108310931103111311293 unmodified lines3206320732083209321032113212321332145 unmodified lines32203221322232233224322532263227147 unmodified lines3375337633773378337933803381338233835 unmodified lines338933903391339233933394339533963 unmodified lines3400340134023403340434053406340734086 unmodified lines34153416341734183419342034213422381 unmodified lines3804380538063807380838093810381138126 unmodified lines381938203821382238233824382538268 unmodified lines3835383638373838383938403841384238436 unmodified lines385038513852385338543855385638571188 unmodified lines5046504750485049505050515052505350545055505650575058505950605061506250635064506527 unmodified lines50935094509550965097509850995100510151025103244 unmodified lines534853495350535153525353535469 unmodified lines5424542554265427542854295430543159 unmodified lines549154925493549454955496549754985499550055015502550358 unmodified lines5562556355645565556655675568556919 unmodified lines558955905591559255935594559555963 unmodified lines560056015602560356045605560610 unmodified lines561756185619562056215622562356245625562656275628562917 unmodified lines564756485649565056515652565356541 unmodified line565656575658565956605661566214 unmodified lines56775678567956805681568256835684145 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:1377 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,69 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