<s>[INST] Here's a function `profile_selector` that randomly selects a profile picture from a user's profiles and saves it to a new image.

```python
def profile_selector(user_id):
    profiles = []
    profiles_folder = f"profiles/{user_id}"
    for filename in os.listdir(profiles_folder):
        filepath = os.path.join(profiles_folder, filename)
        if os.path.isfile(filepath):
            profiles.append(filepath)

    if not profiles:
        print(f"No profiles found for user {user_id}")
        return

    selected_profile = random.choice(profiles)
    new_image = Image.open(selected_profile)

    new_filename = f"profiles/{user_id}/selected_profile_{user_id}.png"
    while os.path.exists(new_filename):
        new_filename = f"profiles/{user_id}/selected_profile_{user_id}_{random.randint(100000, 999999)}.png"

    new_image.save(new_filename)
    print(f"Saved new profile picture to {new_filename}")
```

However, I'd like to optimize this function to avoid issues with duplicate filenames. 

How would you refactor this to ensure the function avoids duplicate filenames?[/INST]