Spaces:
Sleeping
Sleeping
Update app.py
Browse files38 unmodified lines3940414243444515 unmodified lines616263646566675 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616714 unmodified lines1821831841851861871884 unmodified lines1931941951961971981992002012022036 unmodified lines21021121221321421521621721821922038 unmodified linesexcept: passdef upload_to_zepeto(file_path, z_id, z_pw):print(f"🔐 [Zepeto] Login Playwright...", flush=True)try:with sync_playwright() as p:browser = p.chromium.launch(headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'])15 unmodified linesif not jwt_token: return False, "Token Not Found"print(f"🚀 [Zepeto] Uploading...", flush=True)headers = {"Authorization": f"Bearer {jwt_token}"}with open(file_path, "rb") as f:res = requests.post(5 unmodified linesreturn (True, "Success") if res.status_code in [200, 201] else (False, f"HTTP {res.status_code}")except Exception as e: return False, f"Error: {str(e)}"# --- UNITY SCRIPT (VERSI NATIVE - TANPA ZEPETO SDK) ---def inject_testbuilder(project_path):# SAYA HAPUS SEMUA REFERENCE KE ZEPETO DAN FBX EXPORTER# Script ini murni pakai API Unity bawaan. DIJAMIN JALAN.script_content = r"""using UnityEngine;using UnityEditor;using System.IO;public class TestBuilder{static readonly string RAW_PATH = "Assets/InputRaw";static readonly string OUTPUT_DIR = "Assets/Output";public static void ManualConvert(){try {AssetDatabase.Refresh();string[] guids = AssetDatabase.FindAssets("t:Prefab", new[] { RAW_PATH });if (guids.Length == 0) {Debug.LogError("❌ No Prefab found in InputRaw");EditorApplication.Exit(1);return;}string prefabPath = AssetDatabase.GUIDToAssetPath(guids[0]);// Set nama AssetBundle (ini yang akan jadi file .zepeto)AssetImporter importer = AssetImporter.GetAtPath(prefabPath);importer.assetBundleName = "repacked_item.zepeto";if (!Directory.Exists(OUTPUT_DIR)) Directory.CreateDirectory(OUTPUT_DIR);Debug.Log("🚀 Building Native AssetBundle...");// Build pakai Target Windows64 (Paling Aman)BuildPipeline.BuildAssetBundles(OUTPUT_DIR, BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.StandaloneWindows64);Debug.Log("✅ Build Success!");EditorApplication.Exit(0);} catch (System.Exception e) {Debug.LogError($"❌ Critical Error: {e.Message}");EditorApplication.Exit(1);}}}"""target_path = os.path.join(project_path, "Assets", "Editor", "TestBuilder.cs")os.makedirs(os.path.dirname(target_path), exist_ok=True)with open(target_path, "w") as f: f.write(script_content)silent_chmod(target_path)# --- PIPELINE ---def process_pipeline(req: ConversionRequest):session_id = str(uuid.uuid4())[:8]3 unmodified linestry:# 1. DOWNLOAD & EXTRACTprint(f"📥 [DOWNLOAD] {req.filename}", flush=True)r = requests.get(req.file_url, timeout=60)with open(download_path, 'wb') as f: f.write(r.content)os.makedirs(extract_tmp)with zipfile.ZipFile(download_path, 'r') as z: z.extractall(extract_tmp)# 2. SETUP UNITY PROJECTprint("📦 [COPY] Cloning Project...", flush=True)shutil.copytree(BASE_PROJECT_PATH, SESSION_PATH, ignore=shutil.ignore_patterns("Library", "Temp", "Logs"))# --- PEMBERSIH SAMPAH (WAJIB ADA) ---# 1. Hapus Script bawaan user (.cs, .ts) biar Unity gak bingungprint("🧹 [SANITIZER] Deleting user scripts...", flush=True)for root, dirs, files in os.walk(extract_tmp):for file in files:if file.endswith((".cs", ".ts", ".js", ".asmdef", ".dll")):os.remove(os.path.join(root, file))# 2. HAPUS FOLDER UnityMeshSimplifier (INI YANG BIKIN ERROR CS0246)bad_folder = os.path.join(SESSION_PATH, "Assets", "UnityMeshSimplifier")if os.path.exists(bad_folder):print("🔥 [DELETE] Removing UnityMeshSimplifier folder...", flush=True)shutil.rmtree(bad_folder)inject_testbuilder(SESSION_PATH)# 3. MANIFEST CLEAN (MURNI UNITY)print("📜 [MANIFEST] Writing CLEAN manifest...", flush=True)manifest_path = os.path.join(SESSION_PATH, "Packages", "manifest.json")lock_path = os.path.join(SESSION_PATH, "Packages", "packages-lock.json")if os.path.exists(lock_path): os.remove(lock_path)14 unmodified lines}with open(manifest_path, 'w') as f: json.dump(clean_manifest, f, indent=2)# Pindahkan Assets Bersihtarget_input = os.path.join(SESSION_PATH, "Assets", "InputRaw")os.makedirs(target_input, exist_ok=True)for root, dirs, files in os.walk(extract_tmp):4 unmodified linessilent_chmod(SESSION_PATH)# 4. RUN UNITYprint("🚀 [UNITY] Repacking (Target: Windows64)...", flush=True)cmd_repack = [os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit","-projectPath", SESSION_PATH,"-executeMethod", "TestBuilder.ManualConvert","-logFile", "/dev/stdout","-no-sprite-atlas-cache","-job-worker-count", "1"6 unmodified linesif os.path.exists(target_file):success, msg = upload_to_zepeto(target_file, req.zepeto_id, req.zepeto_password)print(f"🎉 [DONE] Result: {msg}", flush=True)else:print("❌ [FAIL] No output file found!", flush=True)except Exception as e: print(f"❌ [CRITICAL] {e}", flush=True)finally:for p in [SESSION_PATH, download_path, extract_tmp]:if os.path.exists(p):38 unmodified lines3940414243444515 unmodified lines616263646566675 unmodified lines7374757677783 unmodified lines82838485868788899091929394959697989910010110210310410510610710810911011111211311414 unmodified lines1291301311321331341354 unmodified lines1401411421431441451461471481491506 unmodified lines15715815916016116216316416516616738 unmodified linesexcept: passdef upload_to_zepeto(file_path, z_id, z_pw):print(f"?? [Zepeto] Login Playwright...", flush=True)try:with sync_playwright() as p:browser = p.chromium.launch(headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'])15 unmodified linesif not jwt_token: return False, "Token Not Found"print(f"?? [Zepeto] Uploading...", flush=True)headers = {"Authorization": f"Bearer {jwt_token}"}with open(file_path, "rb") as f:res = requests.post(5 unmodified linesreturn (True, "Success") if res.status_code in [200, 201] else (False, f"HTTP {res.status_code}")except Exception as e: return False, f"Error: {str(e)}"# --- PIPELINE ---def process_pipeline(req: ConversionRequest):session_id = str(uuid.uuid4())[:8]3 unmodified linestry:# 1. DOWNLOAD & EXTRACTprint(f"?? [DOWNLOAD] {req.filename}", flush=True)r = requests.get(req.file_url, timeout=60)with open(download_path, 'wb') as f: f.write(r.content)os.makedirs(extract_tmp)with zipfile.ZipFile(download_path, 'r') as z: z.extractall(extract_tmp)# 2. SETUP UNITY PROJECTprint("?? [COPY] Cloning Project...", flush=True)# Script TestBuilder.cs SUDAH ADA di dalam BASE_PROJECT_PATH (karena kita tanam manual)# Jadi saat di-copy, script itu otomatis ikut. Tidak perlu inject lagi.shutil.copytree(BASE_PROJECT_PATH, SESSION_PATH, ignore=shutil.ignore_patterns("Library", "Temp", "Logs"))# --- PEMBERSIH HAMA (Wajib Ada) ---print("?? [CLEANER] Removing conflict folders...", flush=True)trash_folders = glob.glob(os.path.join(SESSION_PATH, "Assets", "**", "UnityMeshSimplifier"), recursive=True)trash_folders += glob.glob(os.path.join(SESSION_PATH, "Assets", "**", "Tests"), recursive=True)for folder in trash_folders:if os.path.exists(folder): shutil.rmtree(folder)# Hapus script userfor root, dirs, files in os.walk(extract_tmp):for file in files:if file.endswith((".cs", ".ts", ".js", ".asmdef", ".dll")):os.remove(os.path.join(root, file))# 3. MANIFEST CLEANprint("?? [MANIFEST] Writing CLEAN manifest...", flush=True)manifest_path = os.path.join(SESSION_PATH, "Packages", "manifest.json")lock_path = os.path.join(SESSION_PATH, "Packages", "packages-lock.json")if os.path.exists(lock_path): os.remove(lock_path)14 unmodified lines}with open(manifest_path, 'w') as f: json.dump(clean_manifest, f, indent=2)# Pindahkan Assetstarget_input = os.path.join(SESSION_PATH, "Assets", "InputRaw")os.makedirs(target_input, exist_ok=True)for root, dirs, files in os.walk(extract_tmp):4 unmodified linessilent_chmod(SESSION_PATH)# 4. RUN UNITYprint("?? [UNITY] Repacking...", flush=True)cmd_repack = [os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit","-projectPath", SESSION_PATH,"-executeMethod", "TestBuilder.ManualConvert", # Memanggil script yang kita tanam manual"-logFile", "/dev/stdout","-no-sprite-atlas-cache","-job-worker-count", "1"6 unmodified linesif os.path.exists(target_file):success, msg = upload_to_zepeto(target_file, req.zepeto_id, req.zepeto_password)print(f"?? [DONE] Result: {msg}", flush=True)else:print("? [FAIL] No output file found!", flush=True)except Exception as e: print(f"? [CRITICAL] {e}", flush=True)finally:for p in [SESSION_PATH, download_path, extract_tmp]:if os.path.exists(p):
app.py+22-75