cuando es youtube como obtengo el texto del video de la descripcion: "from…
- User
cuando es youtube como obtengo el texto del video de la descripcion: "from youtube_transcript_api import YouTubeTranscriptApi import requests from bs4 import BeautifulSoup import PyPDF2 from io import BytesIO
def fetch_text_from_url(url): """ Obtiene texto de una URL de YouTube u otros documentos HTML o PDF.
:param url: Una cadena que representa la URL de la que se desea obtener el texto. :return: Una tupla (tipo_de_contenido, texto) donde 'tipo_de_contenido' es 'html', 'pdf', 'youtube' o 'other', y 'texto' es el texto extraído o un mensaje de error. """
def check_url_content_type(url): try: response = requests.head(url, allow_redirects=True) content_type = response.headers.get('Content-Type', '').lower()
if 'application/pdf' in content_type: return 'pdf' elif 'youtube' in url: return 'youtube' elif 'text/html' in content_type: return 'html' else: return 'other' except requests.exceptions.RequestException: return Noneheaders = { 'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'), 'Accept-Language': 'en-US,en;q=0.9', }
try: # Para analizar qué tipo de contenido se tiene content_type = check_url_content_type(url)
response = requests.get(url, headers=headers) response.raise_for_status() if content_type == 'youtube': # Extraer el video_id de la URL de YouTube if 'v=' in url: soup = BeautifulSoup(response.text, 'html.parser') text = soup.get_text() formatted_text = '\n'.join([line.strip() for line in text.splitlines() if line.strip()]) video_id = url.split('v=')[1].split('&')[0] # Obtener la transcripción usando youtube_transcript_api try: transcript_list = YouTubeTranscriptApi.get_transcript(video_id) transcript_text = "\n".join([entry['text'] for entry in transcript_list]) return 'youtube', formatted_text + '\n' + transcript_text except Exception as e: return 'error', f'No se pudo obtener la transcripción: {e}' if content_type == 'html': soup = BeautifulSoup(response.text, 'html.parser') text = soup.get_text() formatted_text = '\n'.join([line.strip() for line in text.splitlines() if line.strip()]) return 'html', formatted_text elif content_type == 'pdf': pdf_file = BytesIO(response.content) pdf_reader = PyPDF2.PdfReader(pdf_file) pdf_text = '' for page in pdf_reader.pages: if len(pdf_text) > 100000: break pdf_text += page.extract_text() return 'pdf', pdf_text else: return 'other', 'Tipo de contenido no soportado o desconocido.'except requests.exceptions.RequestException as e: return 'error', f'Error al realizar la solicitud: {e}'
except Exception as e: return 'error', f'Ocurrió un error: {e}' "
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.