Update app.py
Browse files3 unmodified lines456789101112131415162 unmodified lines19202122232425262728293031323334353637383940414243447 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372385 unmodified lines2442452462472482492502512522532542552562572 unmodified lines2602612622632642652663 unmodified linesimport gradio as grDEFAULT_DIR = "/bucket_data"# ----------------------------# FILE SCANNER (FIXED + SAFE)# ----------------------------def load_live_cctv_dashboard():try:print("\n⚡ Scanning filesystem...")image_exts = (".png", ".jpg", ".jpeg", ".webp", ".gif")video_exts = (".mp4", ".mkv", ".avi", ".mov", ".dav", ".ts")2 unmodified linesvideo_count = 0image_count = 0for root, dirs, files in os.walk(DEFAULT_DIR):# 🔥 DEBUG (confirm traversal works)print("DIR:", root, "FILES:", len(files))for filename in files:full_path = os.path.join(root, filename)lower = filename.lower()# -------------------# skip junk safely# -------------------if lower == ".gitattributes":continueif lower.endswith(".7z"):continueif os.path.isdir(full_path):continuerelative_path = os.path.relpath(full_path, DEFAULT_DIR)relative_path = relative_path.replace("\\", "/")7 unmodified linesencoded_path = quote(relative_path, safe="/")# -------------------# VIDEO# -------------------if lower.endswith(video_exts):video_count += 1print("added video:", encoded_path)grouped_assets[folder_name]["videos"].append({"name": filename,"video_url": encoded_path,})# -------------------# IMAGE# -------------------elif lower.endswith(image_exts):image_count += 1print("added image:", encoded_path)grouped_assets[folder_name]["images"].append({"name": filename,"image_url": encoded_path,})print(f"✅ DONE: {video_count} videos + {image_count} images")return grouped_assetsexcept Exception as e:print("❌ Scan error:", e)return {}# ----------------------------# JS: THUMBNAIL HOVER ENGINE# ----------------------------custom_js = """function initThumbStrip(placeholder) {if (placeholder.dataset.thumbInit === "1") return;const base = placeholder.dataset.thumbBase;if (!base) return;placeholder.dataset.thumbInit = "1";placeholder.style.position = "relative";placeholder.style.overflow = "hidden";let thumbImg = placeholder.querySelector(".native-thumb-poster");if (!thumbImg) {thumbImg = document.createElement("img");thumbImg.className = "native-thumb-poster";thumbImg.style.cssText = `position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:1;pointer-events:none;`;thumbImg.onerror = () => {thumbImg.style.display = "none";};placeholder.prepend(thumbImg);}placeholder.querySelectorAll("span").forEach(el => {el.style.position = "relative";el.style.zIndex = "2";});let frame = 1;thumbImg.src = `${base}/thumbnail1.webp`;const cache = [];for (let i = 1; i <= 5; i++) {const img = new Image();img.src = `${base}/thumbnail${i}.webp`;cache.push(img);}if (placeholder.cycleInterval)clearInterval(placeholder.cycleInterval);placeholder.cycleInterval = setInterval(() => {frame = frame % 5 + 1;thumbImg.src = `${base}/thumbnail${frame}.webp`;}, 2000);}const observer = new IntersectionObserver((entries) => {entries.forEach(entry => {const el = entry.target;if (entry.isIntersecting) {initThumbStrip(el);} else {if (el.cycleInterval) clearInterval(el.cycleInterval);el.dataset.thumbInit = "0";}});}, { threshold: 0.1, rootMargin: "200px" });function observe() {document.querySelectorAll(".video-placeholder").forEach(el => {observer.observe(el);});}if (document.readyState === "loading")document.addEventListener("DOMContentLoaded", observe);elseobserve();new MutationObserver(observe).observe(document.body, {childList: true,subtree: true});"""# ----------------------------# GRADIO APP# ----------------------------with gr.Blocks(title="CCTV Ultimate Explorer",theme=gr.themes.Soft(),js=custom_js) as demo:refresh_btn = gr.Button("🔄 Sync Latest Camera Footage", variant="primary")@gr.render(inputs=refresh_btn, triggers=[demo.load, refresh_btn.click])def render_ui():print("\n--- RENDER START ---")assets = load_live_cctv_dashboard()if not assets:gr.Markdown("### ❌ No media found")returnhtml = []BASE_URL = "https://kphfrepo-webdav.hf.space"for folder, media in assets.items():html.append(f"""<div style="margin-top:25px;"><h2>📁 {folder}</h2>""")# ---------------- VIDEOS ----------------if media["videos"]:html.append("<div style='display:grid;gap:15px;'>")for v in media["videos"]:video_path = v["video_url"].lstrip("/")public_video_url = f"{BASE_URL}/{video_path}"thumb_base = os.path.splitext(video_path)[0]thumb_base_url = f"{BASE_URL}/{thumb_base}"html.append(f"""<div style="border:1px solid #ddd;padding:10px;border-radius:8px;"><div style="height:250px;position:relative;background:#000;"><div class="video-placeholder"data-video-url="{public_video_url}"data-thumb-base="{thumb_base_url}"style="width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#1e293b;color:white;cursor:pointer;"><span style="font-size:2.5rem;">▶️</span><span style="font-size:12px;">Hover preview + Click play</span></div>5 unmodified lines# ---------------- IMAGES ----------------if media["images"]:html.append("<div style='display:grid;grid-template-columns:repeat(auto-fill,150px);gap:10px;'>")for img in media["images"]:img_url = f"{BASE_URL}/{img['image_url'].lstrip('/')}"html.append(f"""<img src="{img_url}"style="width:150px;height:120px;object-fit:cover;border-radius:6px;" />""")html.append("</div>")2 unmodified linesgr.HTML("".join(html))print("--- RENDER END ---\n")if __name__ == "__main__":3 unmodified lines45678910111213141516171819202122232 unmodified lines262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771785 unmodified lines1841851861871881891901911921931941951961971981992002 unmodified lines2032042052062072082092102113 unmodified linesimport gradio as grDEFAULT_DIR = "/bucket_data"BASE_URL = "https://kphfrepo-webdav.hf.space"# ----------------------------# SCANNER (FULL DEBUG MODE)# ----------------------------def load_live_cctv_dashboard():try:print("\n==============================")print("⚡ SCANNER STARTED")print("==============================")print("STEP 1: DEFAULT_DIR =", DEFAULT_DIR)print("STEP 2: EXISTS =", os.path.exists(DEFAULT_DIR))image_exts = (".png", ".jpg", ".jpeg", ".webp", ".gif")video_exts = (".mp4", ".mkv", ".avi", ".mov", ".dav", ".ts")2 unmodified linesvideo_count = 0image_count = 0print("\nSTEP 3: ENTERING os.walk...")walker_step = 0for root, dirs, files in os.walk(DEFAULT_DIR):walker_step += 1print("\n------------------------------")print("WALK STEP:", walker_step)print("ROOT:", root)print("DIRS:", dirs)print("FILES COUNT:", len(files))print("------------------------------")if walker_step > 50:print("DEBUG LIMIT STOPPED WALK EARLY")breakfor filename in files:print(" FILE:", filename)full_path = os.path.join(root, filename)lower = filename.lower()# skip junk safelyif lower == ".gitattributes":print(" SKIP: gitattributes")continueif lower.endswith(".7z"):print(" SKIP: 7z")continueif os.path.isdir(full_path):print(" SKIP: isdir (unexpected)")continueprint(" PROCESSING:", filename)relative_path = os.path.relpath(full_path, DEFAULT_DIR)relative_path = relative_path.replace("\\", "/")7 unmodified linesencoded_path = quote(relative_path, safe="/")# ---------------- VIDEO ----------------if lower.endswith(video_exts):video_count += 1print(" 🎬 ADD VIDEO:", encoded_path)grouped_assets[folder_name]["videos"].append({"name": filename,"video_url": encoded_path,})# ---------------- IMAGE ----------------elif lower.endswith(image_exts):image_count += 1print(" 🖼 ADD IMAGE:", encoded_path)grouped_assets[folder_name]["images"].append({"name": filename,"image_url": encoded_path,})print("\n==============================")print("SCANNER FINISHED")print("VIDEOS:", video_count)print("IMAGES:", image_count)print("==============================\n")return grouped_assetsexcept Exception as e:print("\n❌ SCANNER ERROR:", e)return {}# ----------------------------# GRADIO UI# ----------------------------with gr.Blocks(title="CCTV Debug Explorer") as demo:refresh_btn = gr.Button("🔄 Scan Bucket")@gr.render(inputs=refresh_btn, triggers=[demo.load, refresh_btn.click])def render_ui():print("\n==============================")print("⚡ RENDER START")print("==============================")assets = load_live_cctv_dashboard()print("RENDER RECEIVED ASSETS:", len(assets))if not assets:gr.Markdown("### ❌ No assets found")returnhtml = []for folder, media in assets.items():print("RENDER FOLDER:", folder)html.append(f"""<div style="margin:20px 0;"><h2>📁 {folder}</h2>""")# ---------------- VIDEOS ----------------if media["videos"]:html.append("<div style='display:grid;gap:12px;'>")for v in media["videos"]:video_path = v["video_url"].lstrip("/")video_url = f"{BASE_URL}/{video_path}"print("RENDER VIDEO:", video_url)thumb_base = os.path.splitext(video_path)[0]thumb_url = f"{BASE_URL}/{thumb_base}"html.append(f"""<div style="border:1px solid #ccc;padding:10px;border-radius:8px;"><div style="height:250px;background:#000;position:relative;"><div class="video-placeholder"data-video-url="{video_url}"data-thumb-base="{thumb_url}"style="width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#111827;color:white;cursor:pointer;"><span style="font-size:2rem;">▶️</span><span style="font-size:12px;">Video Ready</span></div>5 unmodified lines# ---------------- IMAGES ----------------if media["images"]:html.append("<div style='display:flex;gap:10px;flex-wrap:wrap;margin-top:10px;'>")for img in media["images"]:img_url = f"{BASE_URL}/{img['image_url'].lstrip('/')}"print("RENDER IMAGE:", img_url)html.append(f"""<img src="{img_url}"style="width:140px;height:110px;object-fit:cover;border-radius:6px;" />""")html.append("</div>")2 unmodified linesgr.HTML("".join(html))print("==============================")print("⚡ RENDER END")print("==============================\n")if __name__ == "__main__":
app.py+76-131