Skip to content

Instantly share code, notes, and snippets.

@phoenixthrush
Last active August 13, 2025 01:59
Show Gist options
  • Select an option

  • Save phoenixthrush/627473e66dc2bf27117fc6a59dd8f0c8 to your computer and use it in GitHub Desktop.

Select an option

Save phoenixthrush/627473e66dc2bf27117fc6a59dd8f0c8 to your computer and use it in GitHub Desktop.
Python mass downloader for baka.ms (images only) #baka.ms #Python #Scraper
"""
MIT License
Copyright (c) 2025 phoenixthrush
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
import mimetypes
import pathlib
import requests
def fetch_gallery_links(gallery_url):
response = requests.get(gallery_url)
galleries = []
for href, name in re.findall(r'<a href="([^"]+)">([^<]+)</a>', response.text):
if href == name and name != ".." and not name.endswith('.html'):
galleries.append((name, f"https://baka.ms/galleries/{name}"))
return galleries
def fetch_subgallery_links(gallery_url):
response = requests.get(gallery_url)
subgalleries = []
for href, name in re.findall(r'<a href="([^"]+\.html)">([^<]+)</a>', response.text):
subgalleries.append((name, f"{gallery_url}/{href}"))
return subgalleries
def fetch_subfolders(gallery_url):
response = requests.get(gallery_url)
subfolders = []
for href, name in re.findall(r'<a href="([^"]+)">([^<]+)</a>', response.text):
if href == name and name != ".." and not name.endswith('.html') and '.' not in name:
subfolders.append((name, f"{gallery_url}/{name}"))
return subfolders
def process_gallery_recursive(base_path, gallery_url, path_components):
subgalleries = fetch_subgallery_links(gallery_url)
for subgallery_name, subgallery_url in subgalleries:
urls = fetch_photoservice_urls(subgallery_url)
if urls:
full_name = "_".join(path_components + [subgallery_name[:-5]])
links_file = pathlib.Path("links") / f"{full_name}.txt"
if not links_file.exists():
links_file.write_text('\n'.join(urls), encoding='utf-8')
download_images(full_name, urls)
subfolders = fetch_subfolders(gallery_url)
for subfolder_name, subfolder_url in subfolders:
print(
f" Exploring subfolder: {'/'.join(path_components + [subfolder_name])}")
process_gallery_recursive(
base_path, subfolder_url, path_components + [subfolder_name])
def fetch_photoservice_urls(gallery_url):
# URL construction: data-idimg="abc123" -> token[::-1] = "321cba" -> https://photos.baka.ms/photoservice/uwu/pull/321cba?abc123
response = requests.get(gallery_url)
return [f"https://photos.baka.ms/photoservice/uwu/pull/{token[::-1]}?{token}"
for token in re.findall(r'data-idimg="([^"]+)"', response.text)]
def download_images(gallery_name, urls):
path_parts = gallery_name.split('_')
gallery_dir = pathlib.Path("images")
for part in path_parts:
gallery_dir = gallery_dir / part
gallery_dir.mkdir(parents=True, exist_ok=True)
downloaded = 0
skipped = 0
for i, url in enumerate(urls, 1):
try:
# Check if file already exists first
response = requests.get(url)
if response.status_code == 200:
content_type = response.headers.get(
'content-type', '').split(';')[0].strip()
ext = mimetypes.guess_extension(content_type) or '.jpg'
image_path = gallery_dir / f"{i:03d}{ext}"
if image_path.exists():
print(
f"\tSkipping {gallery_name}/{i:03d}{ext} (already exists)")
skipped += 1
continue
print(f"\tDownloading {gallery_name}/{i:03d}{ext}...")
image_path.write_bytes(response.content)
downloaded += 1
except:
pass
print(f" {gallery_name}: {downloaded} downloaded, {skipped} skipped")
def main():
pathlib.Path("links").mkdir(exist_ok=True)
pathlib.Path("images").mkdir(exist_ok=True)
galleries = fetch_gallery_links("https://baka.ms/galleries/")
# already downloaded :)
galleries = [(name, url)
for name, url in galleries if name != "belle_delphine"]
print(f"Found {len(galleries)} galleries to process")
for gallery_idx, (gallery_name, gallery_url) in enumerate(galleries, 1):
print(f"[{gallery_idx}/{len(galleries)}] Processing {gallery_name}...")
process_gallery_recursive(gallery_name, gallery_url, [gallery_name])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment