remove temp audio and video
Browse files1525 unmodified lines1526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421914 unmodified lines355735583559356035613562356310 unmodified lines357435753576357735783579358035813582358335843585358635873588358935909 unmodified lines360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336347 unmodified lines364236433644364536463647364810 unmodified lines365936603661366236633664366536663667366836693670367136723673367436759 unmodified lines36853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719467 unmodified lines4187418841894190419141924193419441954196419741984199420042011525 unmodified linesIMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""# ---------------------------------------------------------------------------# 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: str | None, 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: str | None) -> 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; 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: str | None, 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: str | None) -> 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.**🚨 CRITICAL: DO NOT Generate README.md Files**1914 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 re10 unmodified linesraw = _f.read()mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'# Compress video files before converting to data URI to prevent preview breaksif mime and mime.startswith('video/'):print(f"[Sandbox] Compressing video for preview: {len(raw)} bytes")raw = compress_video_for_data_uri(raw, max_size_mb=1) # Very small limit for previewprint(f"[Sandbox] Compressed video size: {len(raw)} bytes")# If still too large, skip video embedding for previewif len(raw) > 512 * 1024: # 512KB final limitprint(f"[Sandbox] Video still too large after compression, using placeholder")return None # Let the replacement function handle the fallbackb64 = _b64.b64encode(raw).decode()return f"data:{mime};base64,{b64}"except Exception as e:9 unmodified linesreturn 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)# Add deployment message for videos that couldn't be convertedif 'file://' in html_doc and ('video' in html_doc.lower() or '.mp4' in html_doc.lower()):deployment_notice = '''<div style="position: fixed;top: 10px;right: 10px;background: #ff6b35;color: white;padding: 12px 16px;border-radius: 8px;font-family: Arial, sans-serif;font-size: 14px;font-weight: bold;box-shadow: 0 4px 12px rgba(0,0,0,0.15);z-index: 9999;max-width: 300px;text-align: center;">Deploy app to see videos with permanent URLs!</div>'''# Insert the notice right after the opening body tagif '<body' in html_doc:body_end = html_doc.find('>', html_doc.find('<body')) + 1html_doc = html_doc[:body_end] + deployment_notice + html_doc[body_end:]else:html_doc = deployment_notice + html_docexcept Exception:# Best-effort; continue without inlining7 unmodified lines"""Render HTML in a sandboxed iframe with cache-busting for media generation updates."""import timehtml_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 re10 unmodified linesraw = _f.read()mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'# Compress video files before converting to data URI to prevent preview breaksif mime and mime.startswith('video/'):print(f"[Sandbox] Compressing video for preview: {len(raw)} bytes")raw = compress_video_for_data_uri(raw, max_size_mb=1) # Very small limit for previewprint(f"[Sandbox] Compressed video size: {len(raw)} bytes")# If still too large, skip video embedding for previewif len(raw) > 512 * 1024: # 512KB final limitprint(f"[Sandbox] Video still too large after compression, using placeholder")return None # Let the replacement function handle the fallbackb64 = _b64.b64encode(raw).decode()return f"data:{mime};base64,{b64}"except Exception as e:9 unmodified linesreturn 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)# Add deployment message for videos that couldn't be convertedif 'file://' in html_doc and ('video' in html_doc.lower() or '.mp4' in html_doc.lower()):deployment_notice = '''<div style="position: fixed;top: 10px;right: 10px;background: #ff6b35;color: white;padding: 12px 16px;border-radius: 8px;font-family: Arial, sans-serif;font-size: 14px;font-weight: bold;box-shadow: 0 4px 12px rgba(0,0,0,0.15);z-index: 9999;max-width: 300px;text-align: center;">Deploy app to see videos with permanent URLs!</div>'''# Insert the notice right after the opening body tagif '<body' in html_doc:body_end = html_doc.find('>', html_doc.find('<body')) + 1html_doc = html_doc[:body_end] + deployment_notice + html_doc[body_end:]else:html_doc = deployment_notice + html_docexcept Exception:# Best-effort; continue without inlining467 unmodified lineselse:session_id = str(uuid.uuid4())# 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:pass# Update Gradio system prompts if neededif language == "gradio":update_gradio_system_prompts()1525 unmodified lines1526152715281529153015311914 unmodified lines344634473448344934503451345210 unmodified lines3463346434653466346734689 unmodified lines3478347934803481348234837 unmodified lines349134923493349434953496349710 unmodified lines3508350935103511351235139 unmodified lines352335243525352635273528467 unmodified lines3996399739983999400040011525 unmodified linesIMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""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.**🚨 CRITICAL: DO NOT Generate README.md Files**1914 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 as data URIs so the# data: iframe can load them. The original code (shown to the user) still contains file URLs.try:import re10 unmodified linesraw = _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 as e:9 unmodified linesreturn 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 inlining7 unmodified lines"""Render HTML in a sandboxed iframe with cache-busting for media generation updates."""import timehtml_doc = (code or "").strip()# For preview only: inline local file URLs as data URIs so the# data: iframe can load them. The original code (shown to the user) still contains file URLs.try:import re10 unmodified linesraw = _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 as e:9 unmodified linesreturn 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 inlining467 unmodified lineselse:session_id = str(uuid.uuid4())# Update Gradio system prompts if neededif language == "gradio":update_gradio_system_prompts()
app.py+2-202