Sada8888 commited on
Commit
10ededa
·
verified ·
1 Parent(s): 78169c4

Create yml/shabihsazi-sada.py

Browse files
Files changed (1) hide show
  1. yml/shabihsazi-sada.py +176 -0
yml/shabihsazi-sada.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "shabihsazi-sada",
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("VOICECONFIG_"):
36
+ err_str = "Error: Invalid voice cloning configuration payload signature."
37
+ print(err_str)
38
+ report_failure(err_str)
39
+ sys.exit(1)
40
+
41
+ # استخراج داده‌ها از توکن رمزگذاری شده بدون فاصله
42
+ config_str = raw_prompt[len("VOICECONFIG_"):]
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
+ aud_ext = config.get("audExt", "wav")
54
+ language = config.get("lang", "Auto")
55
+
56
+ # رمزگشایی متن مرجع (در صورت وجود)
57
+ try:
58
+ b64_ref = config.get("refText", "")
59
+ b64_ref += "=" * ((4 - len(b64_ref) % 4) % 4)
60
+ ref_text = base64.b64decode(b64_ref).decode('utf-8')
61
+ except Exception:
62
+ ref_text = ""
63
+
64
+ # رمزگشایی متن نهایی برای شبیه‌سازی
65
+ try:
66
+ b64_prompt = config.get("prompt", "")
67
+ b64_prompt += "=" * ((4 - len(b64_prompt) % 4) % 4)
68
+ persian_prompt = base64.b64decode(b64_prompt).decode('utf-8')
69
+ except Exception as e:
70
+ persian_prompt = ""
71
+
72
+ print(f" -> User Run ID: {user_run_id}")
73
+ print(f" -> Target Text: {persian_prompt}")
74
+ print(f" -> Reference Transcription: {ref_text}")
75
+ print(f" -> Target Language: {language}")
76
+
77
+ # دانلود فایل صوتی مرجع از هاست فلاسک
78
+ img_url = f"{space_url}/static/images/{user_run_id}_voice_ref.{aud_ext}"
79
+ local_img = f"input.{aud_ext}"
80
+
81
+ print(f"2. Downloading reference audio from: {img_url}")
82
+ try:
83
+ req_img = requests.get(img_url, timeout=45)
84
+ if req_img.status_code != 200:
85
+ raise Exception(f"Reference audio download failed. Status code: {req_img.status_code}")
86
+ with open(local_img, 'wb') as f:
87
+ f.write(req_img.content)
88
+ except Exception as download_err:
89
+ err_str = f"Error downloading source files: {download_err}"
90
+ print(err_str)
91
+ report_failure(err_str)
92
+ sys.exit(1)
93
+
94
+ # برقراری ارتباط مستقیم با مدل شبیه‌سازی صدا
95
+ print('3. Connecting to OmniVoice Space...')
96
+ try:
97
+ hf_token = os.environ.get('HF_TOKEN', '')
98
+ if hf_token:
99
+ client = Client("k2-fsa/OmniVoice", token=hf_token)
100
+ else:
101
+ client = Client("k2-fsa/OmniVoice")
102
+
103
+ print('4. Dynamically locating the 12-input clone endpoint...')
104
+ # اسکن هوشمند متادیتای اندپوینت‌های هاگینگ‌فیس جهت پیدا کردن اتصالات کلون صدا
105
+ fn_index = None
106
+ api_name = None
107
+
108
+ dependencies = client.config.get("dependencies", [])
109
+ for dep in dependencies:
110
+ inputs = dep.get("inputs", [])
111
+ if len(inputs) == 12:
112
+ api_name = dep.get("api_name")
113
+ fn_index = dep.get("id")
114
+ break
115
+
116
+ # ساختار دهی نوع فراخوانی بر اساس وجود یا عدم وجود نام اختصاصی
117
+ endpoint_arg = {}
118
+ if api_name:
119
+ endpoint_arg["api_name"] = f"/{api_name}"
120
+ print(f" -> Selected endpoint by API Name: /{api_name}")
121
+ elif fn_index is not None:
122
+ endpoint_arg["fn_index"] = fn_index
123
+ print(f" -> Selected endpoint by Function Index: {fn_index}")
124
+ else:
125
+ # حالت پیش‌فرض برای پیشگیری از توقف فرآیند
126
+ endpoint_arg["fn_index"] = 0
127
+ print(" -> Warning: Could not locate 12-input endpoint. Falling back to fn_index 0.")
128
+
129
+ print('5. Generating synthesized cloned speech...')
130
+ result = client.predict(
131
+ persian_prompt, # 1. Text to synthesize (str)
132
+ language, # 2. Language (str)
133
+ handle_file(local_img), # 3. Reference Audio (file)
134
+ ref_text if ref_text else "", # 4. Reference Text (str)
135
+ "", # 5. Instruct (در حالت کلون ساده خالی رها می‌شود)
136
+ 32, # 6. Steps (تعداد مراحل تولید)
137
+ 2.0, # 7. Guidance scale (مقیاس هدایت)
138
+ True, # 8. Denoise (کاهش نویز پیش‌فرض)
139
+ 1.0, # 9. Speed (سرعت طبیعی)
140
+ 0, # 10. Duration (تنظیم خودکار زمان)
141
+ True, # 11. Preprocess prompt (پیش‌پردازش)
142
+ True, # 12. Postprocess output (پس‌پردازش خروجی)
143
+ **endpoint_arg
144
+ )
145
+
146
+ # استخراج مسیر فایل صوتی تولید شده نهایی
147
+ audio_path = None
148
+ if isinstance(result, (list, tuple)):
149
+ audio_path = result[0]
150
+ elif isinstance(result, dict):
151
+ audio_path = result.get('name') or result.get('path') or result.get('url')
152
+ else:
153
+ audio_path = result
154
+
155
+ if not audio_path or not os.path.exists(str(audio_path)):
156
+ raise Exception("Generated audio file not found or invalid.")
157
+
158
+ # آپلود مجدد فایل صوتی به فضای وب‌هوک هاست فلاسک با پسوند wav
159
+ print('6. Uploading output back to your Space...')
160
+ with open(audio_path, 'rb') as f:
161
+ res_upload = requests.post(
162
+ f'{space_url}/api/webhook/upload',
163
+ data={'run_id': run_id, 'github_run_id': github_run_id, 'ext': 'wav'},
164
+ files={'file': f}
165
+ )
166
+
167
+ if res_upload.status_code == 200:
168
+ print('7. SUCCESS! Process complete.')
169
+ else:
170
+ raise Exception(f"Webhook upload failed. Status code: {res_upload.status_code}")
171
+
172
+ except Exception as e:
173
+ err_str = str(e)
174
+ print(f"CRITICAL ERROR during generation: {err_str}")
175
+ report_failure(err_str)
176
+ sys.exit(1)