Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines789101112136 unmodified lines20212223242526272829303132333435363738394041421 unmodified line444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642656 unmodified linesimport jsonimport uuidimport boto3from botocore.exceptions import NoCredentialsErrorfrom fastapi import FastAPI, BackgroundTasksfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel6 unmodified linesBASE_PROJECT_PATH = "/app/UnityProject"DEST_LICENSE_PATH = "/tmp/Unity_lic.ulf"# --- CONFIG CLOUDFLARE R2 (SUDAH DIISI) ---R2_CONFIG = {"account_id": "31f2970a3442da4e6f17f79064897226","access_key": "44613d17ec50941707a7ddd9b17944bc","secret_key": "50185c21ff5e4f53e412e2013305b6ab24b7eda16cc0d3dc66593eed64aa99a2","bucket_name": "zepeto", # <--- PASTIKAN BUCKET INI ADA DI R2 ABANG!"public_domain": "" # Isi jika punya custom domain (contoh: https://cdn.domain.com)}app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)class ConversionRequest(BaseModel):file_url: str1 unmodified linezepeto_id: strzepeto_password: str# --- FUNGSI UPLOAD R2 ---def upload_to_r2(file_path, original_filename):print("โ๏ธ [R2] Memulai upload ke Cloudflare R2...", flush=True)try:s3 = boto3.client('s3',endpoint_url=f"https://{R2_CONFIG['account_id']}.r2.cloudflarestorage.com",aws_access_key_id=R2_CONFIG['access_key'],aws_secret_access_key=R2_CONFIG['secret_key'])# Nama file di R2: builds/timestamp_namafile.zepetoobject_name = f"builds/{uuid.uuid4().hex[:8]}_{original_filename}.zepeto"s3.upload_file(file_path, R2_CONFIG['bucket_name'], object_name)# Generate URLif R2_CONFIG['public_domain']:url = f"{R2_CONFIG['public_domain']}/{object_name}"else:# Default R2 URL structureurl = f"https://{R2_CONFIG['account_id']}.r2.cloudflarestorage.com/{R2_CONFIG['bucket_name']}/{object_name}"print(f"โ [R2] Upload Sukses! URL BUKTI: {url}", flush=True)return urlexcept Exception as e:print(f"โ [R2] Upload Gagal: {str(e)}", flush=True)return None# --- FUNGSI UPLOAD ZEPETO ---def 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'])context = browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")page = context.new_page()page.goto("https://account.zepeto.me/signin?sm=1", timeout=60000)page.fill('input[name="userId"]', z_id)page.fill('input[type="password"]', z_pw)page.click('button[type="submit"]')try: page.wait_for_url(lambda u: "signin" not in u, timeout=60000)except:browser.close()return False, "Login Timeout"cookies = {c['name']: c['value'] for c in context.cookies()}jwt_token = cookies.get('token') or cookies.get('jwt')browser.close()if not jwt_token: return False, "Token Not Found"print(f"๐ [Zepeto] Uploading via API...", flush=True)headers = {"Authorization": f"Bearer {jwt_token}"}with open(file_path, "rb") as f:res = requests.post("https://cf-api-studio.zepeto.me/api/items",headers=headers,files={"file": (os.path.basename(file_path), f, "application/octet-stream")},timeout=120)return (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 UTAMA ---def process_pipeline(req: ConversionRequest):session_id = str(uuid.uuid4())[:8]SESSION_PATH = f"/tmp/Project_{session_id}"11 unmodified linesprint("๐ฆ [COPY] Cloning Project...", flush=True)shutil.copytree(BASE_PROJECT_PATH, SESSION_PATH, ignore=shutil.ignore_patterns("Library", "Temp", "Logs"))# Cleanertrash_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)# Flattenertarget_input = os.path.join(SESSION_PATH, "Assets", "InputRaw")os.makedirs(target_input, exist_ok=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))print("๐ [FLATTENER] Moving files...", flush=True)for root, dirs, files in os.walk(extract_tmp):for file in files:if file.startswith(".") or file.endswith(".meta"): continuesrc = os.path.join(root, file)dst = os.path.join(target_input, file)if os.path.exists(dst): dst = os.path.join(target_input, f"{uuid.uuid4().hex[:4]}_{file}")shutil.copy(src, dst)# Manifestmanifest_path = os.path.join(SESSION_PATH, "Packages", "manifest.json")if os.path.exists(os.path.join(SESSION_PATH, "Packages", "packages-lock.json")):os.remove(os.path.join(SESSION_PATH, "Packages", "packages-lock.json"))clean_manifest = {"dependencies": {"com.unity.render-pipelines.universal": "14.0.10","com.unity.scriptablebuildpipeline": "1.21.1","com.unity.textmeshpro": "3.0.6","com.unity.ugui": "1.0.0","com.unity.modules.assetbundle": "1.0.0","com.unity.modules.imageconversion": "1.0.0","com.unity.modules.jsonserialize": "1.0.0","com.unity.modules.unitywebrequest": "1.0.0","com.unity.modules.unitywebrequestassetbundle": "1.0.0","com.unity.modules.unitywebrequesttexture": "1.0.0"}}with open(manifest_path, 'w') as f: json.dump(clean_manifest, f, indent=2)# Inject Script (Target Linux)script_path = os.path.join(SESSION_PATH, "Assets", "Editor", "TestBuilder.cs")os.makedirs(os.path.dirname(script_path), exist_ok=True)csharp_code = 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() {Debug.Log("๐ [NATIVE] STARTING BUILD (TARGET: LINUX64)...");try {AssetDatabase.Refresh();string[] guids = AssetDatabase.FindAssets("t:Prefab t:Model", new[] { RAW_PATH });if (guids.Length == 0) {Debug.LogError("โ [FATAL] No Assets Found!");EditorApplication.Exit(1);return;}string assetPath = AssetDatabase.GUIDToAssetPath(guids[0]);AssetImporter importer = AssetImporter.GetAtPath(assetPath);importer.assetBundleName = "repacked_item.zepeto";if (!Directory.Exists(OUTPUT_DIR)) Directory.CreateDirectory(OUTPUT_DIR);// TARGET LINUX64var manifest = BuildPipeline.BuildAssetBundles(OUTPUT_DIR, BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.StandaloneLinux64);if (manifest == null) { Debug.LogError("โ Build Failed"); EditorApplication.Exit(1); }else { Debug.Log("๐ Build Finished!"); EditorApplication.Exit(0); }} catch (System.Exception e) { Debug.LogError(e.Message); EditorApplication.Exit(1); }}}"""with open(script_path, "w") as f: f.write(csharp_code)# EXECUTE UNITYprint(f"๐ [UNITY] Repacking...", flush=True)cmd_repack = [os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit","-projectPath", SESSION_PATH, "-executeMethod", "TestBuilder.ManualConvert","-logFile", unity_log_file, "-no-sprite-atlas-cache", "-job-worker-count", "1"]subprocess.run(cmd_repack, check=False)# Print Log (Filtered)print("\n" + "="*50, flush=True)print("๐ LOG DIAGNOSTICS:", flush=True)if os.path.exists(unity_log_file):with open(unity_log_file, "r", encoding="utf-8", errors="ignore") as f:for line in f:if any(k in line for k in ["[NATIVE]", "Error", "Exception", "Fail", "CRITICAL"]):if "Shader" in line or "Metal" in line: continueprint(line.strip(), flush=True)else: print("โ Log Not Found")print("="*50 + "\n", flush=True)# OUTPUT CHECK & UPLOADoutput_dir = os.path.join(SESSION_PATH, "Assets", "Output")target_file = os.path.join(output_dir, "repacked_item.zepeto")if os.path.exists(target_file):print(f"๐ [DONE] File generated: {target_file}", flush=True)# 1. UPLOAD KE R2 (BACKUP/BUKTI)upload_to_r2(target_file, req.filename)# 2. UPLOAD KE ZEPETOsuccess, msg = upload_to_zepeto(target_file, req.zepeto_id, req.zepeto_password)print(f"๐ [ZEPETO] Result: {msg}", flush=True)else:print("โ [FAIL] No output file.", flush=True)except Exception as e: print(f"โ [CRITICAL] {e}", flush=True)finally:for p in [SESSION_PATH, download_path, extract_tmp, unity_log_file]:if os.path.exists(p):if os.path.isdir(p): shutil.rmtree(p)else: os.remove(p)@app.on_event("startup")async def startup_event():try:ulf_files = glob.glob("/app/*.ulf")if ulf_files:shutil.copy(ulf_files[0], DEST_LICENSE_PATH)os.chmod(DEST_LICENSE_PATH, 0o666)subprocess.run([os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit", "-manualLicenseFile", DEST_LICENSE_PATH], check=False)except: pass@app.post("/convert")async def api_convert(req: ConversionRequest, background_tasks: BackgroundTasks):background_tasks.add_task(process_pipeline, req)return {"status": "success"}6 unmodified lines7891011126 unmodified lines19202122232425262728293031323334351 unmodified line37383940414243444546474849505152535411 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851866 unmodified linesimport jsonimport uuidimport boto3from fastapi import FastAPI, BackgroundTasksfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel6 unmodified linesBASE_PROJECT_PATH = "/app/UnityProject"DEST_LICENSE_PATH = "/tmp/Unity_lic.ulf"# --- CONFIG CLOUDFLARE R2 ---R2_CONFIG = {"account_id": "31f2970a3442da4e6f17f79064897226","access_key": "44613d17ec50941707a7ddd9b17944bc","secret_key": "50185c21ff5e4f53e412e2013305b6ab24b7eda16cc0d3dc66593eed64aa99a2","bucket_name": "zepeto-builds","public_domain": ""}app = FastAPI()app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])class ConversionRequest(BaseModel):file_url: str1 unmodified linezepeto_id: strzepeto_password: strdef upload_to_r2(file_path, original_filename):print("โ๏ธ [R2] Uploading...", flush=True)try:s3 = boto3.client('s3', endpoint_url=f"https://{R2_CONFIG['account_id']}.r2.cloudflarestorage.com",aws_access_key_id=R2_CONFIG['access_key'], aws_secret_access_key=R2_CONFIG['secret_key'])object_name = f"builds/{uuid.uuid4().hex[:8]}_{original_filename}.zepeto"s3.upload_file(file_path, R2_CONFIG['bucket_name'], object_name)url = f"https://{R2_CONFIG['account_id']}.r2.cloudflarestorage.com/{R2_CONFIG['bucket_name']}/{object_name}"print(f"โ [R2] Sukses: {url}", flush=True)return urlexcept Exception as e: print(f"โ [R2] Gagal: {e}", flush=True); return Nonedef process_pipeline(req: ConversionRequest):session_id = str(uuid.uuid4())[:8]SESSION_PATH = f"/tmp/Project_{session_id}"11 unmodified linesprint("๐ฆ [COPY] Cloning Project...", flush=True)shutil.copytree(BASE_PROJECT_PATH, SESSION_PATH, ignore=shutil.ignore_patterns("Library", "Temp", "Logs"))# --- CLEANER SURGICAL (Hanya hapus Tests agar Simplifier tetap ada) ---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)# --- FLATTENER ---target_input = os.path.join(SESSION_PATH, "Assets", "InputRaw")os.makedirs(target_input, exist_ok=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))elif not file.startswith(".") and not file.endswith(".meta"):shutil.copy(os.path.join(root, file), os.path.join(target_input, file))# --- MANIFEST ---manifest_path = os.path.join(SESSION_PATH, "Packages", "manifest.json")clean_manifest = {"dependencies": {"com.unity.render-pipelines.universal": "14.0.10","com.unity.scriptablebuildpipeline": "1.21.1","com.unity.textmeshpro": "3.0.6","com.unity.ugui": "1.0.0","com.unity.modules.assetbundle": "1.0.0","com.unity.modules.imageconversion": "1.0.0"}}with open(manifest_path, 'w') as f: json.dump(clean_manifest, f, indent=2)# --- INJECT TESTBUILDER DENGAN MESH SIMPLIFIER ---script_path = os.path.join(SESSION_PATH, "Assets", "Editor", "TestBuilder.cs")os.makedirs(os.path.dirname(script_path), exist_ok=True)with open(script_path, "w") as f:f.write(r"""using UnityEngine;using UnityEditor;using System.IO;using System.Linq;using UnityMeshSimplifier;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[] assets = Directory.GetFiles(RAW_PATH, "*.*", SearchOption.AllDirectories).Where(s => !s.EndsWith(".meta")).ToArray();// 1. PROSES PERAMPINGAN POLYGON (MESH SIMPLIFICATION)foreach (string path in assets) {if (path.EndsWith(".prefab") || path.EndsWith(".fbx") || path.EndsWith(".obj")) {GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);if (go != null) {Debug.Log($"โ๏ธ [NATIVE] Merampingkan Poligon: {path}");SimplifyMeshInGameObject(go);}}// Beri label bundle ke SEMUA fileAssetImporter.GetAtPath(path).assetBundleName = "repacked_item.zepeto";}// 2. BUILD ASSETBUNDLEif (!Directory.Exists(OUTPUT_DIR)) Directory.CreateDirectory(OUTPUT_DIR);BuildPipeline.BuildAssetBundles(OUTPUT_DIR, BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.StandaloneLinux64);EditorApplication.Exit(0);} catch (System.Exception e) { Debug.LogError(e.Message); EditorApplication.Exit(1); }}static void SimplifyMeshInGameObject(GameObject go) {var meshFilters = go.GetComponentsInChildren<MeshFilter>();foreach (var mf in meshFilters) {if (mf.sharedMesh != null) {var meshSimplifier = new UnityMeshSimplifier.MeshSimplifier();meshSimplifier.Initialize(mf.sharedMesh);meshSimplifier.SimplifyMesh(0.5f); // <--- KECILKAN 50%mf.sharedMesh = meshSimplifier.ToMesh();}}var skinnedMeshes = go.GetComponentsInChildren<SkinnedMeshRenderer>();foreach (var smr in skinnedMeshes) {if (smr.sharedMesh != null) {var meshSimplifier = new UnityMeshSimplifier.MeshSimplifier();meshSimplifier.Initialize(smr.sharedMesh);meshSimplifier.SimplifyMesh(0.5f); // <--- KECILKAN 50%smr.sharedMesh = meshSimplifier.ToMesh();}}}}""")# EXECUTE UNITYprint(f"๐ [UNITY] Repacking & Simplifying...", flush=True)subprocess.run([os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit", "-projectPath", SESSION_PATH,"-executeMethod", "TestBuilder.ManualConvert", "-logFile", unity_log_file], check=False)# OUTPUT CHECKtarget_file = os.path.join(SESSION_PATH, "Assets", "Output", "repacked_item.zepeto")if os.path.exists(target_file):print(f"๐ [DONE] Size rimpang!", flush=True)upload_to_r2(target_file, req.filename)else: print("โ [FAIL] No output file.", flush=True)except Exception as e: print(f"โ [CRITICAL] {e}", flush=True)finally:for p in [SESSION_PATH, download_path, extract_tmp, unity_log_file]:if os.path.exists(p): shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)@app.on_event("startup")async def startup_event():try:ulf = glob.glob("/app/*.ulf")if ulf: shutil.copy(ulf[0], DEST_LICENSE_PATH); os.chmod(DEST_LICENSE_PATH, 0o666)subprocess.run([os.environ["UNITY_PATH"], "-batchmode", "-nographics", "-quit", "-manualLicenseFile", DEST_LICENSE_PATH], check=False)except: pass@app.post("/convert")async def api_convert(req: ConversionRequest, background_tasks: BackgroundTasks):background_tasks.add_task(process_pipeline, req); return {"status": "success"}
app.py+83-162