_config_endpoint.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import requests
  2. import os
  3. import logging
  4. logging.basicConfig(level=logging.INFO)
  5. # test connection to huggingface
  6. TIMEOUT = 3
  7. def config_endpoint():
  8. """
  9. Checks for connectivity to Hugging Face and sets the model source accordingly.
  10. If the Hugging Face endpoint is reachable, it sets MINERU_MODEL_SOURCE to 'huggingface'.
  11. Otherwise, it falls back to 'modelscope'.
  12. """
  13. os.environ.setdefault('MINERU_MODEL_SOURCE', 'huggingface')
  14. model_list_url = f"https://huggingface.co/models"
  15. modelscope_url = f"https://modelscope.cn/models"
  16. # Use a specific check for the Hugging Face source
  17. if os.environ['MINERU_MODEL_SOURCE'] == 'huggingface':
  18. try:
  19. response = requests.head(model_list_url, timeout=TIMEOUT)
  20. # Check for any successful status code (2xx)
  21. if response.ok:
  22. logging.info(f"Successfully connected to Hugging Face. Using 'huggingface' as model source.")
  23. return True
  24. else:
  25. logging.warning(f"Hugging Face endpoint returned a non-200 status code: {response.status_code}")
  26. except requests.exceptions.RequestException as e:
  27. logging.error(f"Failed to connect to Hugging Face at {model_list_url}: {e}")
  28. # If any of the above checks fail, switch to modelscope
  29. logging.info("Falling back to 'modelscope' as model source.")
  30. os.environ['MINERU_MODEL_SOURCE'] = 'modelscope'
  31. elif os.environ['MINERU_MODEL_SOURCE'] == 'modelscope':
  32. try:
  33. response = requests.head(modelscope_url, timeout=TIMEOUT)
  34. if response.ok:
  35. logging.info(f"Successfully connected to ModelScope. Using 'modelscope' as model source.")
  36. return True
  37. except requests.exceptions.RequestException as e:
  38. logging.error(f"Failed to connect to ModelScope at {modelscope_url}: {e}")
  39. elif os.environ['MINERU_MODEL_SOURCE'] == 'local':
  40. logging.info("Using 'local' as model source.")
  41. return True
  42. else:
  43. logging.error(f"Using custom model source: {os.environ['MINERU_MODEL_SOURCE']}")
  44. return True
  45. return False
  46. if __name__ == '__main__':
  47. print(config_endpoint())