Spaces:
Sleeping
Sleeping
| from config import YOUTUBE_API_KEY | |
| def _get_client(): | |
| """Inisialisasi YouTube client di dalam fungsi, bukan module level.""" | |
| if not YOUTUBE_API_KEY: | |
| print("⚠️ YOUTUBE_API_KEY tidak diset") | |
| return None | |
| try: | |
| from googleapiclient.discovery import build | |
| return build('youtube', 'v3', developerKey=YOUTUBE_API_KEY) | |
| except Exception as e: | |
| print(f"❌ Gagal init YouTube client: {e}") | |
| return None | |
| def search_videos(keyword: str, max_results: int = 3) -> list: | |
| youtube = _get_client() | |
| if not youtube: | |
| return [] | |
| try: | |
| res = youtube.search().list( | |
| part="snippet", | |
| q=keyword, | |
| type="video", | |
| maxResults=max_results, | |
| relevanceLanguage="id" | |
| ).execute() | |
| return [item['id']['videoId'] for item in res.get('items', [])] | |
| except Exception as e: | |
| print(f"❌ YouTube search error: {e}") | |
| return [] | |
| def get_comments(video_id: str, max_results: int = 50) -> list: | |
| youtube = _get_client() | |
| if not youtube: | |
| return [] | |
| comments = [] | |
| try: | |
| res = youtube.commentThreads().list( | |
| part="snippet", | |
| videoId=video_id, | |
| maxResults=max_results, | |
| textFormat="plainText" | |
| ).execute() | |
| for item in res.get('items', []): | |
| text = item['snippet']['topLevelComment']['snippet']['textDisplay'] | |
| if text.strip(): | |
| comments.append(text) | |
| except Exception as e: | |
| print(f"❌ YouTube get_comments error: {e}") | |
| return comments |