add image to video gen
Browse files27 unmodified lines28293031323352 unmodified lines8687888990911144 unmodified lines12361237123812391240124166 unmodified lines1308130913101311131213131314228 unmodified lines154315441545154615471548154915501551155215531554155515561557155815592 unmodified lines15621563156415651566156715681569157015711572283 unmodified lines185618571858185918601861499 unmodified lines236123622363236423652366236721 unmodified lines23892390239123922393239449 unmodified lines2444244524462447244824492450245134 unmodified lines2486248724882489249024912492249324942495249624972498148 unmodified lines26472648264926502651265226532654265526562657265826594 unmodified lines2664266526662667266826692670267126722673267426752676267715 unmodified lines26932694269526962697269826994 unmodified lines270427052706270727082709271027112712271361 unmodified lines27752776277727782779278027812782277 unmodified lines306030613062306330643065306630673068306930703071307210 unmodified lines308330843085308630873088308930903091309230933094309530961041 unmodified lines41384139414041414142414350 unmodified lines4194419541964197419841994200420142022 unmodified lines4205420642074208420942104211250 unmodified lines446244634464446544664467446827 unmodified linesimport tempfilefrom openai import OpenAIfrom mistralai import Mistral# Gradio supported languages for syntax highlightingGRADIO_SUPPORTED_LANGUAGES = [52 unmodified linesReturn ONLY the code inside a single ```html ... ``` code block. No additional text before or after."""TRANSFORMERS_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:1144 unmodified linesprint(f"Image-to-image generation error: {str(e)}")return f"Error generating image (image-to-image): {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 generation66 unmodified lines# If no placeholder images found, look for any img tagsif not placeholder_images:img_pattern = r'<img[^>]*>'placeholder_images = re.findall(img_pattern, html_content)# Also look for div elements that might be image placeholdersdiv_placeholder_patterns = [228 unmodified linesreturn '\n\n'.join(replacement_blocks)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) -> 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."""result = html_contenttry:# 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')):# Prefer the dedicated image-to-image prompt if providedi2i_prompt = (image_to_image_prompt or user_prompt or "").strip()blocks2 = create_image_replacement_blocks_from_input_image(result, i2i_prompt, input_image_data, max_images=1)if blocks2:2 unmodified linesif enable_text_to_image and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):t2i_prompt = (text_to_image_prompt or user_prompt or "").strip()# Single-image flow for text-to-imageblocks = create_image_replacement_blocks_text_to_image_single(result, t2i_prompt)if blocks:result = apply_search_replace_changes(result, blocks)except Exception:return html_contentreturn result283 unmodified linesdef send_to_sandbox(code):"""Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""html_doc = (code or "").strip()encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'499 unmodified linesstop_generation = Falsedef generation_code(query: Optional[str], 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):if query is None:query = ''if _history is None:21 unmodified lines'=== src/App.svelte ===' in last_assistant_msg):has_existing_content = True# Choose system prompt based on contextif has_existing_content:# Use follow-up prompt for modifying existing content49 unmodified lines# Check if this is GLM-4.5 model and handle with simple HuggingFace InferenceClientif _current_model["id"] == "zai-org/GLM-4.5":if image is not None:messages.append(create_multimodal_message(enhanced_query, image))else:messages.append({'role': 'user', 'content': enhanced_query})34 unmodified linesclean_code = remove_code_block(content)# Apply image generation (text→image and/or image→image)final_content = apply_generated_images_to_html(content,query,enable_text_to_image=enable_image_generation,enable_image_to_image=enable_image_to_image,input_image_data=image,image_to_image_prompt=image_to_image_prompt,)_history.append([query, final_content])148 unmodified linesclean_content = remove_code_block(modified_content)# Apply image generation (text→image and/or image→image)clean_content = apply_generated_images_to_html(clean_content,query,enable_text_to_image=enable_image_generation,enable_image_to_image=enable_image_to_image,input_image_data=image,image_to_image_prompt=image_to_image_prompt,)yield {4 unmodified lines}else:# Apply image generation (text→image and/or image→image)final_content = apply_generated_images_to_html(clean_code,query,enable_text_to_image=enable_image_generation,enable_image_to_image=enable_image_to_image,input_image_data=image,image_to_image_prompt=image_to_image_prompt,text_to_image_prompt=text_to_image_prompt,)preview_val = None15 unmodified linesstructured = [{"role": "system", "content": GLM45V_HTML_SYSTEM_PROMPT}]if image is not None:user_msg = {"role": "user","content": [4 unmodified linesimport io, base64from PIL import Imageimport numpy as npif isinstance(image, np.ndarray):image = Image.fromarray(image)buf = io.BytesIO()image.save(buf, format="PNG")b64 = base64.b64encode(buf.getvalue()).decode()user_msg["content"].append({"type": "image_url",61 unmodified lines# Use dynamic client based on selected model (for non-GLM-4.5 models)client = get_inference_client(_current_model["id"], provider)if image is not None:messages.append(create_multimodal_message(enhanced_query, image))else:messages.append({'role': 'user', 'content': enhanced_query})try:277 unmodified linesclean_content = remove_code_block(modified_content)# Apply image generation (text→image and/or image→image)clean_content = apply_generated_images_to_html(clean_content,query,enable_text_to_image=enable_image_generation,enable_image_to_image=enable_image_to_image,input_image_data=image,image_to_image_prompt=image_to_image_prompt,text_to_image_prompt=text_to_image_prompt,)10 unmodified linesfinal_content = remove_code_block(content)# Apply image generation (text→image and/or image→image)final_content = apply_generated_images_to_html(final_content,query,enable_text_to_image=enable_image_generation,enable_image_to_image=enable_image_to_image,input_image_data=image,image_to_image_prompt=image_to_image_prompt,text_to_image_prompt=text_to_image_prompt,)_history.append([query, final_content])1041 unmodified lineslabel="UI design image",visible=False)image_to_image_prompt = gr.Textbox(label="Image-to-Image Prompt",placeholder="Describe how to transform the uploaded image (e.g., 'Turn the cat into a tiger.')",50 unmodified linesvisible=True,info="Transform your uploaded image using FLUX.1-Kontext-dev")def on_image_to_image_toggle(toggled):# Show 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):2 unmodified linesimage_to_image_toggle.change(on_image_to_image_toggle,inputs=[image_to_image_toggle],outputs=[image_input, image_to_image_prompt])image_generation_toggle.change(on_text_to_image_toggle,250 unmodified linesshow_progress="hidden",).then(generation_code,inputs=[input, 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],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,27 unmodified lines282930313233343552 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511144 unmodified lines12961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142466 unmodified lines14911492149314941495149614971498228 unmodified lines17271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218532 unmodified lines1856185718581859186018611862186318641865186618671868186918701871283 unmodified lines215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193499 unmodified lines269326942695269626972698269921 unmodified lines272127222723272427252726272727282729273027312732273327342735273627372738273927402741274249 unmodified lines2792279327942795279627972798279934 unmodified lines28342835283628372838283928402841284228432844284528462847284828492850148 unmodified lines299930003001300230033004300530063007300830093010301130123013301430154 unmodified lines30203021302230233024302530263027302830293030303130323033303430353036303715 unmodified lines30533054305530563057305830594 unmodified lines306430653066306730683069307030713072307361 unmodified lines31353136313731383139314031413142277 unmodified lines3420342134223423342434253426342734283429343034313432343334343435343610 unmodified lines3447344834493450345134523453345434553456345734583459346034613462346334641041 unmodified lines4506450745084509451045114512451345144515451650 unmodified lines4567456845694570457145724573457445754576457745784579458045814582458345844585458645872 unmodified lines459045914592459345944595459645974598459946004601460246034604250 unmodified lines485548564857485848594860486127 unmodified linesimport tempfilefrom openai import OpenAIfrom mistralai import Mistralimport uuidimport threading# Gradio supported languages for syntax highlightingGRADIO_SUPPORTED_LANGUAGES = [52 unmodified linesReturn ONLY the code inside a single ```html ... ``` code block. No additional text before or after."""# ---------------------------------------------------------------------------# Video temp-file management (per-session tracking and cleanup)# ---------------------------------------------------------------------------VIDEO_TEMP_DIR = os.path.join(tempfile.gettempdir(), "anycoder_videos")VIDEO_FILE_TTL_SECONDS = 6 * 60 * 60 # 6 hours_SESSION_VIDEO_FILES: Dict[str, List[str]] = {}_VIDEO_FILES_LOCK = threading.Lock()def _ensure_video_dir_exists() -> None:try:os.makedirs(VIDEO_TEMP_DIR, exist_ok=True)except Exception:passdef _register_video_for_session(session_id: Optional[str], file_path: str) -> None:if not session_id or not file_path:returnwith _VIDEO_FILES_LOCK:if session_id not in _SESSION_VIDEO_FILES:_SESSION_VIDEO_FILES[session_id] = []_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:file_list = _SESSION_VIDEO_FILES.pop(session_id, [])for path in file_list:try:if path and os.path.exists(path):os.unlink(path)except Exception:# Best-effort cleanuppassdef reap_old_videos(ttl_seconds: int = VIDEO_FILE_TTL_SECONDS) -> None:"""Delete old video files in the temp directory based on modification time."""try:_ensure_video_dir_exists()now_ts = time.time()for name in os.listdir(VIDEO_TEMP_DIR):path = os.path.join(VIDEO_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:# 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:1144 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) -> 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://...)."""try:print("[Image2Video] Starting video generation")if not os.getenv('HF_TOKEN'):print("[Image2Video] Missing HF_TOKEN")return "Error: HF_TOKEN environment variable is not set. Please set it to your Hugging Face API token."# Prepare clientclient = InferenceClient(provider="auto",api_key=os.getenv('HF_TOKEN'),bill_to="huggingface",)print(f"[Image2Video] InferenceClient initialized (provider=auto)")# Normalize input image to bytesimport iofrom PIL import Imagetry:import numpy as npexcept Exception:np = Noneprint(f"[Image2Video] Normalizing input image type={type(input_image_data)}")if hasattr(input_image_data, 'read'):raw = input_image_data.read()pil_image = Image.open(io.BytesIO(raw))elif hasattr(input_image_data, 'mode') and hasattr(input_image_data, 'size'):pil_image = input_image_dataelif np is not None and isinstance(input_image_data, np.ndarray):pil_image = Image.fromarray(input_image_data)elif isinstance(input_image_data, (bytes, bytearray)):pil_image = Image.open(io.BytesIO(input_image_data))else:pil_image = Image.open(io.BytesIO(bytes(input_image_data)))if pil_image.mode != 'RGB':pil_image = pil_image.convert('RGB')try:print(f"[Image2Video] Input PIL image size={pil_image.size} mode={pil_image.mode}")except Exception:passbuf = io.BytesIO()pil_image.save(buf, format='PNG')input_bytes = buf.getvalue()# Call image-to-video; require method supportmodel_id = "Lightricks/LTX-Video-0.9.8-13B-distilled"image_to_video_method = getattr(client, "image_to_video", None)if not callable(image_to_video_method):print("[Image2Video] InferenceClient.image_to_video not available in this huggingface_hub version")return ("Error generating video (image-to-video): Your installed huggingface_hub version ""does not expose InferenceClient.image_to_video. Please upgrade with ""`pip install -U huggingface_hub` and try again.")print(f"[Image2Video] Calling image_to_video with model={model_id}, prompt length={len(prompt or '')}")video_bytes = image_to_video_method(input_bytes,prompt=prompt,model=model_id,)print(f"[Image2Video] Received video bytes: {len(video_bytes) if hasattr(video_bytes, '__len__') else 'unknown length'}")# Save to temp file for this session (for cleanup on next Generate)try:_ensure_video_dir_exists()file_name = f"{uuid.uuid4()}.mp4"file_path = os.path.join(VIDEO_TEMP_DIR, file_name)with open(file_path, "wb") as f:f.write(video_bytes)_register_video_for_session(session_id, file_path)try:file_size = os.path.getsize(file_path)except Exception:file_size = -1print(f"[Image2Video] Saved video to temp file: {file_path} (size={file_size} bytes)")except Exception as save_exc:print(f"[Image2Video] Warning: could not persist temp video file: {save_exc}")# Always use a file URL for the video source.video_html = ""file_url = Nonetry:if 'file_path' in locals() and file_path:# Build a proper file:// URL for absolute paths (e.g., file:///var/.../uuid.mp4)try:from pathlib import Pathfile_url = Path(file_path).as_uri()except Exception:# Fallback to manual construction; ensure three slashes# Note: this may not be fully standards-compliant on Windowsif file_path.startswith('/'):file_url = f"file:///{file_path.lstrip('/')}" # file:///abs/pathelse:file_url = f"file:///{file_path}"except Exception:file_url = Noneif file_url:video_html = (f"<video controls style=\"max-width: 100%; height: auto; border-radius: 8px; margin: 10px 0;\">"f"<source src=\"{file_url}\" type=\"video/mp4\" />"f"Your browser does not support the video tag."f"</video>")else:# If a file URL cannot be constructed, signal error to avoid embedding data URIs.return "Error generating video (image-to-video): Could not persist video to a local file."print("[Image2Video] Successfully generated video HTML tag")return video_htmlexcept Exception as e:import tracebackprint("[Image2Video] Exception during generation:")traceback.print_exc()print(f"Image-to-video generation error: {str(e)}")return f"Error generating video (image-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 generation66 unmodified lines# If no placeholder images found, look for any img tagsif not placeholder_images:img_pattern = r'<img[^>]*>'# Case-insensitive to catch <IMG> or mixed-case tagsplaceholder_images = re.findall(img_pattern, html_content, re.IGNORECASE)# Also look for div elements that might be image placeholdersdiv_placeholder_patterns = [228 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."""if not user_prompt:return ""import reprint("[Image2Video] Creating replacement blocks for video insertion")placeholder_patterns = [r'<img[^>]*src=["\'](?:placeholder|dummy|sample|example)[^"\']*["\'][^>]*>',r'<img[^>]*src=["\']https?://via\.placeholder\.com[^"\']*["\'][^>]*>',r'<img[^>]*src=["\']https?://picsum\.photos[^"\']*["\'][^>]*>',r'<img[^>]*src=["\']https?://dummyimage\.com[^"\']*["\'][^>]*>',r'<img[^>]*alt=["\'][^"\']*placeholder[^"\']*["\'][^>]*>',r'<img[^>]*class=["\'][^"\']*placeholder[^"\']*["\'][^>]*>',r'<img[^>]*id=["\'][^"\']*placeholder[^"\']*["\'][^>]*>',r'<img[^>]*src=["\']data:image[^"\']*["\'][^>]*>',r'<img[^>]*src=["\']#["\'][^>]*>',r'<img[^>]*src=["\']about:blank["\'][^>]*>',]placeholder_images = []for pattern in placeholder_patterns:matches = re.findall(pattern, html_content, re.IGNORECASE)if matches:placeholder_images.extend(matches)if not placeholder_images:img_pattern = r'<img[^>]*>'placeholder_images = re.findall(img_pattern, html_content)print(f"[Image2Video] Found {len(placeholder_images)} candidate <img> elements")video_html = generate_video_from_image(input_image_data, user_prompt, session_id=session_id)try:has_file_src = 'src="' in video_html and video_html.count('src="') >= 1 and 'data:video/mp4;base64' not in video_html.split('src="', 1)[1]print(f"[Image2Video] Generated video HTML length={len(video_html)}; has_file_src={has_file_src}")except Exception:passif video_html.startswith("Error"):print("[Image2Video] Video generation returned error; aborting replacement")return ""if placeholder_images:placeholder = placeholder_images[0]placeholder_clean = re.sub(r'\s+', ' ', placeholder.strip())print("[Image2Video] Replacing first image placeholder with video")placeholder_variations = [# Try the exact string first to maximize replacement successplaceholder,placeholder_clean,placeholder_clean.replace('"', "'"),placeholder_clean.replace("'", '"'),re.sub(r'\s+', ' ', placeholder_clean),placeholder_clean.replace(' ', ' '),]blocks = []for variation in placeholder_variations:blocks.append(f"""{SEARCH_START}{variation}{DIVIDER}{video_html}{REPLACE_END}""")return '\n\n'.join(blocks)if '<body' in html_content:body_start = html_content.find('<body')body_end = html_content.find('>', body_start) + 1opening_body_tag = html_content[body_start:body_end]print("[Image2Video] No <img> found; inserting video right after the opening <body> tag")print(f"[Image2Video] Opening <body> tag snippet: {opening_body_tag[:120]}")return f"""{SEARCH_START}{opening_body_tag}{DIVIDER}{opening_body_tag}{video_html}{REPLACE_END}"""print("[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) -> 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."""result = html_contenttry: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')):i2v_prompt = (image_to_video_prompt or user_prompt or "").strip()print(f"[MediaApply] Running image-to-video with prompt len={len(i2v_prompt)}")blocks_v = create_video_replacement_blocks_from_input_image(result, i2v_prompt, input_image_data, session_id=session_id)if blocks_v:print("[MediaApply] Applying image-to-video replacement blocks")before_len = len(result)result_after = apply_search_replace_changes(result, blocks_v)after_len = len(result_after)changed = (result_after != result)print(f"[MediaApply] i2v blocks length={len(blocks_v)}; html before={before_len}, after={after_len}, changed={changed}")if not changed:print("[MediaApply] DEBUG: Replacement did not change content. Dumping first block:")try:first_block = blocks_v.split(REPLACE_END)[0][:1000]print(first_block)except Exception:passresult = result_afterelse:print("[MediaApply] No i2v 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')):i2i_prompt = (image_to_image_prompt or user_prompt or "").strip()blocks2 = create_image_replacement_blocks_from_input_image(result, i2i_prompt, input_image_data, max_images=1)if blocks2:2 unmodified linesif enable_text_to_image and (result.strip().startswith('<!DOCTYPE html>') or result.strip().startswith('<html')):t2i_prompt = (text_to_image_prompt or user_prompt or "").strip()print(f"[MediaApply] Running text-to-image with prompt len={len(t2i_prompt)}")# Single-image flow for text-to-imageblocks = create_image_replacement_blocks_text_to_image_single(result, t2i_prompt)if blocks:print("[MediaApply] Applying text-to-image replacement blocks")result = apply_search_replace_changes(result, blocks)except Exception:import tracebackprint("[MediaApply] Exception during media application:")traceback.print_exc()return html_contentreturn result283 unmodified linesdef send_to_sandbox(code):"""Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""html_doc = (code or "").strip()# For preview only: inline local file URLs (e.g., file:///.../video.mp4) as data URIs so the# data: iframe can load them. The original code (shown to the user) still contains file URLs.try:import reimport base64 as _b64import mimetypes as _mtypesimport urllib.parse as _uparsedef _file_url_to_data_uri(file_url: str) -> str | None:try:parsed = _uparse.urlparse(file_url)path = _uparse.unquote(parsed.path)if not path:return Nonewith open(path, 'rb') as _f:raw = _f.read()mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'b64 = _b64.b64encode(raw).decode()return f"data:{mime};base64,{b64}"except Exception:return Nonedef _repl_double(m):url = m.group(1)data_uri = _file_url_to_data_uri(url)return f'src="{data_uri}"' if data_uri else m.group(0)def _repl_single(m):url = m.group(1)data_uri = _file_url_to_data_uri(url)return f"src='{data_uri}'" if data_uri else m.group(0)html_doc = re.sub(r'src="(file:[^"]+)"', _repl_double, html_doc)html_doc = re.sub(r"src='(file:[^']+)'", _repl_single, html_doc)except Exception:# Best-effort; continue without inliningpassencoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'499 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):if query is None:query = ''if _history is None:21 unmodified lines'=== src/App.svelte ===' in last_assistant_msg):has_existing_content = True# Create/lookup a session id for temp-file tracking and cleanupif _setting is not None and isinstance(_setting, dict):session_id = _setting.get("__session_id__")if not session_id:session_id = str(uuid.uuid4())_setting["__session_id__"] = session_idelse:session_id = str(uuid.uuid4())# On each generate, reap old global files and cleanup previous session filestry:cleanup_session_videos(session_id)reap_old_videos()except Exception:pass# Choose system prompt based on contextif has_existing_content:# Use follow-up prompt for modifying existing content49 unmodified lines# Check if this is GLM-4.5 model and handle with simple HuggingFace InferenceClientif _current_model["id"] == "zai-org/GLM-4.5":if vlm_image is not None:messages.append(create_multimodal_message(enhanced_query, vlm_image))else:messages.append({'role': 'user', 'content': enhanced_query})34 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,enable_image_to_image=enable_image_to_image,input_image_data=gen_image,image_to_image_prompt=image_to_image_prompt,enable_image_to_video=enable_image_to_video,image_to_video_prompt=image_to_video_prompt,session_id=session_id,)_history.append([query, final_content])148 unmodified linesclean_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,enable_image_to_image=enable_image_to_image,input_image_data=gen_image,image_to_image_prompt=image_to_image_prompt,enable_image_to_video=enable_image_to_video,image_to_video_prompt=image_to_video_prompt,session_id=session_id,)yield {4 unmodified lines}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,enable_image_to_image=enable_image_to_image,input_image_data=gen_image,image_to_image_prompt=image_to_image_prompt,text_to_image_prompt=text_to_image_prompt,enable_image_to_video=enable_image_to_video,image_to_video_prompt=image_to_video_prompt,session_id=session_id,)preview_val = None15 unmodified linesstructured = [{"role": "system", "content": GLM45V_HTML_SYSTEM_PROMPT}]if vlm_image is not None:user_msg = {"role": "user","content": [4 unmodified linesimport io, base64from PIL import Imageimport numpy as npif isinstance(vlm_image, np.ndarray):vlm_image = Image.fromarray(vlm_image)buf = io.BytesIO()vlm_image.save(buf, format="PNG")b64 = base64.b64encode(buf.getvalue()).decode()user_msg["content"].append({"type": "image_url",61 unmodified lines# Use dynamic client based on selected model (for non-GLM-4.5 models)client = get_inference_client(_current_model["id"], provider)if vlm_image is not None:messages.append(create_multimodal_message(enhanced_query, vlm_image))else:messages.append({'role': 'user', 'content': enhanced_query})try:277 unmodified linesclean_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,enable_image_to_image=enable_image_to_image,input_image_data=gen_image,image_to_image_prompt=image_to_image_prompt,enable_image_to_video=enable_image_to_video,image_to_video_prompt=image_to_video_prompt,session_id=session_id,text_to_image_prompt=text_to_image_prompt,)10 unmodified linesfinal_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,enable_image_to_image=enable_image_to_image,input_image_data=gen_image,image_to_image_prompt=image_to_image_prompt,text_to_image_prompt=text_to_image_prompt,enable_image_to_video=enable_image_to_video,image_to_video_prompt=image_to_video_prompt,session_id=session_id,)_history.append([query, final_content])1041 unmodified lineslabel="UI design image",visible=False)# New hidden image input used for VLMs, image-to-image, and image-to-videogeneration_image_input = gr.Image(label="image for generation",visible=False)image_to_image_prompt = gr.Textbox(label="Image-to-Image Prompt",placeholder="Describe how to transform the uploaded image (e.g., 'Turn the cat into a tiger.')",50 unmodified linesvisible=True,info="Transform your uploaded image using FLUX.1-Kontext-dev")image_to_video_toggle = gr.Checkbox(label="🎞️ Image to Video (uses input image)",value=False,visible=True,info="Generate a short video from your uploaded image using Lightricks LTX-Video")image_to_video_prompt = gr.Textbox(label="Image-to-Video Prompt",placeholder="Describe the motion (e.g., 'The cat starts to dance')",lines=2,visible=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):2 unmodified linesimage_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,250 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],outputs=[code_output, history, sandbox, history_output]).then(end_generation_ui,
app.py+413-20