Ezmary commited on
Commit
2b94fac
·
verified ·
1 Parent(s): be3e773

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -21
app.py CHANGED
@@ -16,13 +16,19 @@ DATASET_FILENAME = "video_usage_data.json"
16
  USAGE_LIMIT = 5
17
  HF_TOKEN = os.environ.get("HF_TOKEN")
18
  TEMP_DIR = "/app/tmp"
 
 
19
  ROUTER_WORKER_URL = os.environ.get("ROUTER_WORKER_URL")
20
 
21
  # --- تنظیمات لاگینگ ---
 
22
  for handler in logging.root.handlers[:]:
23
  logging.root.removeHandler(handler)
24
  logging.basicConfig(level=logging.INFO, format='%(message)s')
 
 
25
  logging.getLogger('huggingface_hub').setLevel(logging.ERROR)
 
26
  logging.getLogger('werkzeug').setLevel(logging.ERROR)
27
  logging.getLogger("urllib3").setLevel(logging.WARNING)
28
 
@@ -39,11 +45,13 @@ api = None
39
  if HF_TOKEN:
40
  api = HfApi(token=HF_TOKEN)
41
 
 
42
  if not ROUTER_WORKER_URL:
43
  logging.error("❌ CRITICAL ERROR: The ROUTER_WORKER_URL environment variable is not set!")
44
  else:
45
  logging.info(f"✅ Main app is configured to use the router at: {ROUTER_WORKER_URL}")
46
 
 
47
  def load_initial_data():
48
  global usage_data_cache
49
  with cache_lock:
@@ -51,13 +59,18 @@ def load_initial_data():
51
  try:
52
  with tempfile.TemporaryDirectory(dir=TEMP_DIR) as tmp_download_dir:
53
  local_path = hf_hub_download(
54
- repo_id=DATASET_REPO, filename=DATASET_FILENAME, repo_type="dataset",
55
- token=HF_TOKEN, force_download=True, cache_dir=tmp_download_dir
 
 
 
 
56
  )
57
  with open(local_path, 'r', encoding='utf-8') as f:
58
  content = f.read()
59
  usage_data_cache = json.loads(content) if content else []
60
  except Exception:
 
61
  usage_data_cache = []
62
 
63
  def persist_data_to_hub():
@@ -72,10 +85,14 @@ def persist_data_to_hub():
72
  temp_filepath = temp_f.name
73
  json.dump(data_to_write, temp_f, ensure_ascii=False, indent=2)
74
  api.upload_file(
75
- path_or_fileobj=temp_filepath, path_in_repo=DATASET_FILENAME,
76
- repo_id=DATASET_REPO, repo_type="dataset", commit_message="Update animation usage data"
 
 
 
77
  )
78
  except Exception:
 
79
  data_changed.set()
80
  finally:
81
  if temp_filepath and os.path.exists(temp_filepath):
@@ -101,7 +118,7 @@ def enhance_animation_prompt():
101
  if not image_file:
102
  return jsonify({"error": "فایل تصویر الزامی است."}), 400
103
 
104
- # 🧠🧠🧠 شاه پرامپت کامل و نهایی برای ساخت ویدیو 🧠🧠🧠
105
  gemini_master_prompt = f"""
106
  You are an expert AI Animation Planner. Your absolute highest priority is to faithfully and creatively execute the user's specific request. You are not just an artist; you are a technical problem solver.
107
 
@@ -166,41 +183,42 @@ Based on your decision, generate the following two keys in English.
166
  }}
167
  """
168
 
 
169
  image_file.seek(0)
170
  image_bytes = image_file.read()
171
 
172
  endpoint = f"{ROUTER_WORKER_URL}/v1/request"
173
- logging.info(f"Relaying video prompt request to router at {endpoint}")
174
 
175
  try:
176
  files = {'image': (image_file.filename, image_bytes, image_file.mimetype)}
177
- data = {'prompt': gemini_master_prompt}
178
 
 
179
  response = requests.post(endpoint, files=files, data=data, timeout=100)
180
- response.raise_for_status()
181
-
182
- router_response = response.json()
183
 
