Untitled conversation
- User
import time import requests import yt_dlp import os import re from google.colab import drive from google.colab import userdata from PIL import Image import requests from io import BytesIO # Retrieve sensitive information from Colab's userdata TELEGRAM_BOT_TOKEN = userdata.get('TELEGRAM_BOT_TOKEN') TELEGRAM_CHAT_ID = userdata.get('TELEGRAM_CHAT_ID') TOPIC_THREAD_ID = int(userdata.get('TOPIC_THREAD_ID')) if userdata.get('TOPIC_THREAD_ID') else None API_ID = userdata.get('API_ID') API_HASH = userdata.get('API_HASH') # I put it here, 'cause fuck rebel. ASMR_PATTERN = r'(?i)^(?!.*(?:gameplay|just\s*chatting|highlights|subathon)).*(?:^|[^@\w])\s*(?:ASMR(?:ing)?|(?:white|brown)\s*noise|sleep(?:ing)?|男性向け|女性向け|癒し|耳かき|囁き|음면|자장|꿀꿀|리랙스|F4[MFA][MF]?|M4[MFA][MF]?|A4[MFA][MF]?|ku100|heart\s?beat(?:ing|s)?|mouth\s*sounds|rest(?:ful|ing)?|breathy|whisper(?:s|ing)?|blowing|brush(?:ing)?|[Redacted Person](?:y|e|es|ing)?|hum(?:ming)?|roleplay(?:ing)?|tap(?:s|ping|pies)?|binaural|tingl(?:y|e|es|ies|ing)?|kiss(?:es|ing)?|smooch(?:es|ing|ies)|rub(?:bing|bies)?|relax(?:ing)?|soothing|personal\s*attention|s(?:ch)?lurp(?:ing)?|tongue\s*sounds|no\s*talking|soft\s*speak(?:ing)?|prais(?:es|ing)|ear\s*(?:play|eating|clean(?:ing)?|cup(?:s|ping|pies)?)|lick(?:s|ing)?|nom(?:s|ming)|thigh\s*cup(?:s|ping|pies)?|s[h]{1,9}|fantasy|comfort(?:ing)?|healing|massag(?:ing|e|es)|trigger(?:s)?|ambient|soundscape|meditation|mindfulness|lover|asmr(?:t)?ist|scratching|べろキス音|舌の音|口内の音|無言|リラックス|マッサージ|癒やし|睡眠導入|音フェチ|속삭임|심신안정|백색소음|수면유도|힐링|助眠|解压|白噪音|掏耳朵|按摩|轻声细语|哄睡|敲击|触发音|睡觉|放松|冥想|音控|療愈)(?!\w).*$' def get_secret(name): try: auth.authenticate_user() return output.eval_js(f"google.colab.secrets.get('{name}')") except Exception as e: print(f"Error retrieving secret {name}: {e}") return None # Initialize log file path with a default location LOG_FILE_PATH = '/tmp/downloaded_videos.txt' def initialize_log(): try: drive.mount('/content/drive') global LOG_FILE_PATH LOG_FILE_PATH = '/content/drive/My Drive/downloaded_videos.txt' except Exception as e: print("Google Drive mount failed. Using local storage for download tracking.") LOG_FILE_PATH = '/tmp/downloaded_videos.txt' if not os.path.exists(LOG_FILE_PATH): with open(LOG_FILE_PATH, 'w') as f: pass def print_progress(d): if d['status'] == 'downloading': progress = d.get('_percent_str', 'N/A') speed = d.get('_speed_str', 'N/A') eta = d.get('_eta_str', 'N/A') print(f"Progress: {progress} @ {speed} | ETA: {eta}", end='\r') [Redacted Person] d['status'] == 'finished': print("\nDownload completed. Starting post-processing...") def embed_thumbnail(file_path, thumbnail_url, is_audio=False): try: # Download thumbnail and convert to jpg if it's webp response = requests.get(thumbnail_url) if response.status_code == 200: temp_dir = os.path.dirname(file_path) temp_thumb = os.path.join(temp_dir, 'temp_thumb.jpg') temp_output = os.path.join(temp_dir, 'temp_output' + os.path.splitext(file_path)[1]) # Save thumbnail with open(temp_thumb, 'wb') as f: f.write(response.content) if thumbnail_url.endswith('.webp'): # Convert webp to jpg convert_cmd = [ 'ffmpeg', '-i', temp_thumb, '-y', temp_thumb + '.jpg' ] subprocess.run(convert_cmd, check=True, capture_output=True) os.replace(temp_thumb + '.jpg', temp_thumb) # Different commands for audio and video files if is_audio: cmd = [ 'ffmpeg', '-i', file_path, '-i', temp_thumb, '-map', '0:a', '-map', '1', '-codec:a', 'copy', '-codec:v', 'mjpeg', '-id3v2_version', '3', '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"', '-disposition:v', 'attached_pic', '-y', temp_output ] else: # For video files cmd = [ 'ffmpeg', '-i', file_path, '-i', temp_thumb, '-map', '0', '-map', '1', '-c', 'copy', '-c:v:1', 'mjpeg', '-disposition:v:1', 'attached_pic', '-y', temp_output ] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode == 0: os.replace(temp_output, file_path) print(f"Thumbnail embedded for {os.path.basename(file_path)}") else: print(f"ffmpeg stderr: {result.stderr}") raise subprocess.CalledProcessError(result.returncode, cmd) # Cleanup temporary files if os.path.exists(temp_thumb): os.remove(temp_thumb) if os.path.exists(temp_output) and temp_output != file_path: os.remove(temp_output) except Exception as e: print(f"Failed to embed thumbnail for {os.path.basename(file_path)}: {e}") if isinstance(e, subprocess.CalledProcessError): print(f"ffmpeg error output: {e.stderr}") def is_video_downloaded(video_url): try: with open(LOG_FILE_PATH, 'r') as f: downloaded_urls = f.read().splitlines() return video_url in downloaded_urls except Exception: return False def mark_video_as_downloaded(video_url): try: with open(LOG_FILE_PATH, 'a') as f: f.write(video_url + '\n') except Exception: print("Could not mark video as downloaded. Continuing anyway.") def start_bot(): binary_url = "https://github.com/jakbin/telegram-bot-api-binary/releases/download/latest/telegram-bot-api" binary_path = "/tmp/telegram-bot-api" if not os.path.exists(binary_path) or os.stat(binary_path).st_size == 0: print(f"Downloading Telegram Bot API binary from {binary_url}...") response = requests.get(binary_url, stream=True) response.raise_for_status() with open(binary_path, 'wb') as file: for chunk in response.iter_content(chunk_size=8192): file.write(chunk) print(f"Downloaded binary to {binary_path}") try: os.chmod(binary_path, 0o755) subprocess.[Redacted Person]([ binary_path, '--http-port', '8081', '--local', '--api-id', API_ID, '--api-hash', API_HASH ]) print("Telegram Bot API server started (I swaer to god if it hasn;t).") time.sleep(5) return True except Exception as e: print(f"Failed to start the Telegram Bot API server: {e}") return False def print_progress(d): """Enhanced real-time monitoring with speed analytics""" if d['status'] == 'downloading': current_speed = d.get('_speed_str', 'N/A').rjust(9) avg_speed = d.get('_avg_speed_str', 'N/A').rjust(9) progress = d.get('_percent_str', 'N/A').rjust(6) eta = d.get('_eta_str', 'N/A').rjust(6) print(f"▶️ {progress} | 🚀 {current_speed} | 📈 {avg_speed} | ⏳ {eta}", end='\r') [Redacted Person] d['status'] == 'finished': print(f"\n✅ Download completed in {d.get('_elapsed_str', 'N/A')}") def send_to_telegram(file_path, title, channel_name, is_video=True): """Send media file using Telegram Bot API's local mode with proper file URI scheme""" if not os.path.exists(file_path): print(f"Error: File '{file_path}' not found.") return duration = get_media_duration(file_path) thumb_path = get_thumbnail_path(file_path) # Convert paths to file:// URIs file_uri = f'file://{os.path.abspath(file_path)}' thumb_uri = f'file://{os.path.abspath(thumb_path)}' if thumb_path else None # Configure request parameters if is_video: endpoint = 'sendVideo' data = { 'video': file_uri, 'supports_streaming': 'true', 'caption': f"Video from {channel_name}\nTitle: {title}", } else: endpoint = 'sendAudio' data = { 'audio': file_uri, 'title': title, 'performer': channel_name, 'caption': f"Audio-only from {channel_name}\nTitle: {title}", } # Add thumbnail if available if thumb_uri: data['thumb'] = thumb_uri # Common parameters data.update({ 'chat_id': TELEGRAM_CHAT_ID, 'duration': duration, 'message_thread_id': TOPIC_THREAD_ID, }) url = f'http://localhost:8081/bot{TELEGRAM_BOT_TOKEN}/{endpoint}' try: start_time = time.time() response = requests.post(url, data=data) end_time = time.time() if response.status_code == 200: print(f'✅ "{title}" uploaded in {end_time-start_time:.2f}s') else: print(f'❌ Failed to upload "{title}":', response.text) except Exception as e: print(f"⚠️ Error sending {title}: {str(e)}") finally: if thumb_path and os.path.exists(thumb_path): os.remove(thumb_path) def search_youtube_channel(channel_url): ydl_opts = { 'quiet': True, 'extract_flat': 'in_playlist', 'ignoreerrors': True, 'external_downloader': 'aria2c', 'external_downloader_args': [ '-x16', '-s32', '-k20M', '--max-connection-per-server=16', '--stream-piece-selector=geom', '--lowest-speed-limit=2M', '--socket-recv-buffer-size=4M', '--header=Accept-Encoding: gzip, deflate, br' ] } try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info(channel_url, download=False) videos = result.get('entries', []) channel_name = result.get('title', "Unknown Channel") matching_videos = [ { 'url': video['url'], 'title': video['title'], 'channel_name': channel_name, 'thumbnail': video.get('thumbnail', video.get('thumbnails', [{'url': None}])[0]['url']) } for video in videos if video and re.search(ASMR_PATTERN, video['title']) and not video.get('is_live', False) and not video.get('live_status') == 'is_upcoming' ] return matching_videos except Exception as e: print(f"Error processing channel {channel_url}: {e}") return [] def clean_filename(title): return re.sub(r'\[.*?\]', '', title).strip() def set_audio_metadata(audio_path, uploader, title): try: cmd = [ 'ffmpeg', '-i', audio_path, '-metadata', f'artist={uploader}', '-metadata', f'album={title}', '-metadata', f'title={uploader} - {title}', '-codec', 'copy', audio_path + '.temp.m4a' ] subprocess.run(cmd, check=True, capture_output=True) os.replace(audio_path + '.temp.m4a', audio_path) print(f"Metadata updated for {audio_path}") except Exception as e: print(f"Failed to set metadata for {audio_path}: {e}") def download_video_and_audio(url, video_title, channel_name, thumbnail_url): cleaned_title = clean_filename(video_title) video_path = f"/tmp/{cleaned_title}.mp4" audio_path = f"/tmp/{cleaned_title}.m4a" if os.path.exists(video_path) and os.path.exists(audio_path): print(f"Files for {cleaned_title} already exist, skipping download.") return video_path, audio_path # Optimized video download config ydl_opts_video = { 'format': 'bestvideo[ext=mp4][protocol=dash]+bestaudio/best', 'outtmpl': video_path, 'merge_output_format': 'mp4', 'external_downloader': 'aria2c', 'external_downloader_args': [ '-x16', '-s32', '-k20M', '--max-connection-per-server=16', '--lowest-speed-limit=2M', '--min-split-size=10M', '--socket-recv-buffer-size=4M', '--file-allocation=falloc', '--header=Accept-Encoding: gzip, deflate, br' ], 'progress_hooks': [print_progress], } # Optimized audio download config ydl_opts_audio = { 'format': 'bestaudio[ext=m4a]/bestaudio/best', 'outtmpl': audio_path, 'external_downloader': 'aria2c', 'external_downloader_args': ['-x16', '-s16', '-k1M'], 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'm4a', 'preferredquality': '192', }], 'progress_hooks': [print_progress], } try: # Download video print(f"\nStarting video download: {video_title}") with yt_dlp.YoutubeDL(ydl_opts_video) as ydl: ydl.download([url]) # Download audio print(f"\nStarting audio download: {video_title}") with yt_dlp.YoutubeDL(ydl_opts_audio) as ydl: ydl.download([url]) # Embed thumbnail if thumbnail_url: print(f"Using thumbnail URL: {thumbnail_url}") time.sleep(1) embed_thumbnail(video_path, thumbnail_url, is_audio=False) embed_thumbnail(audio_path, thumbnail_url, is_audio=True) else: print(f"No thumbnail URL found for {video_title}") set_audio_metadata(audio_path, channel_name, video_title) return video_path, audio_path except yt_dlp.utils.ExtractorError as e: print(f"Skipping video '{video_title}' due to age restriction or other issues: {e}") return None, None except Exception as e: print(f"Error downloading video '{video_title}': {e}") return None, None def get_media_duration(file_path): try: cmd = [ 'ffprobe', '-v', 'quiet', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path ] result = subprocess.run(cmd, capture_output=True, text=True) return int(float(result.stdout.strip())) except Exception as e: print(f"Failed to get duration for {file_path}: {e}") return 0 def get_thumbnail_path(file_path): try: thumb_path = f"{file_path}_thumb.jpg" cmd = [ 'ffmpeg', '-i', file_path, '-map', '0:v', '-map', '-0:V', '-c', 'copy', '-y', thumb_path ] subprocess.run(cmd, capture_output=True) if os.path.exists(thumb_path) and os.path.getsize(thumb_path) > 0: return thumb_path except Exception as e: print(f"Failed to extract thumbnail from {file_path}: {e}") return None def process_video(video): video_url = video['url'] video_title = video['title'] channel_name = video['channel_name'] thumbnail_url = video['thumbnail'] print(f"\nProcessing: {video_title}") if is_video_downloaded(video_url): print(f"Video '{video_title}' already processed. Skipping.") return video_path, audio_path = download_video_and_audio(video_url, video_title, channel_name, thumbnail_url) if video_path: send_to_telegram(video_path, video_title, channel_name, is_video=True) if audio_path: send_to_telegram(audio_path, video_title, channel_name, is_video=False) mark_video_as_downloaded(video_url) def process_channel(channel_url): print(f"\n{'='*40}") print(f"Processing channel: {channel_url}") videos = search_youtube_channel(channel_url) if videos: print(f"Found {len(videos)} matching video(s)") for video in videos: process_video(video) else: print(f"No matching ASMR content found in this channel") if __name__ == "__main__": # Install required dependencies subprocess.run(['apt-get', 'update'], check=True) subprocess.run(['apt-get', 'install', '-y', 'aria2'], check=True) initialize_log() if start_bot(): channel_urls = [ 'https://www.youtube.com/@REMKanashibari/streams', 'https://www.youtube.com/@yomiquinnley/videos', 'https://www.youtube.com/@yomiquinnley/streams', 'https://www.youtube.com/@REMKanashibari/videos', 'https://www.youtube.com/@AliasAnono/videos', 'https://www.youtube.com/@AliasAnono/streams', 'https://www.youtube.com/@niminightmare/videos', 'https://www.youtube.com/@niminightmare/streams', 'https://www.youtube.com/@NeneAmanoCh/videos', 'https://www.youtube.com/@NeneAmanoCh/streams', 'https://www.youtube.com/@sachinawasthi/videos', 'https://www.youtube.com/@sachinawasthi/streams', 'https://www.youtube.com/@Diabolikha/videos', 'https://www.youtube.com/@Diabolikha/streams', 'https://www.youtube.com/@YumemiChannel/videos', 'https://www.youtube.com/@YumemiChannel/streams', 'https://www.youtube.com/@GyanTherapy/videos', ] for channel_url in channel_urls: process_channel(channel_url) time.sleep(0.1)``` Port this script to golang. Also add concurrency in the processing and other stuff to make it faster. The compiled binary will run in colab. I want to combine the asmr finding embedding and other stuff of this script to the downloading and uploading part of this script. Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.