Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import threading
- import os
- import yt_dlp
- import httpx
- import subprocess
- import re
- import tempfile
- import sys
- print("Server is running...")
- # Function to get local IP
- def get_local_ip():
- try:
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s.connect(("8.8.8.8", 80)) # Connect to Google's DNS server
- local_ip = s.getsockname()[0]
- s.close()
- return local_ip
- except Exception as e:
- return "Error: " + str(e)
- # Function to handle broadcasting the IP
- def run_ip_broadcast():
- HOST = '0.0.0.0' # Listen on all interfaces
- PORT = 65432
- with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
- s.bind((HOST, PORT))
- print(f"IP Broadcast Server running on port {PORT}...")
- try:
- while True:
- data, addr = s.recvfrom(1024)
- if data.decode().strip() == "GET_IP":
- local_ip = get_local_ip()
- s.sendto(local_ip.encode(), addr)
- print(f"Sent IP to {addr[0]}")
- except KeyboardInterrupt:
- print("\nServer stopped by user.")
- def check_thumbnail_exists(url):
- try:
- response = httpx.head(url)
- return response.status_code == 200 # Thumbnail exists if response code is 200
- except httpx.RequestError:
- return False
- # Get the best thumbnail available from YouTube
- def get_best_thumbnail_url(youtube_url):
- # Extract video ID considering different URL formats
- video_id = None
- if 'youtu.be/' in youtube_url:
- video_id = youtube_url.split('youtu.be/')[-1].split('?')[0]
- elif 'v=' in youtube_url:
- video_id = youtube_url.split('v=')[-1].split('&')[0]
- elif '/watch/' in youtube_url:
- video_id = youtube_url.split('/watch/')[1].split('?')[0]
- if not video_id:
- print("Invalid YouTube URL.")
- return None
- thumbnail_urls = {
- "max": f"https://img.youtube.com/vi/{video_id}/sddefault.jpg", # Highest resolution
- "high": f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg", # High quality
- "medium": f"https://img.youtube.com/vi/{video_id}/mqdefault.jpg", # Medium quality
- "default": f"https://img.youtube.com/vi/{video_id}/default.jpg" # Default quality
- }
- for quality, url in thumbnail_urls.items():
- if check_thumbnail_exists(url):
- print(f"Found thumbnail at {quality} quality: {url}")
- return url
- print("No thumbnail available.")
- return None
- # Sanitize file name to remove or replace unsupported characters
- def sanitize_filename(filename):
- sanitized = re.sub(r'[\\/*?:"<>|]', '_', filename)
- return sanitized
- # Download the video using yt-dlp
- def download_video_with_placeholder(youtube_url, output_path="."):
- placeholder_video_file = os.path.join(output_path, "VIDEO.mp4") # Temporary video file name
- ydl_opts = {
- 'format': 'bestvideo+bestaudio/best',
- 'outtmpl': placeholder_video_file,
- 'merge_output_format': 'mp4',
- 'quiet': True,
- }
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- print(f"Downloading video from: {youtube_url}")
- ydl.download([youtube_url])
- # Extract info (we'll use the original title later)
- info = ydl.extract_info(youtube_url, download=False)
- return placeholder_video_file, info
- # Convert the downloaded video to MP3 using FFmpeg
- def convert_to_mp3_with_ffmpeg(video_file_path, output_mp3_path):
- print(f"Converting {video_file_path} to MP3 using FFmpeg...")
- command = [
- 'ffmpeg', '-i', video_file_path,
- '-vn', # Disable video output (audio only)
- '-acodec', 'libmp3lame', # MP3 encoding
- output_mp3_path
- ]
- subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- print(f"Converted to MP3: {output_mp3_path}")
- # Embed thumbnail into MP3 using FFmpeg
- def embed_thumbnail_with_ffmpeg(mp3_file_path, thumbnail_file_path, output_mp3_with_thumbnail):
- print(f"Embedding thumbnail {thumbnail_file_path} into MP3 using FFmpeg...")
- command = [
- 'ffmpeg', '-i', mp3_file_path,
- '-i', thumbnail_file_path, # Input the thumbnail
- '-map', '0:a', '-map', '1:v', # Map audio from mp3, video from thumbnail
- '-c', 'copy', # Copy audio data without re-encoding
- '-id3v2_version', '3', # Use ID3v2.3 metadata standard for album art
- '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"',
- output_mp3_with_thumbnail
- ]
- subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- print(f"MP3 with thumbnail saved to: {output_mp3_with_thumbnail}")
- # Download the thumbnail image using httpx
- def download_thumbnail(thumbnail_url, output_path):
- if thumbnail_url:
- print(f"Downloading thumbnail from: {thumbnail_url}")
- try:
- with httpx.stream("GET", thumbnail_url) as response:
- if response.status_code == 200:
- thumbnail_file_path = os.path.join(output_path, "thumbnail.jpg")
- with open(thumbnail_file_path, 'wb') as f:
- for chunk in response.iter_bytes():
- f.write(chunk)
- print(f"Downloaded thumbnail to: {thumbnail_file_path}")
- return thumbnail_file_path
- except httpx.RequestError:
- print("Failed to download thumbnail.")
- return None
- # Cleanup the downloaded files
- def cleanup(files):
- for file in files:
- if os.path.exists(file):
- os.remove(file)
- print(f"Deleted: {file}")
- else:
- print(f"File not found: {file}")
- def download_audio_with_thumbnail(youtube_url, output_path="."):
- if not os.path.exists(output_path):
- os.makedirs(output_path)
- # Step 1: Download the video with a placeholder name
- video_file_path, info = download_video_with_placeholder(youtube_url, output_path)
- # Step 2: Get the best available thumbnail URL
- thumbnail_url = get_best_thumbnail_url(youtube_url)
- thumbnail_file_path = download_thumbnail(thumbnail_url, output_path)
- # Step 3: Convert to MP3 using FFmpeg (with a placeholder name)
- mp3_file_path = os.path.join(output_path, "audio.mp3")
- convert_to_mp3_with_ffmpeg(video_file_path, mp3_file_path)
- # Step 4: Embed the thumbnail into the MP3 using FFmpeg
- if thumbnail_file_path:
- mp3_with_thumbnail_path = os.path.join(output_path, "audio_with_thumbnail.mp3")
- embed_thumbnail_with_ffmpeg(mp3_file_path, thumbnail_file_path, mp3_with_thumbnail_path)
- else:
- mp3_with_thumbnail_path = mp3_file_path
- # Step 5: Rename the final MP3 file to the original title
- final_mp3_path = os.path.join(output_path, f"{sanitize_filename(info['title'])}.mp3")
- os.rename(mp3_with_thumbnail_path, final_mp3_path)
- print(f"Renamed final MP3 to: {final_mp3_path}")
- # Step 6: Clean up (delete temporary files: video, thumbnail, and initial MP3)
- cleanup([video_file_path, thumbnail_file_path, mp3_file_path])
- return final_mp3_path # Return the path of the final MP3 file
- # Function to handle each client
- def handle_client(conn, addr):
- print(f"Client {addr} connected.")
- # Send input prompt
- conn.sendall(b"Enter YouTube video URLs separated by spaces: ")
- # Receive video URLs from client
- data = conn.recv(1024).decode().strip()
- if not data:
- print("No URLs received. Closing connection.")
- conn.close()
- return
- video_urls = data.split()
- processed_files = []
- # Specify the directory where the temporary directory should be created
- temp_dir_base = "C:/Users/06mosnaz/Desktop/Laboratory/temporary_files" # Replace with the desired path
- # Create a temporary directory for processing
- with tempfile.TemporaryDirectory(dir=temp_dir_base) as temp_dir:
- # Process each URL
- for url in video_urls:
- try:
- mp3_file = download_audio_with_thumbnail(url, output_path=temp_dir)
- if mp3_file:
- processed_files.append(mp3_file)
- except Exception as e:
- print(f"Error processing {url}: {e}")
- # Send file(s) to the client
- for mp3_file in processed_files:
- file_name = os.path.basename(mp3_file)
- file_size = os.path.getsize(mp3_file)
- conn.sendall(f"{file_name}\n".encode()) # Send file name
- conn.recv(3) # Wait for ACK
- conn.sendall(f"{file_size}\n".encode()) # Send file size
- conn.recv(3) # Wait for ACK
- with open(mp3_file, "rb") as f:
- conn.sendall(f.read())
- os.remove(mp3_file) # Cleanup after sending
- print("File transfer complete.")
- conn.close()
- # Function to run the main server
- def run_server():
- HOST = get_local_ip()
- PORT = 65433 # TCP port for client communication
- server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- server_socket.bind((HOST, PORT))
- server_socket.listen()
- print(f"Server listening on {HOST}:{PORT}...")
- while True:
- conn, addr = server_socket.accept()
- client_thread = threading.Thread(target=handle_client, args=(conn, addr))
- client_thread.start()
- # Run both IP broadcasting and the main server simultaneously
- if __name__ == "__main__":
- threading.Thread(target=run_ip_broadcast, daemon=True).start()
- run_server()
Advertisement
Add Comment
Please, Sign In to add comment