Spaces:
Sleeping
Sleeping
Update fetcher.py
Browse files- fetcher.py +156 -181
fetcher.py
CHANGED
|
@@ -1,231 +1,206 @@
|
|
| 1 |
"""
|
| 2 |
-
fetcher.py β
|
| 3 |
-
Completely decoupled from the UI layer.
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
import os
|
| 7 |
import re
|
| 8 |
-
import
|
| 9 |
-
from typing import Optional, Tuple, List, Dict, Any
|
| 10 |
-
|
| 11 |
import pandas as pd
|
| 12 |
-
from googleapiclient.discovery import build
|
| 13 |
-
from googleapiclient.errors import HttpError
|
| 14 |
-
from youtube_transcript_api import (
|
| 15 |
-
YouTubeTranscriptApi,
|
| 16 |
-
NoTranscriptFound,
|
| 17 |
-
TranscriptsDisabled,
|
| 18 |
-
VideoUnavailable,
|
| 19 |
-
)
|
| 20 |
|
| 21 |
|
| 22 |
-
# ββ
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
def extract_video_id(url_or_id: str) ->
|
| 25 |
-
"""
|
| 26 |
-
url_or_id = url_or_id.strip()
|
| 27 |
patterns = [
|
| 28 |
-
r"(?:v=|youtu\.be/|embed/|shorts/
|
| 29 |
-
r"^([
|
| 30 |
]
|
| 31 |
-
for
|
| 32 |
-
m = re.search(
|
| 33 |
if m:
|
| 34 |
return m.group(1)
|
| 35 |
return None
|
| 36 |
|
| 37 |
|
| 38 |
-
# ββ
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
-
# ββ
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
def fetch_video_metadata(video_id: str, api_key: str) ->
|
| 47 |
-
"""
|
| 48 |
-
Returns (metadata_dict, error_string).
|
| 49 |
-
metadata_dict keys: title, channel_title, description, tags, duration,
|
| 50 |
-
published_at, view_count, like_count, comment_count,
|
| 51 |
-
thumbnail_url, video_id
|
| 52 |
-
"""
|
| 53 |
try:
|
| 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 |
-
"comment_count": int(stats.get("commentCount", 0)),
|
| 83 |
"thumbnail_url": (
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
.get("url", "")
|
| 87 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
}
|
| 89 |
-
return
|
| 90 |
|
| 91 |
-
except
|
| 92 |
-
return None,
|
| 93 |
-
except Exception as
|
| 94 |
-
return None,
|
| 95 |
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
parts = []
|
| 104 |
-
if h: parts.append(f"{h}h")
|
| 105 |
-
if mn: parts.append(f"{mn}m")
|
| 106 |
-
if s: parts.append(f"{s}s")
|
| 107 |
-
return " ".join(parts) or "0s"
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
# ββ Transcript βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 111 |
-
|
| 112 |
-
def fetch_transcript(video_id: str) -> Tuple[str, str]:
|
| 113 |
-
"""
|
| 114 |
-
Returns (transcript_text, status_message).
|
| 115 |
-
Tries English first, then any available language.
|
| 116 |
-
"""
|
| 117 |
try:
|
| 118 |
-
|
|
|
|
| 119 |
text = " ".join(s["text"] for s in segments)
|
| 120 |
-
return text, f"β
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
text = " ".join(s["text"] for s in segments)
|
| 130 |
-
return text, f"β
Transcript fetched (lang: {t.language_code}, {len(text.split())} words)"
|
| 131 |
-
except Exception:
|
| 132 |
-
continue
|
| 133 |
-
return "", "β οΈ No usable transcript found for any language."
|
| 134 |
-
except Exception as e:
|
| 135 |
-
return "", f"β οΈ Transcript listing failed: {e}"
|
| 136 |
-
|
| 137 |
-
except TranscriptsDisabled:
|
| 138 |
-
return "", "β οΈ Transcripts are disabled for this video."
|
| 139 |
-
except VideoUnavailable:
|
| 140 |
-
return "", "β Video is unavailable."
|
| 141 |
-
except Exception as e:
|
| 142 |
-
return "", f"β οΈ Transcript error: {e}"
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
# ββ Comments βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
|
| 147 |
def fetch_comments(
|
| 148 |
video_id: str,
|
| 149 |
api_key: str,
|
| 150 |
-
max_comments: int =
|
| 151 |
-
) ->
|
| 152 |
-
"""
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
"""
|
| 157 |
try:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
)
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
"
|
| 180 |
-
"
|
| 181 |
-
"
|
|
|
|
| 182 |
})
|
| 183 |
|
| 184 |
-
|
| 185 |
-
if not
|
| 186 |
break
|
| 187 |
|
| 188 |
-
if not
|
| 189 |
-
return pd.DataFrame(), "β οΈ No comments
|
| 190 |
|
| 191 |
-
df = pd.DataFrame(
|
| 192 |
-
return df, f"β
|
| 193 |
|
| 194 |
-
except
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
return pd.DataFrame(), f"β API error {e.resp.status}: {reason}"
|
| 199 |
-
except Exception as e:
|
| 200 |
-
return pd.DataFrame(), f"β Comments error: {e}"
|
| 201 |
|
| 202 |
|
| 203 |
-
# ββ
|
|
|
|
|
|
|
| 204 |
|
| 205 |
-
def search_videos_by_title(
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
try:
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
results = []
|
| 220 |
-
for item in
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
results.append({
|
| 222 |
-
"video_id":
|
| 223 |
-
"title":
|
| 224 |
-
"channel_title":
|
| 225 |
-
"
|
| 226 |
-
"
|
| 227 |
})
|
| 228 |
return results
|
| 229 |
-
|
| 230 |
except Exception:
|
| 231 |
return []
|
|
|
|
| 1 |
"""
|
| 2 |
+
fetcher.py β YouTube Data API v3 helpers
|
|
|
|
| 3 |
"""
|
| 4 |
|
|
|
|
| 5 |
import re
|
| 6 |
+
import requests
|
|
|
|
|
|
|
| 7 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
# Video ID extraction
|
| 12 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
|
| 14 |
+
def extract_video_id(url_or_id: str) -> str | None:
|
| 15 |
+
"""Return an 11-char YouTube video ID, or None if not found."""
|
|
|
|
| 16 |
patterns = [
|
| 17 |
+
r"(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/embed/|youtube\.com/shorts/)([a-zA-Z0-9_-]{11})",
|
| 18 |
+
r"^([a-zA-Z0-9_-]{11})$",
|
| 19 |
]
|
| 20 |
+
for pattern in patterns:
|
| 21 |
+
m = re.search(pattern, url_or_id)
|
| 22 |
if m:
|
| 23 |
return m.group(1)
|
| 24 |
return None
|
| 25 |
|
| 26 |
|
| 27 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
# Duration parser
|
| 29 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 30 |
|
| 31 |
+
def _parse_duration(iso: str) -> str:
|
| 32 |
+
m = re.match(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", iso or "PT0S")
|
| 33 |
+
if not m:
|
| 34 |
+
return "0:00"
|
| 35 |
+
h, mn, s = (int(x or 0) for x in m.groups())
|
| 36 |
+
return f"{h}:{mn:02d}:{s:02d}" if h else f"{mn}:{s:02d}"
|
| 37 |
|
| 38 |
|
| 39 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
# Metadata
|
| 41 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
|
| 43 |
+
def fetch_video_metadata(video_id: str, api_key: str) -> tuple[dict | None, str | None]:
|
| 44 |
+
"""Return (meta_dict, error_string). One will be None."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
try:
|
| 46 |
+
resp = requests.get(
|
| 47 |
+
"https://www.googleapis.com/youtube/v3/videos",
|
| 48 |
+
params={
|
| 49 |
+
"id": video_id,
|
| 50 |
+
"key": api_key,
|
| 51 |
+
"part": "snippet,statistics,contentDetails",
|
| 52 |
+
},
|
| 53 |
+
timeout=15,
|
| 54 |
+
)
|
| 55 |
+
data = resp.json()
|
| 56 |
+
if "error" in data:
|
| 57 |
+
return None, data["error"].get("message", "YouTube API error")
|
| 58 |
+
|
| 59 |
+
items = data.get("items", [])
|
| 60 |
+
if not items:
|
| 61 |
+
return None, "Video not found β check the ID or URL."
|
| 62 |
+
|
| 63 |
+
item = items[0]
|
| 64 |
+
sn = item.get("snippet", {})
|
| 65 |
+
st = item.get("statistics", {})
|
| 66 |
+
cd = item.get("contentDetails", {})
|
| 67 |
+
|
| 68 |
+
meta = {
|
| 69 |
+
"title": sn.get("title", "Unknown"),
|
| 70 |
+
"description": sn.get("description", ""),
|
| 71 |
+
"channel_title": sn.get("channelTitle", "Unknown"),
|
| 72 |
+
"published_at": sn.get("publishedAt", "")[:10],
|
| 73 |
+
"tags": sn.get("tags", []),
|
|
|
|
| 74 |
"thumbnail_url": (
|
| 75 |
+
sn.get("thumbnails", {}).get("high", {}).get("url", "")
|
| 76 |
+
or sn.get("thumbnails", {}).get("medium", {}).get("url", "")
|
|
|
|
| 77 |
),
|
| 78 |
+
"view_count": int(st.get("viewCount", 0)),
|
| 79 |
+
"like_count": int(st.get("likeCount", 0)),
|
| 80 |
+
"comment_count": int(st.get("commentCount", 0)),
|
| 81 |
+
"duration": _parse_duration(cd.get("duration", "PT0S")),
|
| 82 |
}
|
| 83 |
+
return meta, None
|
| 84 |
|
| 85 |
+
except requests.exceptions.Timeout:
|
| 86 |
+
return None, "Request timed out. Check your internet connection."
|
| 87 |
+
except Exception as exc:
|
| 88 |
+
return None, str(exc)
|
| 89 |
|
| 90 |
|
| 91 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
# Transcript
|
| 93 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
+
|
| 95 |
+
def fetch_transcript(video_id: str) -> tuple[str, str]:
|
| 96 |
+
"""Return (text, status_message)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
try:
|
| 98 |
+
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
|
| 99 |
+
segments = YouTubeTranscriptApi.get_transcript(video_id)
|
| 100 |
text = " ".join(s["text"] for s in segments)
|
| 101 |
+
return text, f"β
Transcript: {len(text.split())} words"
|
| 102 |
+
except Exception as exc:
|
| 103 |
+
short = str(exc)[:80]
|
| 104 |
+
return "", f"β οΈ Transcript unavailable: {short}"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
+
# Comments
|
| 109 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
def fetch_comments(
|
| 112 |
video_id: str,
|
| 113 |
api_key: str,
|
| 114 |
+
max_comments: int = 150,
|
| 115 |
+
) -> tuple[pd.DataFrame, str]:
|
| 116 |
+
"""Return (DataFrame, status_message)."""
|
| 117 |
+
rows = []
|
| 118 |
+
next_token = None
|
| 119 |
+
|
|
|
|
| 120 |
try:
|
| 121 |
+
while len(rows) < max_comments:
|
| 122 |
+
want = min(100, max_comments - len(rows))
|
| 123 |
+
params = {
|
| 124 |
+
"videoId": video_id,
|
| 125 |
+
"key": api_key,
|
| 126 |
+
"part": "snippet",
|
| 127 |
+
"maxResults": want,
|
| 128 |
+
"order": "relevance",
|
| 129 |
+
}
|
| 130 |
+
if next_token:
|
| 131 |
+
params["pageToken"] = next_token
|
| 132 |
+
|
| 133 |
+
resp = requests.get(
|
| 134 |
+
"https://www.googleapis.com/youtube/v3/commentThreads",
|
| 135 |
+
params=params,
|
| 136 |
+
timeout=15,
|
| 137 |
)
|
| 138 |
+
data = resp.json()
|
| 139 |
+
|
| 140 |
+
if "error" in data:
|
| 141 |
+
msg = data["error"].get("message", "Comment API error")
|
| 142 |
+
break
|
| 143 |
+
|
| 144 |
+
for item in data.get("items", []):
|
| 145 |
+
c = item["snippet"]["topLevelComment"]["snippet"]
|
| 146 |
+
rows.append({
|
| 147 |
+
"author": c.get("authorDisplayName", ""),
|
| 148 |
+
"text": c.get("textDisplay", ""),
|
| 149 |
+
"likes": int(c.get("likeCount", 0)),
|
| 150 |
+
"published_at": c.get("publishedAt", "")[:10],
|
| 151 |
})
|
| 152 |
|
| 153 |
+
next_token = data.get("nextPageToken")
|
| 154 |
+
if not next_token or not data.get("items"):
|
| 155 |
break
|
| 156 |
|
| 157 |
+
if not rows:
|
| 158 |
+
return pd.DataFrame(), "β οΈ No comments fetched (comments may be disabled)"
|
| 159 |
|
| 160 |
+
df = pd.DataFrame(rows)
|
| 161 |
+
return df, f"β
Comments: {len(df)} fetched"
|
| 162 |
|
| 163 |
+
except requests.exceptions.Timeout:
|
| 164 |
+
return pd.DataFrame(), "β Comments request timed out"
|
| 165 |
+
except Exception as exc:
|
| 166 |
+
return pd.DataFrame(), f"β Comments error: {str(exc)[:80]}"
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββ
|
| 170 |
+
# Search by keyword
|
| 171 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 172 |
|
| 173 |
+
def search_videos_by_title(
|
| 174 |
+
keyword: str,
|
| 175 |
+
api_key: str,
|
| 176 |
+
max_results: int = 5,
|
| 177 |
+
) -> list[dict]:
|
| 178 |
try:
|
| 179 |
+
resp = requests.get(
|
| 180 |
+
"https://www.googleapis.com/youtube/v3/search",
|
| 181 |
+
params={
|
| 182 |
+
"q": keyword,
|
| 183 |
+
"key": api_key,
|
| 184 |
+
"part": "snippet",
|
| 185 |
+
"type": "video",
|
| 186 |
+
"maxResults": max_results,
|
| 187 |
+
},
|
| 188 |
+
timeout=15,
|
| 189 |
+
)
|
| 190 |
+
data = resp.json()
|
| 191 |
results = []
|
| 192 |
+
for item in data.get("items", []):
|
| 193 |
+
vid_id = item.get("id", {}).get("videoId", "")
|
| 194 |
+
sn = item.get("snippet", {})
|
| 195 |
+
if not vid_id:
|
| 196 |
+
continue
|
| 197 |
results.append({
|
| 198 |
+
"video_id": vid_id,
|
| 199 |
+
"title": sn.get("title", ""),
|
| 200 |
+
"channel_title": sn.get("channelTitle", ""),
|
| 201 |
+
"published_at": sn.get("publishedAt", "")[:10],
|
| 202 |
+
"thumbnail_url": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
|
| 203 |
})
|
| 204 |
return results
|
|
|
|
| 205 |
except Exception:
|
| 206 |
return []
|