184
- if router_response.get("type") == "json" and "content" in router_response:
185
- logging.info("✅ Successfully received and unwrapped JSON content from router.")
186
- return jsonify(router_response["content"])
187
- else:
188
- logging.error(f"❌ Unexpected response format from router: {router_response}")
189
- return jsonify({"error": "پاسخ دریافت شده از سرور پردازش، معتبر نبود."}), 502
190
 
191
  except requests.exceptions.Timeout:
192
- logging.error(f"❌ Timeout error from router.")
193
- return jsonify({"error": "سرور پردازش با تاخیر مواجه است. لطفاً دوباره تلاش کنید."}), 504
194
  except requests.exceptions.RequestException as e:
195
- error_detail = "سرویس هوش مصنوعی با مشکل مواجه شده است."
196
  if e.response is not None:
197
  try:
 
198
  router_error = e.response.json().get("detail", e.response.text)
199
  error_detail = f"خطا از سرور پردازش: {router_error}"
200
- except: pass
201
- logging.error(f" RequestException from router: {error_detail}")
 
202
  return jsonify({"error": error_detail}), 503
203
 
 
204
  def get_user_identifier(data):
205
  fingerprint = data.get('fingerprint')
206
  if fingerprint: return str(fingerprint)
@@ -260,10 +278,12 @@ def use_credit():
260
 
261
  return jsonify({"status": "success", "credits_remaining": credits_remaining})
262
 
 
263
  @app.route('/health', methods=['GET'])
264
  def health_check():
265
  return "OK", 200
266
 
 
267
  if __name__ != '__main__':
268
  try:
269
  load_initial_data()
 
16
  USAGE_LIMIT = 5
17
  HF_TOKEN = os.environ.get("HF_TOKEN")
18
  TEMP_DIR = "/app/tmp"
19
+
20
+ # ✅✅✅ آدرس ورودی اصلی (مسیریاب) که از متغیرهای راز خوانده می‌شود
21
  ROUTER_WORKER_URL = os.environ.get("ROUTER_WORKER_URL")
22
 
23
  # --- تنظیمات لاگینگ ---
24
+ # فقط پیام لاگ نمایش داده می‌شود
25
  for handler in logging.root.handlers[:]:
26
  logging.root.removeHandler(handler)
27
  logging.basicConfig(level=logging.INFO, format='%(message)s')
28
+
29
+ # ساکت کردن لاگ‌های کتابخانه‌های پرحرف
30
  logging.getLogger('huggingface_hub').setLevel(logging.ERROR)
31
+ logging.getLogger('gunicorn.error').setLevel(logging.WARNING)
32
  logging.getLogger('werkzeug').setLevel(logging.ERROR)
33
  logging.getLogger("urllib3").setLevel(logging.WARNING)
34
 
 
45
  if HF_TOKEN:
46
  api = HfApi(token=HF_TOKEN)
47
 
48
+ # بررسی وجود آدرس مسیریاب در هنگام شروع به کار
49
  if not ROUTER_WORKER_URL:
50
  logging.error("❌ CRITICAL ERROR: The ROUTER_WORKER_URL environment variable is not set!")
51
  else:
52
  logging.info(f"✅ Main app is configured to use the router at: {ROUTER_WORKER_URL}")
53
 
54
+ # --- توابع مدیریت داده (بدون تغییر) ---
55
  def load_initial_data():
56
  global usage_data_cache
57
  with cache_lock:
 
59
  try:
60
  with tempfile.TemporaryDirectory(dir=TEMP_DIR) as tmp_download_dir:
61
  local_path = hf_hub_download(
62
+ repo_id=DATASET_REPO,
63
+ filename=DATASET_FILENAME,
64
+ repo_type="dataset",
65
+ token=HF_TOKEN,
66
+ force_download=True,
67
+ cache_dir=tmp_download_dir
68
  )
69
  with open(local_path, 'r', encoding='utf-8') as f:
70
  content = f.read()
71
  usage_data_cache = json.loads(content) if content else []
72
  except Exception:
