Spaces:
Sleeping
Sleeping
Download tools.py from olaf-bu/Final_Assignment: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/olaf-bu/Final_Assignment/resolve/main/tools.py
- Command line
-
hf download hf://spaces/olaf-bu/Final_Assignment/tools.py
-
curl -L -o tools.py https://huggingface.co/spaces/olaf-bu/Final_Assignment/resolve/main/tools.py
10.3 kB
| import base64 | |
| import logging | |
| from typing import List | |
| import os | |
| import markdownify | |
| import requests | |
| from smolagents import Tool, PythonInterpreterTool, VisitWebpageTool, WikipediaSearchTool | |
| from duckduckgo_search import DDGS | |
| from openai import OpenAI | |
| import whisper | |
| from youtube_transcript_api import YouTubeTranscriptApi | |
| logger = logging.getLogger(__name__) | |
| class ReadFileTool(Tool): | |
| """ | |
| Tool to read a file and return its content. | |
| Args: | |
| file_path (str): Path to the file to read. | |
| Returns: | |
| str: Content of the file or error message. | |
| """ | |
| name = 'read_file' | |
| description = 'Reads a file and returns its content' | |
| inputs = {'file_path': {'type': 'string', 'description': 'Path to the file to read'}, | |
| } | |
| output_type = 'string' | |
| def __init__(self): | |
| """Nothing to do for this class here, but kick the constructor of the base class.""" | |
| super().__init__() | |
| def forward(self, file_path: str) -> str: | |
| try: | |
| with open(file_path, 'r') as file: | |
| return file.read() | |
| except Exception as e: | |
| logger.error('error while reading attempt of %s: %s', file_path, e) | |
| return f'Error reading file: {str(e)}' | |
| class OpenAISpeechToTextTool(Tool): | |
| """ | |
| Tool to convert speech to text using OpenAI's Whisper model. | |
| Args: | |
| audio_path (str): Path to the audio file. | |
| Returns: | |
| str: Transcribed text from the audio file. | |
| """ | |
| name = 'transcribe_audio' | |
| description = 'Transcribes audio to text and returns the text' | |
| inputs = {'audio_path': {'type': 'string', 'description': 'Path to the audio file'}, | |
| } | |
| output_type = 'string' | |
| def __init__(self): | |
| """Nothing to do for this class here, but kick the constructor of the base class.""" | |
| super().__init__() | |
| def forward(self, audio_path: str) -> str: | |
| try: | |
| model = whisper.load_model('small') | |
| if not os.path.exists(audio_path): | |
| return f'Error: Audio file not found at {audio_path}' | |
| result = model.transcribe(audio_path) | |
| return result['text'] | |
| except Exception as e: | |
| return f'Error transcribing audio: {str(e)}' | |
| class YouTubeTranscriptionTool(Tool): | |
| """ | |
| Tool to fetch the transcript of a YouTube video given its URL. | |
| Args: | |
| video_url (str): YouTube video URL. | |
| Returns: | |
| str: Transcript of the video as a single string. | |
| """ | |
| name = 'youtube_transcription' | |
| description = 'Fetches the transcript of a YouTube video given its URL' | |
| inputs = {'video_url': {'type': 'string', | |
| 'description': 'YouTube video URL'}, | |
| } | |
| output_type = 'string' | |
| def __init__(self): | |
| """Nothing to do for this class here, but kick the constructor of the base class.""" | |
| super().__init__() | |
| def forward(self, video_url: str) -> str: | |
| video_id = video_url.strip().split('v=')[-1] | |
| transcript = YouTubeTranscriptApi.get_transcript(video_id) | |
| return ' '.join([entry['text'] for entry in transcript]) | |
| class DescribeImageTool(Tool): | |
| """ | |
| Tool to analyze and describe any image using GPT-4 Vision API. | |
| Args: | |
| image_path (str): Path to the image file. | |
| description_type (str): Type of description to generate. Options: | |
| - "general": General description of the image | |
| - "detailed": Detailed analysis of the image | |
| - "chess": Analysis of a chess position | |
| - "text": Extract and describe text from the image | |
| - "custom": Custom description based on user prompt | |
| Returns: | |
| str: Description of the image based on the requested type. | |
| """ | |
| name = 'describe_image' | |
| description = 'Analyzes and describes images using GPT-4 Vision API' | |
| inputs = {'image_path': {'type': 'string', 'description': 'Path to the image file'}, | |
| 'description_type': {'type': 'string', | |
| 'description': 'Type of description to generate (general, detailed, chess, text, custom)', | |
| 'nullable': True, | |
| }, | |
| 'custom_prompt': {'type': 'string', | |
| 'description': 'Custom prompt for description (only used when description_type is "custom")', | |
| 'nullable': True, | |
| }, | |
| } | |
| output_type = 'string' | |
| _client = None # OpenAI (compatible) client. Instantiated on first use | |
| def __init__(self): | |
| """ensure, that the super class is instantiated properly and creat an OpenAI client (if not already done).""" | |
| super().__init__() | |
| if not self.__class__._client: | |
| openai_api_key = os.environ.get('REAL_OPENAI_API_KEY', # just in case we run with other openAI compatibel providers | |
| os.environ.get('OPENAI_API_KEY') | |
| ) | |
| self.__class__._client = OpenAI(api_key=openai_api_key) | |
| def encode_image(self, image_path: str) -> str: | |
| """Encode image to base64 string.""" | |
| with open(image_path, 'rb') as image_file: | |
| return base64.b64encode(image_file.read()).decode('utf-8') | |
| def get_prompt(self, description_type: str, custom_prompt: str = None) -> str: | |
| """Get appropriate prompt based on description type.""" | |
| prompts = {'general': 'Provide a general description of this image. Focus on the main subjects, colors, and overall scene.', | |
| 'detailed': """Analyze this image in detail. Include: | |
| 1. Main subjects and their relationships | |
| 2. Colors, lighting, and composition | |
| 3. Any text or symbols present | |
| 4. Context or possible meaning | |
| 5. Notable details or interesting elements""", | |
| 'chess': """Analyze this chess position and provide a detailed description including: | |
| 1. List of pieces on the board for both white and black | |
| 2. Whose turn it is to move | |
| 3. Basic evaluation of the position | |
| 4. Any immediate tactical opportunities or threats | |
| 5. Suggested next moves with brief explanations""", | |
| 'text': 'Extract and describe any text present in this image. If there are multiple pieces of text, organize them clearly.', | |
| } | |
| return (custom_prompt | |
| if description_type == 'custom' | |
| else prompts.get(description_type, prompts['general']) | |
| ) | |
| def forward(self, image_path: str, description_type: str = 'general', custom_prompt: str = None | |
| ) -> str: | |
| try: | |
| if not os.path.exists(image_path): | |
| return f'Error: Image file not found at {image_path}' | |
| # Encode the image | |
| base64_image = self.encode_image(image_path) | |
| # Get appropriate prompt | |
| prompt = self.get_prompt(description_type, custom_prompt) | |
| # Make the API call | |
| response = self.__class__._client.chat.completions.create( | |
| model='gpt-4.1', | |
| messages=[{'role': 'user', | |
| 'content': [{'type': 'text', | |
| 'text': prompt}, | |
| {'type': 'image_url', | |
| 'image_url': {'url': f'data:image/jpeg;base64,{base64_image}' | |
| }, | |
| }, ], | |
| }], | |
| max_tokens=1000, | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| return f'Error analyzing image: {str(e)}' | |
| class ReliableDuckDuckGoSearchTool(Tool): | |
| """Reliable search for web content. | |
| especially try to avoid the ratelimit problems of the lite duckduckgosearch. | |
| Args: | |
| query (str): query to search with | |
| Returns: | |
| str: the query results | |
| """ | |
| name = 'duckduckgo_search' | |
| description = 'Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results.' | |
| inputs = {'query': {'type': 'string', | |
| 'description': 'The search query to perform.'}, | |
| } | |
| output_type = 'string' | |
| def __init__(self, num_results=3): | |
| super().__init__() | |
| self.num_results = num_results | |
| def forward(self, query: str) -> str: | |
| with DDGS() as ddgs: | |
| results = ddgs.text(query, max_results=self.num_results) | |
| if len(results) == 0: | |
| raise Exception("No results found! Try a less restrictive/shorter query.") | |
| postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" | |
| for result in results] | |
| return "## Search Results\n\n" + "\n\n".join(postprocessed_results) | |
| def get_tools() -> List[Tool]: | |
| """ | |
| Returns a list of available tools for the agent. | |
| Returns: | |
| List[Tool]: List of initialized tool instances. | |
| """ | |
| authorized_imports = ['requests', | |
| 'markdownify', | |
| 'wikipedia-api', | |
| ] | |
| try: | |
| tools = [ReliableDuckDuckGoSearchTool(), | |
| PythonInterpreterTool(authorized_imports=authorized_imports), | |
| WikipediaSearchTool(), | |
| VisitWebpageTool(), | |
| OpenAISpeechToTextTool(), | |
| YouTubeTranscriptionTool(), | |
| ReadFileTool(), | |
| DescribeImageTool() | |
| ] | |
| except Exception as e: | |
| logger.error('error while instantiating the tools: %s', e) | |
| return f'error instantiating the tools {str(e)}' | |
| return tools | |