Spaces:
Running

File size: 4,635 Bytes
14dabf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#URLをplaylistに書き込むモジュール
import requests
from bs4 import BeautifulSoup
import yt_dlp
from urllib.parse import urlparse, parse_qs
import re


def URLwrite(input,guild):
    print("input:",input)
    #if url_or_word(input) != "None":
    if input.startswith("http"):
        #url = url_or_word(input)
        url = input
        if is_youtube_url(url):#youtubeのURL
            if has_ampersand_in_url(url): #&が中に存在する
                id = extract_playlist_id(url)#playlistのIDを取得
                url = "https://www.youtube.com/playlist?list="+id#playlistのURLを取得
        if input.startswith("https://www.nicobox.jp"):#ボカコレか判定
          url = nicobox_to_nicovideo("https://www.nicobox.jp/share?mylist=59279076")#ニコニコに変換
        if input.startswith("https://www.nicovideo.jp"):
            url  = input.split('?')[0]
        print("URL:",url)
        type = URLwrite_to_txt(url,guild)#txtに書き込み
        return url,type#終了

    else:#wordで検索
       url =search_youtube(input)
       type = URLwrite_to_txt(url,guild)
       return url,type

def url_or_word(input): #URLか識別する
    # findall() 正規表現に一致する文字列を検索する
    url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', input)
    if len(url) != 0:
        return url[0]
    else:
        return "None"
    
def is_youtube_url(url):#youtubeのURLか判別する
    pattern = r'(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/)?([a-zA-Z0-9_-]+)'
    match = re.match(pattern, url)
    return match is not None

def has_ampersand_in_url(url):#youtubeの特殊playlistURLか判別する
    if '&' in url:
        return True
    else:
        return False

def extract_playlist_id(url):#playlistIDを取得する
    # URLを解析してクエリパラメーターを取得
    query_params = parse_qs(urlparse(url).query)
    # "list"パラメーターの値を抽出
    playlist_id = query_params.get('list', [''])[0]
    return playlist_id

def URLwrite_to_txt(input,id):#書き込みdef
    ydl_opts = {
        'dump_single_json': True,
        'extract_flat': True,
        'skip_download': True,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        try:
            result = ydl.extract_info(input, download=False)
            if 'entries' in result:
                # プレイリストの場合
                entries = result['entries']
                urls = [entry['url'] for entry in entries if 'url' in entry]

                for i in range(len(urls)):#書き込み
                    with open(id+".txt", 'a') as f:
                        print(urls[i], file=f)

                return "Playlist"
            else:
                # 個別の動画の場合
                url = result['webpage_url']
                with open(id+".txt", 'a') as f:#書き込み
                    print(url, file=f) 

                return "Video"
        except yt_dlp.DownloadError as e:#エラー
            return "Error"  
        
def nicobox_to_nicovideo(url):#ボカコレURL⇒ニコニコURL
  parsed_url = urlparse(url)
  query_params = parse_qs(parsed_url.query)
  id = query_params.get('mylist', [''])[0]#idを取得
 
  url = 'https://www.nicovideo.jp/mylist/'+id

  response = requests.get(url)

  if response.status_code == 200:
    # レスポンスの内容をBeautifulSoupで解析
    soup = BeautifulSoup(response.text, 'html.parser')
    meta_tag = soup.find('meta', {'property': 'og:url'})

    if meta_tag:
        content = meta_tag.get('content')
    return content         


def search_youtube(query):
    ydl_opts = {
        'quiet': True,
        'format': 'best',
        'noplaylist': True,
        'extract_flat': True,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            search_results = ydl.extract_info(f"ytsearch:{query}", download=False)
            first_video_url = search_results['entries'][0]['url']
            return first_video_url   
    
def get_url(input):
    with yt_dlp.YoutubeDL({'dump_single_json': True,'extract_flat': True,'skip_download': True,'cachedir': False }) as ydl:
        try:
            result = ydl.extract_info(input, download=False)
            title = result['title']
            print(title)
            return str(title)
        except yt_dlp.DownloadError as e:#エラー
            return "Error 再生不能"  
        
from concurrent.futures import ThreadPoolExecutor

def get_multiple_urls(inputs):
    with ThreadPoolExecutor() as executor:
        titles = list(executor.map(get_url, inputs))
    return titles