Spaces:
Sleeping

File size: 2,127 Bytes
4f3fd1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
youtube_tools.py
YouTube ダウンロード処理(Colab / ngrok 経由)
  - youtube : URL リストを Colab サーバーに送信してファイルを取得する
"""
import os
import zipfile
import requests
from typing import List

from tools.base_tool import tasks, get_colab_url, is_ngrok_error


# ---------- YouTube → MP3 / MP4 ----------

def download_youtube(
    task_id: str,
    url_text: str,
    session_path: str,
    output_path: str,
    output_format: str = "mp3"
):
    """
    Colab サーバーに YouTube URL リストを送信し、
    返ってきた ZIP を output_path に展開する。
    """
    current_colab_url = get_colab_url()
    if not current_colab_url:
        raise Exception("サーバーが停止しています。管理者にお問い合わせください。")

    urls = [u.strip() for u in url_text.split("\n") if u.strip()]
    tasks[task_id]["last_log"] = f"Colabへリクエスト送信中... ({output_format})"

    try:
        response = requests.post(
            f"{current_colab_url.rstrip('/')}/batch-download",
            json={"urls": urls, "format": output_format},
            timeout=900
        )

        if response.status_code != 200:
            error_body = response.text
            if is_ngrok_error(error_body):
                raise Exception("サーバーが停止しています。管理者にお問い合わせください。")
            raise Exception(f"Colabエラー: {error_body}")

        colab_zip = os.path.join(session_path, "colab_result.zip")
        with open(colab_zip, "wb") as f:
            f.write(response.content)

        with zipfile.ZipFile(colab_zip, "r") as z:
            z.extractall(output_path)

        tasks[task_id]["last_log"] = "取得完了"
        tasks[task_id]["progress"] = 90

    except Exception as e:
        error_msg = str(e)
        if is_ngrok_error(error_msg) or "サーバーが停止しています" in error_msg:
            raise Exception("サーバーが停止しています。管理者にお問い合わせください。")
        raise Exception(f"Colab接続失敗: {error_msg}")