Sada8888 commited on
Commit
c513be2
·
verified ·
1 Parent(s): 92d00f4

Create yml/ghibli.py

Browse files
Files changed (1) hide show
  1. yml/ghibli.py +132 -0
yml/ghibli.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import requests
4
+ import base64
5
+ from gradio_client import Client, handle_file
6
+
7
+ # دریافت متغیرهای محیطی ارسال شده از سمت گیت‌هاب اکشن
8
+ raw_prompt = os.environ.get('PROMPT', '')
9
+ run_id = os.environ.get('RUN_ID', '')
10
+ space_url = os.environ.get('SPACE_URL', '')
11
+ github_run_id = os.environ.get('GITHUB_RUN_ID', '')
12
+
13
+ # متد گزارش شکست فرآیند جهت فعال‌سازی مجدد رانرهای موازی در صورت بروز هرگونه خطا
14
+ def report_failure(error_msg):
15
+ try:
16
+ requests.post(
17
+ f"{space_url}/api/webhook/fail",
18
+ json={
19
+ "run_id": run_id,
20
+ "error": error_msg,
21
+ "event_type": "ghibli",
22
+ "client_payload": {
23
+ "prompt": raw_prompt,
24
+ "run_id": run_id,
25
+ "space_url": space_url
26
+ },
27
+ "github_run_id": github_run_id
28
+ },
29
+ timeout=15
30
+ )
31
+ except Exception as e:
32
+ print(f"Failed to report failure: {e}")
33
+
34
+ print('1. Decoding packed configurations from safe payload...')
35
+ if not raw_prompt.startswith("GHIBLICONFIG_"):
36
+ err_str = "Error: Invalid ghibli configuration payload signature."
37
+ print(err_str)
38
+ report_failure(err_str)
39
+ sys.exit(1)
40
+
41
+ # استخراج داده‌های رمزگذاری شده کاربر
42
+ config_str = raw_prompt[len("GHIBLICONFIG_"):]
43
+ parts = config_str.split("_")
44
+ config = {}
45
+ i = 0
46
+ while i < len(parts) - 1:
47
+ key = parts[i]
48
+ val = parts[i+1]
49
+ config[key] = val
50
+ i += 2
51
+
52
+ user_run_id = config.get("userRunId", run_id)
53
+ img_ext = config.get("imgExt", "png")
54
+
55
+ try:
56
+ b64_style = config.get("style", "")
57
+ style = base64.b64decode(b64_style).decode('utf-8')
58
+ except Exception as e:
59
+ style = "Studio Ghibli"
60
+
61
+ print(f' -> User Run ID: {user_run_id}')
62
+ print(f' -> Target style: "{style}"')
63
+
64
+ # آدرس‌دهی و دانلود تصویر پایه از فضای موقت فلاسک
65
+ img_url = f"{space_url}/static/images/{user_run_id}_ghibli_img.{img_ext}"
66
+ local_img = f"input_img.{img_ext}"
67
+
68
+ print('2. Downloading reference image from your Space...')
69
+ try:
70
+ req_img = requests.get(img_url, timeout=45)
71
+ if req_img.status_code != 200:
72
+ raise Exception(f"Image download failed. Status code: {req_img.status_code}")
73
+ with open(local_img, 'wb') as f:
74
+ f.write(req_img.content)
75
+ except Exception as download_err:
76
+ err_str = f"Error downloading source files: {download_err}"
77
+ print(err_str)
78
+ report_failure(err_str)
79
+ sys.exit(1)
80
+
81
+ # برقراری ارتباط با مدل پشتیبان OminiControl_Art
82
+ print('3. Connecting to Yuanshi/OminiControl_Art Space...')
83
+ try:
84
+ client = Client("Yuanshi/OminiControl_Art")
85
+
86
+ print('4. Generating cartoon image style...')
87
+ # ارسال به تابع تولید تصویر با همان پارامترهای دقیق گرادیو
88
+ result = client.predict(
89
+ style, # [0] استایل انتخابی کاربر
90
+ handle_file(local_img), # [1] تصویر ورودی
91
+ "High Quality", # [2] رزولوشن پردازش
92
+ 1.5, # [3] غلظت اثرپذیری استایل
93
+ "Auto", # [4] پیش‌پردازشگر
94
+ True, # [5] رندوم کردن سید خروجی
95
+ 42, # [6] سید عددی پایه
96
+ 20, # [7] تعداد گام‌های فرآیند انتشار
97
+ fn_index=7
98
+ )
99
+
100
+ # استخراج مسیر فایل ساخته شده در گرادیو کلاینت
101
+ image_path = None
102
+ if isinstance(result, list) and len(result) > 0:
103
+ image_path = result[0].get('image') or result[0].get('path') if isinstance(result[0], dict) else result[0]
104
+ elif isinstance(result, tuple) and len(result) > 0:
105
+ image_path = result[0]
106
+ elif isinstance(result, dict):
107
+ image_path = result.get('image') or result.get('path')
108
+ else:
109
+ image_path = result
110
+
111
+ if not image_path or not os.path.exists(str(image_path)):
112
+ raise Exception("Generated output image file not found or invalid.")
113
+
114
+ # ارسال تصویر نهایی به شکل وب‌پ فرمت به کنترل‌کننده موقت فلاسک
115
+ print('5. Uploading output image back to your Space...')
116
+ with open(image_path, 'rb') as f:
117
+ res_upload = requests.post(
118
+ f'{space_url}/api/webhook/upload',
119
+ data={'run_id': run_id, 'github_run_id': github_run_id, 'ext': 'webp'},
120
+ files={'file': f}
121
+ )
122
+
123
+ if res_upload.status_code == 200:
124
+ print('6. SUCCESS! Process complete.')
125
+ else:
126
+ raise Exception(f"Webhook upload failed. Status code: {res_upload.status_code}")
127
+
128
+ except Exception as e:
129
+ err_str = str(e)
130
+ print(f"CRITICAL ERROR during generation: {err_str}")
131
+ report_failure(err_str)
132
+ sys.exit(1)