Spaces:
Running
Running
Download hf_deploy/api.py from kodnuke/youtube-bot: direct link, hf CLI and curl.
- Browser
- Download file 8.71 kB
-
https://huggingface.co/spaces/kodnuke/youtube-bot/resolve/main/hf_deploy/api.py
- Command line
-
hf download hf://spaces/kodnuke/youtube-bot/hf_deploy/api.py
-
curl -L -o api.py https://huggingface.co/spaces/kodnuke/youtube-bot/resolve/main/hf_deploy/api.py
8.71 kB
| """ | |
| MoneyPrinterTurbo REST API istemcisi. | |
| Bot, aynı konteynerde çalışan API'yi HTTP üzerinden çağırır. Böylece | |
| botun mantığı ile üretim mantığı birbirinden bağımsız kalır ve API | |
| çökerse bot ayakta kalıp hatayı bildirebilir. | |
| """ | |
| import os | |
| import time | |
| from typing import Any, Optional | |
| import requests | |
| from loguru import logger | |
| from hf_deploy import config as cfg | |
| class APIError(Exception): | |
| """API çağrısı başarısız oldu. Kullanıcıya gösterilebilir mesaj taşır.""" | |
| def _headers() -> dict: | |
| headers = {"Content-Type": "application/json"} | |
| if cfg.MPT_API_KEY: | |
| headers["x-api-key"] = cfg.MPT_API_KEY | |
| return headers | |
| def _url(path: str) -> str: | |
| return f"{cfg.MPT_API_BASE.rstrip('/')}{path}" | |
| def wait_for_api(timeout_seconds: int = 180) -> bool: | |
| """Uygulamanın hazır olmasını bekler. Başlangıçta kullanılır.""" | |
| deadline = time.time() + timeout_seconds | |
| while time.time() < deadline: | |
| if ping(): | |
| logger.info("MoneyPrinterTurbo API hazır") | |
| return True | |
| time.sleep(3) | |
| return False | |
| def ping() -> bool: | |
| """Sağlık kontrolü. MoneyPrinterTurbo /ping'i kök yolda sunar.""" | |
| try: | |
| return requests.get( | |
| _url("/ping"), headers=_headers(), timeout=5 | |
| ).status_code == 200 | |
| except requests.RequestException: | |
| return False | |
| def _unwrap(payload: Any) -> Any: | |
| """ | |
| API yanıtı ``{"status": <http_kodu>, "data": ..., "message": ...}`` biçiminde. | |
| ``status`` HTTP kodunu yansıtır (200 başarı, 4xx/5xx hata); hata mesajı | |
| çoğu zaman ``message`` alanındadır. | |
| """ | |
| if isinstance(payload, dict) and "status" in payload: | |
| status = payload["status"] | |
| if isinstance(status, int) and status >= 400: | |
| raise APIError(payload.get("message") or f"API hatası ({status})") | |
| return payload.get("data") | |
| return payload | |
| def create_video( | |
| subject: str, | |
| language: str = "", | |
| paragraph_number: Optional[int] = None, | |
| aspect: str = "9:16", | |
| voice_name: Optional[str] = None, | |
| video_source: Optional[str] = None, | |
| script_prompt: str = "", | |
| count: int = 1, | |
| subtitle_enabled: bool = True, | |
| ) -> str: | |
| """Video üretimi başlatır, task_id döndürür.""" | |
| payload = { | |
| "video_subject": subject, | |
| "video_aspect": aspect, | |
| "video_concat_mode": "random", | |
| "video_count": count, | |
| "subtitle_enabled": subtitle_enabled, | |
| "video_language": language or cfg.DEFAULT_LANGUAGE, | |
| "paragraph_number": paragraph_number or cfg.DEFAULT_PARAGRAPH_NUMBER, | |
| "video_source": video_source or cfg.DEFAULT_VIDEO_SOURCE, | |
| "video_script_prompt": script_prompt, | |
| "bgm_type": cfg.DEFAULT_BGM_TYPE, | |
| "bgm_volume": cfg.DEFAULT_BGM_VOLUME, | |
| "voice_name": voice_name or cfg.DEFAULT_VOICE_NAME, | |
| # 2 vCPU'da fazla iş parçacığı bellek ve CPU çakışması yaratır. | |
| "n_threads": 2, | |
| } | |
| try: | |
| response = requests.post( | |
| _url("/api/v1/videos"), json=payload, headers=_headers(), timeout=60 | |
| ) | |
| except requests.RequestException as exc: | |
| raise APIError(f"API'ye ulaşılamıyor: {exc}") from exc | |
| if response.status_code != 200: | |
| raise APIError(_error_from(response)) | |
| data = _unwrap(response.json()) | |
| task_id = data.get("task_id") if isinstance(data, dict) else None | |
| if not task_id: | |
| raise APIError("API task_id döndürmedi") | |
| return task_id | |
| def _error_from(response: requests.Response) -> str: | |
| try: | |
| body = response.json() | |
| if isinstance(body, dict): | |
| return body.get("message") or f"HTTP {response.status_code}" | |
| except ValueError: | |
| pass | |
| return f"HTTP {response.status_code}: {response.text[:200]}" | |
| def get_task(task_id: str) -> Optional[dict]: | |
| """Görev durumunu döndürür. Bulunamazsa None.""" | |
| try: | |
| response = requests.get( | |
| _url(f"/api/v1/tasks/{task_id}"), headers=_headers(), timeout=20 | |
| ) | |
| except requests.RequestException as exc: | |
| raise APIError(f"API'ye ulaşılamıyor: {exc}") from exc | |
| if response.status_code == 404: | |
| return None | |
| if response.status_code != 200: | |
| raise APIError(_error_from(response)) | |
| return _unwrap(response.json()) | |
| def list_tasks(page: int = 1, page_size: int = 10) -> list[dict]: | |
| try: | |
| response = requests.get( | |
| _url(f"/api/v1/tasks?page={page}&page_size={page_size}"), | |
| headers=_headers(), | |
| timeout=20, | |
| ) | |
| except requests.RequestException as exc: | |
| raise APIError(f"API'ye ulaşılamıyor: {exc}") from exc | |
| if response.status_code != 200: | |
| raise APIError(_error_from(response)) | |
| data = _unwrap(response.json()) | |
| return data.get("tasks", []) if isinstance(data, dict) else [] | |
| def delete_task(task_id: str) -> bool: | |
| try: | |
| response = requests.delete( | |
| _url(f"/api/v1/tasks/{task_id}"), headers=_headers(), timeout=30 | |
| ) | |
| except requests.RequestException as exc: | |
| raise APIError(f"API'ye ulaşılamıyor: {exc}") from exc | |
| return response.status_code == 200 | |
| def describe_task(task: dict) -> str: | |
| """Görev durumunu okunabilir metne çevirir.""" | |
| from app.models import const # noqa: PLC0415 (geç import: ağır bağımlılık) | |
| state = task.get("state") | |
| progress = task.get("progress", 0) | |
| if state == const.TASK_STATE_COMPLETE: | |
| return "✅ Tamamlandı" | |
| if state == const.TASK_STATE_FAILED: | |
| return f"❌ Başarısız: {task.get('fail_reason') or task.get('error') or 'bilinmeyen hata'}" | |
| return f"⏳ İşleniyor (%{progress})" | |
| def resolve_video_path(task: dict) -> Optional[str]: | |
| """ | |
| Görevin teslim edilecek video dosyasının **URL**'ini döndürür. | |
| Video üretimi Hugging Face'te, bot bu bilgisayarda çalışır. Bu yüzden | |
| dosya yerel diskte değil, uzaktadır; çağıran taraf indirmekle yükümlüdür | |
| (:func:`download_video`). | |
| Sıra önemli: ``videos`` (son render) sesli dosyayı gösterir, | |
| ``combined_videos`` ise ham klip birleşimidir ve **sessizdir** — ses | |
| ancak son render aşamasında eklenir. Önce ``videos`` denenir. | |
| """ | |
| videos = task.get("videos") or task.get("combined_videos") or [] | |
| if not videos: | |
| return None | |
| for candidate in videos: | |
| if isinstance(candidate, str) and candidate: | |
| if candidate.startswith(("http://", "https://")): | |
| return candidate | |
| # Göreli yol ("/tasks/<id>/dosya.mp4") mutlak URL'e çevrilir. | |
| return _url(candidate) | |
| return None | |
| def download_video(task: dict, dest_dir: Optional[str] = None) -> Optional[str]: | |
| """ | |
| Görevin videosunu API'den indirir ve yerel yolunu döndürür. | |
| Dosya zaten indirilmişse tekrar indirilmez. İndirilen dosya | |
| ``dest_dir`` (varsayılan: geçici dizin) altına ``<task_id>.mp4`` | |
| adıyla yazılır. | |
| """ | |
| url = resolve_video_path(task) | |
| if not url: | |
| return None | |
| task_id = task.get("task_id", "video") | |
| name = url.rstrip("/").split("/")[-1] or "video.mp4" | |
| if not name.lower().endswith(".mp4"): | |
| name = f"{name}.mp4" | |
| target_dir = dest_dir or cfg.DOWNLOAD_DIR | |
| os.makedirs(target_dir, exist_ok=True) | |
| path = os.path.join(target_dir, f"{task_id}-{name}") | |
| if os.path.isfile(path) and os.path.getsize(path) > 0: | |
| logger.info(f"Video zaten indirilmiş, atlaniyor: {path}") | |
| return path | |
| logger.info(f"Video indiriliyor: {url}") | |
| try: | |
| with requests.get(url, headers=_headers(), stream=True, timeout=600) as response: | |
| response.raise_for_status() | |
| # Kısmi indirme (yarım dosya) bırakmamak için önce .part yaz. | |
| partial = f"{path}.part" | |
| written = 0 | |
| with open(partial, "wb") as handle: | |
| for chunk in response.iter_content(chunk_size=1024 * 1024): | |
| if not chunk: | |
| continue | |
| handle.write(chunk) | |
| written += len(chunk) | |
| except requests.RequestException as exc: | |
| logger.error(f"Video indirilemedi: {exc}") | |
| return None | |
| except OSError as exc: | |
| logger.error(f"Video yazilamadi: {exc}") | |
| return None | |
| if written == 0: | |
| logger.error("Video indirildi ama dosya bos") | |
| try: | |
| os.remove(partial) | |
| except OSError: | |
| pass | |
| return None | |
| os.replace(partial, path) | |
| size_mb = written / (1024 * 1024) | |
| logger.info(f"Video indirildi: {path} ({size_mb:.1f} MB)") | |
| return path |