_config_endpoint.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. # Use a specific check for the Hugging Face source
  16. if os.environ['MINERU_MODEL_SOURCE'] == 'huggingface':
  17. try:
  18. response = requests.head(model_list_url, timeout=TIMEOUT)
  19. # Check for any successful status code (2xx)
  20. if response.ok:
  21. logging.info(f"Successfully connected to Hugging Face. Using 'huggingface' as model source.")
  22. return True
  23. else:
  24. logging.warning(f"Hugging Face endpoint returned a non-200 status code: {response.status_code}")
  25. except requests.exceptions.RequestException as e:
  26. logging.error(f"Failed to connect to Hugging Face at {model_list_url}: {e}")
  27. # If any of the above checks fail, switch to modelscope
  28. logging.info("Falling back to 'modelscope' as model source.")
  29. os.environ['MINERU_MODEL_SOURCE'] = 'modelscope'
  30. elif os.environ['MINERU_MODEL_SOURCE'] == 'modelscope':
  31. try:
  32. response = requests.head(model_list_url, timeout=TIMEOUT)
  33. if response.ok:
  34. logging.info(f"Successfully connected to ModelScope. Using 'modelscope' as model source.")
  35. return True
  36. except requests.exceptions.RequestException as e:
  37. logging.error(f"Failed to connect to ModelScope at {model_list_url}: {e}")
  38. elif os.environ['MINERU_MODEL_SOURCE'] == 'local':
  39. logging.info("Using 'local' as model source.")
  40. return True
  41. else:
  42. logging.error(f"Using custom model source: {os.environ['MINERU_MODEL_SOURCE']}")
  43. return True
  44. return False
  45. if __name__ == '__main__':
  46. print(config_endpoint())