73
+ # در صورت بروز خطا، با لیست خالی شروع می‌کنیم
74
  usage_data_cache = []
75
 
76
  def persist_data_to_hub():
 
85
  temp_filepath = temp_f.name
86
  json.dump(data_to_write, temp_f, ensure_ascii=False, indent=2)
87
  api.upload_file(
88
+ path_or_fileobj=temp_filepath,
89
+ path_in_repo=DATASET_FILENAME,
90
+ repo_id=DATASET_REPO,
91
+ repo_type="dataset",
92
+ commit_message="Update animation usage data"
93
  )
94
  except Exception:
95
+ # اگر آپلود ناموفق بود، دوباره پرچم را تنظیم می‌کنیم تا در تلاش بعدی ارسال شود
96
  data_changed.set()
97
  finally:
98
  if temp_filepath and os.path.exists(temp_filepath):
 
118
  if not image_file:
119
  return jsonify({"error": "فایل تصویر الزامی است."}), 400
120
 
121
+ # 🧠🧠🧠 شاه پرامپت کامل در اینجا ساخته می‌شود 🧠🧠🧠
122
  gemini_master_prompt = f"""
123
  You are an expert AI Animation Planner. Your absolute highest priority is to faithfully and creatively execute the user's specific request. You are not just an artist; you are a technical problem solver.
124
 
 
183
  }}
184
  """
185
 
186
+ # خواندن فایل تصویر در حافظه
187
  image_file.seek(0)
188
  image_bytes = image_file.read()
189
 
190
  endpoint = f"{ROUTER_WORKER_URL}/v1/request"
191
+ logging.info(f"Relaying request to router at {endpoint}")
192
 
193
  try:
194
  files = {'image': (image_file.filename, image_bytes, image_file.mimetype)}
195
+ data = {'prompt': gemini_master_prompt} # شاه پرامپت کامل به مسیریاب ارسال می‌شود
196
 
197
+ # ارسال درخواست با تایم‌اوت طولانی‌تر برای اطمینان
198
  response = requests.post(endpoint, files=files, data=data, timeout=100)
 
 
 
199
 
200
+ # اگر پاسخ خطا بود (مثلاً 5xx)، استثنا ایجاد می‌کند
201
+ response.raise_for_status()
202
+
203
+ logging.info("✅ Successfully received response from router.")
204
+ return jsonify(response.json())
 
205
 
206
  except requests.exceptions.Timeout:
207
+ logging.error("❌ Timeout error: The request to the router timed out.")
208
+ return jsonify({"error": "سرور پردازش با تاخیر مواجه است. لطفاً چند لحظه دیگر دوباره تلاش کنید."}), 504
209
  except requests.exceptions.RequestException as e:
210
+ error_detail = "سرویس هوش مصنوعی با مشکل مواجه شده است. لطفاً بعداً تلاش کنید."
211
  if e.response is not None:
212
  try:
213
+ # تلاش برای استخراج پیام خطای اصلی از مسیریاب
214
  router_error = e.response.json().get("detail", e.response.text)
215
  error_detail = f"خطا از سرور پردازش: {router_error}"
216
+ except json.JSONDecodeError:
217
+ error_detail = f"سرور پردازش با خطای {e.response.status_code} پاسخ داد."
218
+ logging.error(f"❌ RequestException when contacting router: {error_detail}")
219
  return jsonify({"error": error_detail}), 503
220
 
221
+ # --- روت‌های مدیریت اعتبار (بدون تغییر) ---
222
  def get_user_identifier(data):
223
  fingerprint = data.get('fingerprint')
224
  if fingerprint: return str(fingerprint)
 
278
 
279
  return jsonify({"status": "success", "credits_remaining": credits_remaining})
280
 
281
+ # --- روت بررسی سلامت (Health Check) ---
282
  @app.route('/health', methods=['GET'])
283
  def health_check():
284
  return "OK", 200
285
 
286
+ # --- راه‌اندازی برنامه (بدون تغییر) ---
287
  if __name__ != '__main__':
288
  try:
289
  load_initial_data()