Skip to content

Conversation

@sandeepsalwan1
Copy link

@sandeepsalwan1 sandeepsalwan1 commented May 8, 2025

This script automates downloading 3 MP3 sound effects from soundgator.com for any search term you provide to a folder.

mainSoundDemo

Full script

#!/usr/bin/env python3
"""
Sound Downloader
Script that navigates to soundgator.com, searches for firecracker sounds,
and downloads 3 of them to a local directory.
"""

import asyncio
import os
import time
import shutil
from pathlib import Path
from typing import List, Optional
from pydantic import BaseModel
from browser_use import Agent, Controller, Browser, BrowserConfig
from langchain_openai import ChatOpenAI

class SoundFile(BaseModel):
    title: str
    url: str
    downloaded: bool = False
    local_path: Optional[str] = None

class SoundData(BaseModel):
    sound_files: List[SoundFile]

controller = Controller(output_model=SoundData)

async def main():
    # Set absolute download path
    download_path = Path("/Users/sandeep/projects/browser-use-1/firecracker_sounds")
    
    # Make sure directory exists and is empty
    if download_path.exists():
        shutil.rmtree(download_path)
    download_path.mkdir(exist_ok=True, parents=True)
    
    print(f"Navigating to soundgator.com to download firecracker sounds...")
    print(f"Files will be saved to: {download_path}")
    search_query = "firecracker"

    browser_config = BrowserConfig(
        headless=False,  # Show browser window
    )
    
    # Initialize browser with our configs
    browser = Browser(config=browser_config)
    
    # Initialize the agent with a task to find and download firecracker sounds
    task = f"""
    Go to https://soundgator.com/
    
    Search for "{search_query}" sounds.
    
    Find 3 different "{search_query}" sounds and download them.
    For each sound:
    1. Click on the sound title to go to its detail page
    2. Click the "Free Download" button 
    3. On the download page, download the MP3 version (not WAV)
    4. After each download completes, wait 5 seconds, then go back to search results to find the next sound
    5. Record the sound title and download status
    
    IMPORTANT: After clicking a download button, wait at least 5 seconds for the download to start.
    
    The files will be downloaded to your default downloads folder. After downloading,
    move them to this directory: {download_path}
    
    Format the data according to the SoundData model with a list of sound files.
    """
    
    # Create and run the agent
    agent = Agent(
        task=task,
        llm=ChatOpenAI(model="gpt-4o"),
        controller=controller,
        browser=browser,
    )
    
    # Run the agent to extract data with increased max_steps
    try:
        history = await agent.run(max_steps=20)
        
        # Get the final result from the agent
        result = history.final_result()
        
        if not result:
            print("No sounds were downloaded. Exiting.")
            return
        
        # Parse the result using our Pydantic model
        try:
            sound_data = SoundData.model_validate_json(result)
            
            # Print summary of downloaded sounds
            print("\n✓ Downloaded Firecracker Sounds:")
            for sound in sound_data.sound_files:
                status = "✓ Downloaded" if sound.downloaded else "✗ Failed to download"
                print(f"{status}: {sound.title}")
                if sound.local_path:
                    print(f"   Saved to: {sound.local_path}")
            
            print(f"\nChecking for files in {download_path}:")
            files = list(download_path.glob("*"))
            if files:
                for file in files:
                    print(f"Found file: {file.name} ({file.stat().st_size / 1024:.1f} KB)")
            else:
                print("No files found in the target directory.")
            
            default_downloads = Path.home() / "Downloads"
            print(f"\nChecking default Downloads folder: {default_downloads}")
            
            if default_downloads.exists():
                recent_files = sorted(default_downloads.glob("*"), 
                                    key=lambda x: x.stat().st_mtime, reverse=True)[:5]
                if recent_files:
                    print("Recent files in Downloads folder:")
                    for file in recent_files:
                        print(f"  {file.name} (Modified: {time.ctime(file.stat().st_mtime)})")
                    
                    print("\nTo move files to the target directory, run:")
                    print(f"mv ~/Downloads/*firecracker* {download_path}/")
            
        except Exception as e:
            print(f"Error processing results: {e}")
            print("Raw result:", result)
    except KeyboardInterrupt:
        print("\nOperation cancelled by user.")
    except Exception as e:
        print(f"Error running agent: {e}")
    finally:
        await browser.close()

if __name__ == "__main__":
    asyncio.run(main())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant