download-model.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. '''
  2. Downloads models from Hugging Face to models/model-name.
  3. Example:
  4. python download-model.py facebook/opt-1.3b
  5. '''
  6. import requests
  7. from bs4 import BeautifulSoup
  8. import multiprocessing
  9. import tqdm
  10. from sys import argv
  11. from pathlib import Path
  12. def get_file(args):
  13. url = args[0]
  14. output_folder = args[1]
  15. r = requests.get(url, stream=True)
  16. with open(output_folder / Path(url.split('/')[-1]), 'wb') as f:
  17. total_size = int(r.headers.get('content-length', 0))
  18. block_size = 1024
  19. t = tqdm.tqdm(total=total_size, unit='iB', unit_scale=True)
  20. for data in r.iter_content(block_size):
  21. t.update(len(data))
  22. f.write(data)
  23. t.close()
  24. model = Path(argv[1])
  25. url = f'https://huggingface.co/{model}/tree/main'
  26. output_folder = Path("models") / model.name
  27. if not output_folder.exists():
  28. output_folder.mkdir()
  29. # Finding the relevant files to download
  30. page = requests.get(url)
  31. soup = BeautifulSoup(page.content, 'html.parser')
  32. links = soup.find_all('a')
  33. downloads = []
  34. for link in links:
  35. href = link.get('href')[1:]
  36. if href.startswith(f'{model}/resolve/main'):
  37. if href.endswith(('.json', '.txt')) or (href.endswith('.bin') and 'pytorch_model' in href):
  38. downloads.append(f'https://huggingface.co/{href}')
  39. # Downloading the files
  40. print(f"Downloading the model to {output_folder}...")
  41. pool = multiprocessing.Pool(processes=4)
  42. results = pool.map(get_file, [[downloads[i], output_folder] for i in range(len(downloads))])
  43. pool.close()
  44. pool.join()