Sada8888 commited on
Commit
dc3303a
·
verified ·
1 Parent(s): 513e9e9

Create yml/gostaresh-tasvir.py

Browse files
Files changed (1) hide show
  1. yml/gostaresh-tasvir.py +168 -0
yml/gostaresh-tasvir.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # تابع گزارش خطای احتمالی جهت اجرای سیستم خودکار تلاش مجدد (Retry)
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": "gostaresh-tasvir",
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 configuration from payload...')
35
+ if not raw_prompt.startswith("OUTPAINTCONFIG_"):
36
+ err_str = "Error: Invalid outpaint configuration payload signature."
37
+ print(err_str)
38
+ report_failure(err_str)
39
+ sys.exit(1)
40
+
41
+ # استخراج داده‌ها از توکن رمزگذاری شده
42
+ config_str = raw_prompt[len("OUTPAINTCONFIG_"):]
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
+ width = int(config.get("width", "1024"))
55
+ height = int(config.get("height", "1024"))
56
+ raw_steps = int(config.get("steps", "8"))
57
+
58
+ # تعدیل خودکار تعداد گام‌ها جهت هماهنگی با محدودیت ۴ تا ۱۲ سرور میزبان
59
+ outpaint_steps = max(4, min(12, raw_steps))
60
+
61
+ expand_left = config.get("left") == "true"
62
+ expand_right = config.get("right") == "true"
63
+ expand_top = config.get("top") == "true"
64
+ expand_bottom = config.get("bottom") == "true"
65
+
66
+ # رمزگشایی پرامپت فارسی
67
+ try:
68
+ b64_prompt = config.get("prompt", "")
69
+ b64_prompt += "=" * ((4 - len(b64_prompt) % 4) % 4)
70
+ persian_prompt = base64.b64decode(b64_prompt).decode('utf-8')
71
+ except Exception as e:
72
+ persian_prompt = ""
73
+
74
+ print(f" -> User Run ID: {user_run_id}")
75
+ print(f" -> Persian Prompt: {persian_prompt}")
76
+ print(f" -> Enforced Steps (within 4-12 range): {outpaint_steps}")
77
+
78
+ # ترجمه مستقیم متن فارسی به انگلیسی بدون وابستگی به کتابخانه‌ها
79
+ english_prompt = ""
80
+ if persian_prompt.strip():
81
+ try:
82
+ translate_url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q={requests.utils.quote(persian_prompt)}"
83
+ r_trans = requests.get(translate_url, timeout=15)
84
+ english_prompt = r_trans.json()[0][0][0]
85
+ print(f" -> Translated Prompt: {english_prompt}")
86
+ except Exception as trans_err:
87
+ print(f" -> Translation failed, using original: {trans_err}")
88
+ english_prompt = persian_prompt
89
+
90
+ # دانلود تصویر مرجع آپلود شده از فضای داکر
91
+ img_url = f"{space_url}/static/images/{user_run_id}_outpaint_img.{img_ext}"
92
+ local_img = f"input.{img_ext}"
93
+
94
+ print(f"2. Downloading source image from: {img_url}")
95
+ try:
96
+ req_img = requests.get(img_url, timeout=45)
97
+ if req_img.status_code != 200:
98
+ raise Exception(f"Image download failed. Status code: {req_img.status_code}")
99
+ with open(local_img, 'wb') as f:
100
+ f.write(req_img.content)
101
+ except Exception as download_err:
102
+ err_str = f"Error downloading source files: {download_err}"
103
+ print(err_str)
104
+ report_failure(err_str)
105
+ sys.exit(1)
106
+
107
+ # شبیه‌سازی اتصال مستقیم به موتور هوش مصنوعی گسترش تصویر
108
+ print('3. Connecting to Outpaint Space...')
109
+ try:
110
+ client = Client("fffiloni/diffusers-image-outpaint")
111
+
112
+ print('4. Generating expanded image...')
113
+ # تطبیق دقیق آرگومان‌های ارسالی با ساختار ورودی‌های تابع infer در هاگینگ‌فیس
114
+ result = client.predict(
115
+ handle_file(local_img), # 0: image (PIL Image)
116
+ width, # 1: width (int)
117
+ height, # 2: height (int)
118
+ 10, # 3: overlap_percentage (int)
119
+ outpaint_steps, # 4: num_inference_steps (int)
120
+ "Full", # 5: resize_option (str)
121
+ 50, # 6: custom_resize_percentage (int)
122
+ english_prompt, # 7: prompt_input (str)
123
+ "Middle", # 8: alignment (str)
124
+ expand_left, # 9: overlap_left (bool)
125
+ expand_right, # 10: overlap_right (bool)
126
+ expand_top, # 11: overlap_top (bool)
127
+ expand_bottom, # 12: overlap_bottom (bool)
128
+ fn_index=7
129
+ )
130
+
131
+ # استخراج صحیح فایل نهایی تولید شده از ساختار گالری
132
+ image_path = None
133
+ if isinstance(result, (list, tuple)):
134
+ if len(result) > 0:
135
+ item = result[-1]
136
+ if isinstance(item, (list, tuple)):
137
+ image_path = item[0]
138
+ elif isinstance(item, dict):
139
+ image_path = item.get('path') or item.get('url')
140
+ else:
141
+ image_path = item
142
+ elif isinstance(result, dict):
143
+ image_path = result.get('path') or result.get('url')
144
+ else:
145
+ image_path = result
146
+
147
+ if not image_path or not os.path.exists(str(image_path)):
148
+ raise Exception("Generated expanded image file not found or invalid.")
149
+
150
+ # ارسال فایل نهایی تولید شده به هاست فلاسک با پسوند مناسب
151
+ print('5. Uploading output back to your Space...')
152
+ with open(image_path, 'rb') as f:
153
+ res_upload = requests.post(
154
+ f'{space_url}/api/webhook/upload',
155
+ data={'run_id': run_id, 'github_run_id': github_run_id, 'ext': 'png'},
156
+ files={'file': f}
157
+ )
158
+
159
+ if res_upload.status_code == 200:
160
+ print('6. SUCCESS! Process complete.')
161
+ else:
162
+ raise Exception(f"Webhook upload failed. Status code: {res_upload.status_code}")
163
+
164
+ except Exception as e:
165
+ err_str = str(e)
166
+ print(f"CRITICAL ERROR during generation: {err_str}")
167
+ report_failure(err_str)
168
+ sys.exit(1)