milind1989's picture
Update app.py
32a30d8 verified
Raw History Blame Contribute Delete
12.2 kB
import gradio as gr
import whisper
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from youtube_transcript_api import YouTubeTranscriptApi
import yt_dlp
import tempfile
import os
import re
import logging
import time
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Set cache directory for whisper
os.environ['XDG_CACHE_HOME'] = os.path.expanduser('~/.cache')
os.environ['MPLCONFIGDIR'] = os.path.expanduser('~/.config/matplotlib')
# Initialize Whisper model
try:
model = whisper.load_model("tiny", download_root=os.path.expanduser('~/.cache/whisper'))
logger.info("Whisper model loaded successfully")
except Exception as e:
logger.error(f"Error loading Whisper model: {str(e)}")
raise
def get_youtube_cookies():
"""Get cookies for YouTube from a pre-configured file"""
cookie_file = os.path.expanduser('~/cookies.txt')
if not os.path.exists(cookie_file):
# Create a basic cookie file if it doesn't exist
with open(cookie_file, 'w') as f:
f.write("""# Netscape HTTP Cookie File
.youtube.com TRUE / TRUE 2147483647 CONSENT YES+
.youtube.com TRUE / TRUE 2147483647 VISITOR_INFO1_LIVE random_string
""")
return cookie_file
def extract_video_id(url):
"""Extract video ID from YouTube URL"""
patterns = [
r'(?:youtube\.com\/watch\?v=|youtu.be\/)([\w-]+)',
r'(?:youtube\.com\/embed\/)([\w-]+)',
r'(?:youtube\.com\/v\/)([\w-]+)',
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1)
return None
def try_transcript_api(url):
"""Method 1: Try using YouTube Transcript API"""
logger.info("Trying YouTube Transcript API...")
video_id = extract_video_id(url)
if not video_id:
raise ValueError("Could not extract video ID")
transcript = YouTubeTranscriptApi.get_transcript(video_id)
return " ".join([entry['text'] for entry in transcript])
def setup_chrome_options():
"""Setup Chrome options for Docker environment"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-software-rasterizer')
chrome_options.add_argument('--remote-debugging-port=9222')
chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument('--start-maximized')
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)
# Add cookie handling
cookie_file = get_youtube_cookies()
if os.path.exists(cookie_file):
chrome_options.add_argument(f'--cookie-file={cookie_file}')
return chrome_options
def try_selenium(url):
"""Method 2: Try using Selenium"""
logger.info("Trying Selenium method...")
driver = None
try:
options = setup_chrome_options()
driver = webdriver.Chrome(options=options)
# Execute CDP commands to prevent detection
driver.execute_cdp_cmd('Network.setUserAgentOverride', {
"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
})
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
logger.info("Navigating to URL...")
driver.get(url)
# Wait for video to load
time.sleep(10) # Increased wait time
try:
# Try clicking the play button first
play_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CLASS_NAME, "ytp-play-button"))
)
driver.execute_script("arguments[0].click();", play_button)
time.sleep(2)
# Now try to enable captions
captions_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "ytp-subtitles-button"))
)
# Try different methods to click the captions button
try:
captions_button.click()
except:
try:
driver.execute_script("arguments[0].click();", captions_button)
except:
# Try finding it again and clicking
driver.find_element(By.CLASS_NAME, "ytp-subtitles-button").click()
time.sleep(5) # Wait longer for captions
# Try multiple caption element classes
caption_classes = ["captions-text", "ytp-caption-segment"]
transcript_text = ""
for class_name in caption_classes:
try:
elements = driver.find_elements(By.CLASS_NAME, class_name)
if elements:
transcript_text = " ".join([el.text for el in elements if el.text])
if transcript_text:
break
except:
continue
if not transcript_text:
raise Exception("No caption text found")
return transcript_text
except Exception as e:
logger.warning(f"Error with captions: {str(e)}")
raise Exception(f"Could not handle captions: {str(e)}")
except Exception as e:
logger.error(f"Selenium error: {str(e)}")
raise
finally:
if driver:
try:
driver.quit()
except:
pass
def try_yt_dlp(url):
"""Method 3: Try using yt-dlp"""
logger.info("Trying yt-dlp method...")
temp_dir = os.path.expanduser('~/downloads')
os.makedirs(temp_dir, exist_ok=True)
cookie_file = get_youtube_cookies()
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
}],
'quiet': True,
'no_warnings': True,
'extract_audio': True,
'outtmpl': os.path.join(temp_dir, '%(id)s.%(ext)s'),
'no_check_certificate': True,
'ignoreerrors': False,
'cookiefile': cookie_file,
'socket_timeout': 30,
'retries': 3,
}
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False, dir=temp_dir) as temp_file:
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
logger.info("Extracting video info...")
info = ydl.extract_info(url, download=False)
if info is None:
raise Exception("Could not extract video info")
video_id = info['id']
logger.info("Downloading audio...")
download_result = ydl.download([url])
if download_result != 0:
raise Exception("Download failed")
downloaded_file = os.path.join(temp_dir, f"{video_id}.mp3")
if os.path.exists(downloaded_file):
os.rename(downloaded_file, temp_file.name)
logger.info("Starting transcription...")
result = model.transcribe(temp_file.name)
return result["text"]
else:
raise Exception(f"Downloaded file not found: {downloaded_file}")
except Exception as e:
logger.error(f"yt-dlp error: {str(e)}")
raise
finally:
if os.path.exists(temp_file.name):
try:
os.remove(temp_file.name)
logger.info("Cleaned up temporary file")
except:
pass
def try_whisper_direct(url):
"""Method 4: Try direct whisper transcription"""
logger.info("Trying direct whisper transcription...")
temp_dir = os.path.expanduser('~/downloads')
os.makedirs(temp_dir, exist_ok=True)
cookie_file = get_youtube_cookies()
ydl_opts = {
'format': 'bestaudio/best',
'extract_audio': True,
'audio_format': 'mp3',
'outtmpl': os.path.join(temp_dir, '%(id)s.%(ext)s'),
'quiet': True,
'no_warnings': True,
'no_check_certificate': True,
'ignoreerrors': False,
'cookiefile': cookie_file,
'socket_timeout': 30,
'retries': 3,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
}],
}
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False, dir=temp_dir) as temp_file:
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
if info is None:
raise Exception("Could not extract video info")
video_id = info['id']
audio_file = os.path.join(temp_dir, f"{video_id}.mp3")
if os.path.exists(audio_file):
os.rename(audio_file, temp_file.name)
result = model.transcribe(temp_file.name)
return result["text"]
else:
raise Exception("Audio file not found")
except Exception as e:
logger.error(f"Direct whisper error: {str(e)}")
raise
finally:
if os.path.exists(temp_file.name):
try:
os.remove(temp_file.name)
except:
pass
def transcribe(youtube_url):
"""Main function that tries multiple methods"""
methods = [
try_transcript_api,
try_selenium,
try_yt_dlp,
try_whisper_direct
]
errors = []
for method in methods:
try:
logger.info(f"Attempting method: {method.__name__}")
result = method(youtube_url)
if result:
logger.info(f"Success with method: {method.__name__}")
return result
except Exception as e:
error_msg = f"{method.__name__} failed: {str(e)}"
logger.error(error_msg)
errors.append(error_msg)
continue
# If all methods fail, return the errors
return f"All methods failed:\n" + "\n".join(errors)
# Create Gradio interface
iface = gr.Interface(
fn=transcribe,
inputs=gr.Textbox(
label="YouTube URL",
placeholder="Enter YouTube URL here...",
info="Works with most YouTube videos"
),
outputs=gr.Textbox(
label="Transcription",
show_copy_button=True
),
title="YouTube Video Transcriber",
description="Enter a YouTube URL to get its transcription. This tool will try multiple methods to get the transcript.",
examples=[
["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
],
cache_examples=False
)
# Launch the app
if __name__ == "__main__":
# Ensure cache directories exist
os.makedirs(os.path.expanduser('~/.cache'), exist_ok=True)
os.makedirs(os.path.expanduser('~/.config'), exist_ok=True)
os.makedirs(os.path.expanduser('~/.config/matplotlib'), exist_ok=True)
os.makedirs(os.path.expanduser('~/.config/chrome'), exist_ok=True)
os.makedirs(os.path.expanduser('~/downloads'), exist_ok=True)
# Launch the interface
iface.launch(server_name="0.0.0.0", server_port=7860)