Spaces:
Sleeping
Sleeping
Joachim M. Vis commited on
Upload multimodal_tools.py
Browse files4 unmodified lines56789103 unmodified lines14151617181913 unmodified lines333435363738513 unmodified lines5525535545554 unmodified lines- Image analysis and description- Chart/graph interpretation- Document parsingAll tools handle errors gracefully and provide detailed error messages."""3 unmodified linesimport jsonimport osimport tempfilefrom typing import Dict, Any, List, Optional, Union, BinaryIOfrom pathlib import Path13 unmodified linespdf2image = Nonedocx2txt = Nonefrom agent.config import get_model_config, get_tool_configfrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplate513 unmodified linesdef create_document_parser() -> DocumentParser:"""Create a document parser instance."""return DocumentParser()4 unmodified lines5678910113 unmodified lines1516171819202113 unmodified lines353637383940414243444546513 unmodified lines5605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887894 unmodified lines- Image analysis and description- Chart/graph interpretation- Document parsing- YouTube video analysis and transcript extractionAll tools handle errors gracefully and provide detailed error messages."""3 unmodified linesimport jsonimport osimport tempfileimport refrom typing import Dict, Any, List, Optional, Union, BinaryIOfrom pathlib import Path13 unmodified linespdf2image = Nonedocx2txt = Nonetry:from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFoundimport requestsexcept ImportError:YouTubeTranscriptApi = Nonefrom agent.config import get_model_config, get_tool_configfrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplate513 unmodified linesdef create_document_parser() -> DocumentParser:"""Create a document parser instance."""return DocumentParser()class YouTubeVideoTool:"""Tool for analyzing YouTube videos and extracting transcripts."""def __init__(self, config: Optional[Dict[str, Any]] = None):"""Initialize the YouTube video tool.Args:config: Optional configuration dictionary"""self.config = config or get_tool_config().get("youtube_video", {})self.model_config = get_model_config()self.model = ChatOpenAI(model=self.model_config.get("text_model", "gpt-4o"),temperature=self.model_config.get("temperature", 0.1),max_tokens=self.model_config.get("max_tokens", 4096))if YouTubeTranscriptApi is None:logger.warning("youtube_transcript_api not installed. Install with: pip install youtube-transcript-api")def extract_video_id(self, url: str) -> str:"""Extract the YouTube video ID from a URL.Args:url: YouTube video URLReturns:YouTube video IDRaises:ValueError: If the video ID cannot be extracted"""# Regular expressions for different YouTube URL formatspatterns = [r'(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/|youtube\.com\/e\/|youtube\.com\/watch\?.*v=|youtube\.com\/watch\?.*&v=)([^&\n?#]+)',r'youtube\.com\/shorts\/([^&\n?#]+)']for pattern in patterns:match = re.search(pattern, url)if match:return match.group(1)raise ValueError(f"Could not extract video ID from URL: {url}")def extract_transcript(self, video_id_or_url: str, language: Optional[str] = None) -> Dict[str, Any]:"""Extract transcript from a YouTube video.Args:video_id_or_url: YouTube video ID or URLlanguage: Optional language code for transcript (e.g., 'en', 'fr')Returns:Dictionary containing the transcript and metadataRaises:Exception: If an error occurs during transcript extraction"""if YouTubeTranscriptApi is None:raise ImportError("youtube_transcript_api not installed. Install with: pip install youtube-transcript-api")try:# Check if input is a URL or a video IDif "youtube.com" in video_id_or_url or "youtu.be" in video_id_or_url:video_id = self.extract_video_id(video_id_or_url)else:video_id = video_id_or_url# Get video metadatametadata = self.get_video_metadata(video_id)# Get transcriptif language:transcript_list = YouTubeTranscriptApi.get_transcript(video_id, languages=[language])else:transcript_list = YouTubeTranscriptApi.get_transcript(video_id)# Format transcript with timestampsformatted_transcript = self._format_transcript(transcript_list)# Process transcript to identify speakers (if possible)processed_transcript = self._process_transcript_with_speakers(formatted_transcript)return {"video_id": video_id,"title": metadata.get("title", ""),"channel": metadata.get("channel", ""),"transcript": formatted_transcript,"processed_transcript": processed_transcript,"duration_seconds": metadata.get("duration", 0),"language": language or "auto-detected"}except TranscriptsDisabled as e:logger.error(f"Transcripts are disabled for this video: {str(e)}")return {"video_id": video_id,"error": "Transcripts are disabled for this video","error_type": "TranscriptsDisabled"}except NoTranscriptFound as e:logger.error(f"No transcript found for this video: {str(e)}")return {"video_id": video_id,"error": "No transcript found for this video","error_type": "NoTranscriptFound"}except Exception as e:logger.error(f"Error extracting transcript: {str(e)}")logger.error(traceback.format_exc())return {"video_id": video_id if 'video_id' in locals() else video_id_or_url,"error": f"Transcript extraction failed: {str(e)}","error_type": type(e).__name__}def get_video_metadata(self, video_id: str) -> Dict[str, Any]:"""Get metadata for a YouTube video.Args:video_id: YouTube video IDReturns:Dictionary containing video metadata"""try:# Use YouTube's oEmbed API to get basic metadataoembed_url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"response = requests.get(oembed_url)if response.status_code == 200:metadata = response.json()return {"title": metadata.get("title", ""),"channel": metadata.get("author_name", ""),"thumbnail_url": metadata.get("thumbnail_url", ""),"duration": 0 # YouTube's oEmbed API doesn't provide duration}else:# Fallback to minimal metadatareturn {"title": "Unknown","channel": "Unknown","thumbnail_url": "","duration": 0}except Exception as e:logger.warning(f"Error fetching video metadata: {str(e)}")return {"title": "Unknown","channel": "Unknown","thumbnail_url": "","duration": 0}def _format_transcript(self, transcript_list: List[Dict[str, Any]]) -> str:"""Format transcript with timestamps.Args:transcript_list: List of transcript segmentsReturns:Formatted transcript string"""formatted_lines = []for item in transcript_list:start_time = item['start']text = item['text']# Convert seconds to MM:SS formatminutes = int(start_time // 60)seconds = int(start_time % 60)timestamp = f"[{minutes:02d}:{seconds:02d}]"formatted_lines.append(f"{timestamp} {text}")return "\n".join(formatted_lines)def _process_transcript_with_speakers(self, transcript: str) -> str:"""Process transcript to identify speakers if possible.Args:transcript: Formatted transcript stringReturns:Processed transcript with speaker identification if possible"""try:# Use LLM to identify potential speakers in the transcriptprompt = f"""Analyze this YouTube video transcript and identify different speakers if possible.Format the transcript with speaker labels (e.g., "Speaker 1:", "Speaker 2:").If you cannot confidently identify different speakers, return the transcript as is.Transcript:{transcript}Processed transcript with speakers:"""prompt_template = PromptTemplate.from_template(prompt)chain = prompt_template | self.model | StrOutputParser()result = chain.invoke({})return resultexcept Exception as e:logger.warning(f"Error processing transcript with speakers: {str(e)}")return transcript # Return original transcript if processing failsdef create_youtube_video_tool() -> YouTubeVideoTool:"""Create a YouTube video tool instance."""return YouTubeVideoTool()
tools/multimodal_tools.py+235-1