Spaces:
webzepetoku
/
Sleeping

webzepetoku commited on
Commit
ef96d38
Β·
verified Β·
1 Parent(s): 6e54bc2

Update UnityProject/app.py

Browse files
Files changed (1) hide show
  1. UnityProject/app.py +122 -110
UnityProject/app.py CHANGED
@@ -1,110 +1,122 @@
1
- import os
2
- import shutil
3
- import subprocess
4
- import json
5
- from fastapi import FastAPI, BackgroundTasks, HTTPException
6
- from pydantic import BaseModel
7
- from google.oauth2 import service_account
8
- from googleapiclient.discovery import build
9
- from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
10
-
11
- app = FastAPI()
12
-
13
- # --- KONFIGURASI UNITY (Milik Admin SaaS) ---
14
- UNITY_PATH = "/opt/unity/Editor/Unity"
15
- UNITY_EMAIL = os.getenv("UNITY_EMAIL")
16
- UNITY_PASSWORD = os.getenv("UNITY_PASSWORD")
17
- PROJECT_PATH = "/app/UnityProject" # Folder template yang di-upload di awal
18
-
19
- # --- MODEL DATA DARI HONO ---
20
- class ConversionRequest(BaseModel):
21
- file_id: str # ID File FBX di Google Drive User
22
- folder_id: str # ID Folder Output di Google Drive User
23
- google_creds: dict # JSON Service Account User (Dikirim oleh Hono)
24
- filename: str # Nama file asli (misal: baju.fbx)
25
-
26
- # --- 1. AKTIVASI LISENSI SAAT SERVER NYALA ---
27
- @app.on_event("startup")
28
- async def startup_event():
29
- print("πŸ”„ [SYSTEM] Melakukan Aktivasi Unity...")
30
- if not UNITY_EMAIL or not UNITY_PASSWORD:
31
- print("❌ [ERROR] Email/Password Unity belum diset di Secret!")
32
- return
33
-
34
- cmd = [
35
- UNITY_PATH, "-batchmode", "-nographics",
36
- "-username", UNITY_EMAIL, "-password", UNITY_PASSWORD,
37
- "-quit", "-logFile", "-"
38
- ]
39
- subprocess.run(cmd, capture_output=True)
40
- print("βœ… [SYSTEM] Unity Siap Digunakan!")
41
-
42
- # --- 2. FUNGSI UTAMA: PROSES UNITY ---
43
- def process_unity_conversion(req: ConversionRequest):
44
- print(f"πŸš€ [JOB] Memulai proses untuk file: {req.filename}")
45
-
46
- # A. AUTH GOOGLE DRIVE (Pake Credential User)
47
- try:
48
- creds = service_account.Credentials.from_service_account_info(req.google_creds)
49
- service = build('drive', 'v3', credentials=creds)
50
- except Exception as e:
51
- print(f"❌ [AUTH] Gagal login Google Drive User: {e}")
52
- return
53
-
54
- # B. DOWNLOAD FBX DARI DRIVE USER
55
- input_path = os.path.join(PROJECT_PATH, "Assets", req.filename)
56
- try:
57
- request = service.files().get_media(fileId=req.file_id)
58
- with open(input_path, "wb") as fh:
59
- downloader = MediaIoBaseDownload(fh, request)
60
- done = False
61
- while done is False:
62
- status, done = downloader.next_chunk()
63
- print(f"πŸ“₯ [DOWNLOAD] Berhasil download ke: {input_path}")
64
- except Exception as e:
65
- print(f"❌ [DOWNLOAD] Gagal download file: {e}")
66
- return
67
-
68
- # C. JALANKAN UNITY CONVERSION
69
- # Pastikan script TestBuilder.cs sudah dimodifikasi untuk menerima -outputFile juga jika perlu
70
- cmd = [
71
- UNITY_PATH, "-batchmode", "-nographics",
72
- "-projectPath", PROJECT_PATH,
73
- "-executeMethod", "TestBuilder.ManualConvert",
74
- "-inputFile", req.filename,
75
- "-quit", "-logFile", "-"
76
- ]
77
- proc = subprocess.run(cmd, capture_output=True, text=True)
78
-
79
- # Cek apakah berhasil
80
- output_filename = req.filename.replace(".fbx", ".zepeto")
81
- output_local_path = os.path.join(PROJECT_PATH, "output", output_filename)
82
-
83
- if os.path.exists(output_local_path):
84
- print("βœ… [UNITY] Build Sukses!")
85
-
86
- # D. UPLOAD BALIK KE DRIVE USER
87
- file_metadata = {
88
- 'name': output_filename,
89
- 'parents': [req.folder_id] # Masuk ke folder ZEPETO_OUTPUT user
90
- }
91
- media = MediaFileUpload(output_local_path, mimetype='application/octet-stream')
92
- try:
93
- file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
94
- print(f"πŸ“€ [UPLOAD] Sukses upload ke Drive User! File ID: {file.get('id')}")
95
- except Exception as e:
96
- print(f"❌ [UPLOAD] Gagal upload ke Drive: {e}")
97
- else:
98
- print("❌ [UNITY] Build Gagal. Cek Log:")
99
- print(proc.stdout)
100
-
101
- # E. CLEANUP (Hapus file lokal biar RAM lega)
102
- # if os.path.exists(input_path): os.remove(input_path)
103
- # if os.path.exists(output_local_path): os.remove(output_local_path)
104
-
105
- # --- 3. ENDPOINT API (Ditembak oleh Hono) ---
106
- @app.post("/convert")
107
- async def api_convert(req: ConversionRequest, background_tasks: BackgroundTasks):
108
- # Jalankan di background agar Hono tidak timeout nungguin Unity
109
- background_tasks.add_task(process_unity_conversion, req)
110
- return {"status": "queued", "message": "Proses dimulai di background"}
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import json
5
+ import time
6
+ import requests
7
+ from fastapi import FastAPI, BackgroundTasks, HTTPException, Request
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from pydantic import BaseModel
10
+ from playwright.sync_api import sync_playwright
11
+
12
+ app = FastAPI()
13
+
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ # --- KONFIGURASI ---
23
+ UNITY_PATH = "/opt/unity/Editor/Unity"
24
+ PROJECT_PATH = "/app/UnityProject"
25
+ TEMP_DIR = "/tmp/zepeto_work"
26
+ os.makedirs(TEMP_DIR, exist_ok=True)
27
+
28
+ # --- MODEL DATA (Sesuai dengan kiriman Cloudflare + Cloudinary) ---
29
+ class ConversionRequest(BaseModel):
30
+ file_url: str # URL dari Cloudinary
31
+ filename: str # Nama file (contoh: baju_keren.fbx)
32
+ zepeto_id: str
33
+ zepeto_password: str
34
+
35
+ # --- FUNGSI: LOGIN & UPLOAD KE ZEPETO STUDIO ---
36
+ def upload_to_zepeto(file_path, z_id, z_pw):
37
+ print(f"πŸ” [Zepeto] Mencoba login untuk: {z_id}")
38
+ try:
39
+ with sync_playwright() as p:
40
+ browser = p.chromium.launch(headless=True, args=['--no-sandbox'])
41
+ context = browser.new_context(user_agent="Mozilla/5.0...")
42
+ page = context.new_page()
43
+
44
+ # Login Process
45
+ page.goto("https://account.zepeto.me/signin?sm=1")
46
+ page.fill('input[name="userId"]', z_id)
47
+ page.fill('input[type="password"]', z_pw)
48
+ page.click('button[type="submit"]')
49
+
50
+ # Tunggu Token/Cookie
51
+ page.wait_for_url(lambda u: "signin" not in u, timeout=15000)
52
+ cookies = context.cookies()
53
+ jwt_token = next((c['value'] for c in cookies if c['name'] == 'token'), None)
54
+ browser.close()
55
+
56
+ if not jwt_token:
57
+ return False, "Gagal mendapatkan JWT Token"
58
+
59
+ # API Upload Zepeto Studio
60
+ print("πŸš€ [Zepeto] Mengirim file ke Studio API...")
61
+ upload_url = "https://cf-api-studio.zepeto.me/api/items"
62
+ headers = {"Authorization": f"Bearer {jwt_token}"}
63
+
64
+ with open(file_path, "rb") as f:
65
+ files = {"file": (os.path.basename(file_path), f, "application/octet-stream")}
66
+ res = requests.post(upload_url, headers=headers, files=files)
67
+
68
+ if res.status_code in [200, 201]:
69
+ return True, "Sukses Upload"
70
+ else:
71
+ return False, f"API Error: {res.text}"
72
+ except Exception as e:
73
+ return False, str(e)
74
+
75
+ # --- FUNGSI UTAMA: DOWNLOAD -> UNITY -> UPLOAD ---
76
+ def process_pipeline(req: ConversionRequest):
77
+ local_fbx = os.path.join(PROJECT_PATH, "Assets", req.filename)
78
+ output_filename = req.filename.replace(".fbx", ".zepeto")
79
+ local_zepeto = os.path.join(PROJECT_PATH, "output", output_filename)
80
+
81
+ try:
82
+ # 1. DOWNLOAD DARI CLOUDINARY
83
+ print(f"πŸ“₯ [Cloudinary] Downloading: {req.filename}")
84
+ r = requests.get(req.file_url, stream=True)
85
+ with open(local_fbx, 'wb') as f:
86
+ for chunk in r.iter_content(chunk_size=8192):
87
+ f.write(chunk)
88
+
89
+ # 2. JALANKAN UNITY (Konversi & Optimasi Poligon)
90
+ print("βš™οΈ [Unity] Memulai konversi & optimasi...")
91
+ # Perhatikan: Method C# harus menangani decimation/polygon reduction
92
+ cmd = [
93
+ UNITY_PATH, "-batchmode", "-nographics",
94
+ "-projectPath", PROJECT_PATH,
95
+ "-executeMethod", "TestBuilder.ManualConvert",
96
+ "-inputFile", req.filename,
97
+ "-quit", "-logFile", "-"
98
+ ]
99
+ result = subprocess.run(cmd, capture_output=True, text=True)
100
+
101
+ if not os.path.exists(local_zepeto):
102
+ print(f"❌ [Unity] Gagal. Log: {result.stdout}")
103
+ return
104
+
105
+ # 3. UPLOAD KE ZEPETO STUDIO
106
+ success, msg = upload_to_zepeto(local_zepeto, req.z_id, req.z_pw)
107
+
108
+ if success:
109
+ print(f"βœ… [FINAL] {req.filename} Berhasil dikirim ke Zepeto!")
110
+ else:
111
+ print(f"❌ [FINAL] Gagal upload ke Zepeto Studio: {msg}")
112
+
113
+ except Exception as e:
114
+ print(f"❌ [CRITICAL] Pipeline Error: {e}")
115
+ finally:
116
+ # Cleanup
117
+ if os.path.exists(local_fbx): os.remove(local_fbx)
118
+
119
+ @app.post("/convert")
120
+ async def api_convert(req: ConversionRequest, background_tasks: BackgroundTasks):
121
+ background_tasks.add_task(process_pipeline, req)
122
+ return {"status": "success", "message": "Proses konversi dan upload Zepeto dimulai di background"}