nananie143 commited on
Commit
daade8b
·
verified ·
1 Parent(s): 3df09b6

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. requirements.txt +2 -3
  2. upload_to_hub.py +141 -52
requirements.txt CHANGED
@@ -1,7 +1,7 @@
1
  fastapi>=0.68.0
2
  uvicorn>=0.15.0
3
  pydantic>=2.0.0
4
- gradio==5.11.0
5
  llama-cpp-python>=0.2.23
6
  huggingface-hub>=0.19.4
7
  numpy>=1.24.0
@@ -15,8 +15,7 @@ aiohttp>=3.8.0
15
  asyncio>=3.4.3
16
  joblib==1.3.2
17
  tqdm>=4.66.0
18
- python-dotenv
19
  httpx>=0.24.0
20
  requests>=2.31.0
21
  urllib3>=2.0.7
22
-
 
1
  fastapi>=0.68.0
2
  uvicorn>=0.15.0
3
  pydantic>=2.0.0
4
+ gradio==4.44.1
5
  llama-cpp-python>=0.2.23
6
  huggingface-hub>=0.19.4
7
  numpy>=1.24.0
 
15
  asyncio>=3.4.3
16
  joblib==1.3.2
17
  tqdm>=4.66.0
18
+ python-dotenv>=0.19.0
19
  httpx>=0.24.0
20
  requests>=2.31.0
21
  urllib3>=2.0.7
 
upload_to_hub.py CHANGED
@@ -1,61 +1,150 @@
1
- from huggingface_hub import HfApi
2
  import os
3
  import sys
 
 
 
 
 
 
 
 
 
 
4
 
5
- def check_token():
6
- """Check if HUGGINGFACE_TOKEN is properly set."""
7
- token = os.environ.get("HUGGINGFACE_TOKEN")
8
- if not token:
9
- print("Error: HUGGINGFACE_TOKEN not found in environment variables.")
10
- print("Please ensure you have:")
11
- print("1. Created a .env file from .env.example")
12
- print("2. Added your Hugging Face token to the .env file")
13
- print("3. The token has write access to Spaces")
14
- sys.exit(1)
15
- return token
16
 
17
- # Check token before proceeding
18
- token = check_token()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # Initialize the Hugging Face API
21
- try:
22
- api = HfApi(token=token)
23
- except Exception as e:
24
- print(f"Error initializing Hugging Face API: {e}")
25
- sys.exit(1)
 
 
 
 
 
 
 
26
 
27
- print("Starting upload to Hugging Face Space...")
 
 
 
 
 
 
 
28
 
29
- # Create a new Space if it doesn't exist
30
- try:
31
- api.create_repo(
32
- repo_id="nananie143/advanced-reasoning",
33
- repo_type="space",
34
- space_sdk="gradio",
35
- private=False
36
- )
37
- except Exception as e:
38
- if "409" in str(e): # HTTP 409 Conflict - repo already exists
39
- print("Space already exists, continuing with upload...")
40
- else:
41
- print(f"Error creating Space: {e}")
42
- print("Please check your token permissions and network connection.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  sys.exit(1)
 
 
 
 
44
 
45
- # Upload the files
46
- try:
47
- api.upload_folder(
48
- folder_path=".",
49
- repo_id="nananie143/advanced-reasoning",
50
- repo_type="space",
51
- ignore_patterns=["*.pyc", "__pycache__", ".git", ".env", "*.gguf"]
52
- )
53
- print("Upload completed successfully!")
54
- except Exception as e:
55
- print(f"Error uploading files: {e}")
56
- print("\nTroubleshooting steps:")
57
- print("1. Check your internet connection")
58
- print("2. Verify your HUGGINGFACE_TOKEN has write access")
59
- print("3. Ensure you're not rate limited")
60
- print("4. Try again in a few minutes")
61
- sys.exit(1)
 
 
1
  import os
2
  import sys
3
+ import time
4
+ import subprocess
5
+ from pathlib import Path
6
+ import logging
7
+ import requests
8
+ from requests.adapters import HTTPAdapter
9
+ from urllib3.util.retry import Retry
10
+ from typing import Optional
11
+ from dotenv import load_dotenv
12
+ from huggingface_hub import HfApi, create_repo
13
 
14
+ # Configure logging
15
+ logging.basicConfig(level=logging.INFO)
16
+ logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
17
 
18
+ def setup_requests_session(
19
+ retries: int = 5,
20
+ backoff_factor: float = 1.0,
21
+ status_forcelist: Optional[list] = None
22
+ ) -> requests.Session:
23
+ """Configure requests session with retries."""
24
+ if status_forcelist is None:
25
+ status_forcelist = [408, 429, 500, 502, 503, 504]
26
+
27
+ session = requests.Session()
28
+ retry = Retry(
29
+ total=retries,
30
+ read=retries,
31
+ connect=retries,
32
+ backoff_factor=backoff_factor,
33
+ status_forcelist=status_forcelist,
34
+ )
35
+ adapter = HTTPAdapter(max_retries=retry)
36
+ session.mount('http://', adapter)
37
+ session.mount('https://', adapter)
38
+ return session
39
 
40
+ def check_network_connectivity(host: str = "8.8.8.8", timeout: int = 5) -> bool:
41
+ """Check if network is accessible."""
42
+ try:
43
+ # Try DNS resolution first
44
+ subprocess.run(
45
+ ["ping", "-c", "1", "-W", str(timeout), host],
46
+ stdout=subprocess.PIPE,
47
+ stderr=subprocess.PIPE,
48
+ check=True
49
+ )
50
+ return True
51
+ except subprocess.CalledProcessError:
52
+ return False
53
 
54
+ def check_huggingface_connectivity(timeout: int = 5) -> bool:
55
+ """Check if Hugging Face is accessible."""
56
+ session = setup_requests_session()
57
+ try:
58
+ response = session.get("https://huggingface.co", timeout=timeout)
59
+ return response.status_code == 200
60
+ except:
61
+ return False
62
 
63
+ def wait_for_network(
64
+ max_attempts: int = 5,
65
+ delay: int = 10,
66
+ hosts: Optional[list] = None
67
+ ) -> bool:
68
+ """Wait for network connectivity."""
69
+ if hosts is None:
70
+ hosts = ["8.8.8.8", "1.1.1.1"]
71
+
72
+ for attempt in range(max_attempts):
73
+ logger.info(f"Checking network connectivity (attempt {attempt + 1}/{max_attempts})")
74
+
75
+ # Try different DNS servers
76
+ for host in hosts:
77
+ if check_network_connectivity(host):
78
+ logger.info(f"Network connectivity established via {host}")
79
+ return True
80
+
81
+ # Check Hugging Face specifically
82
+ if check_huggingface_connectivity():
83
+ logger.info("Hugging Face is accessible")
84
+ return True
85
+
86
+ if attempt < max_attempts - 1:
87
+ logger.warning(f"Network check failed. Waiting {delay} seconds before retry...")
88
+ time.sleep(delay)
89
+
90
+ return False
91
+
92
+ def upload_to_huggingface():
93
+ """Upload the project to Hugging Face."""
94
+ creds_path = None
95
+ try:
96
+ # Load environment variables
97
+ load_dotenv()
98
+ token = os.getenv("HUGGINGFACE_TOKEN")
99
+ if not token:
100
+ raise ValueError("HUGGINGFACE_TOKEN not found in environment variables")
101
+
102
+ # Check network connectivity
103
+ if not wait_for_network():
104
+ raise ConnectionError("Unable to establish network connectivity")
105
+
106
+ # Initialize Hugging Face API
107
+ api = HfApi(token=token)
108
+
109
+ logger.info("Starting upload to Hugging Face Space...")
110
+
111
+ # Space configuration
112
+ space_name = "nananie143/advanced-reasoning"
113
+
114
+ try:
115
+ # Try to create the space (will fail if it exists)
116
+ create_repo(
117
+ repo_id=space_name,
118
+ token=token,
119
+ repo_type="space",
120
+ space_sdk="gradio",
121
+ private=False
122
+ )
123
+ logger.info("Created new Hugging Face Space")
124
+ except Exception as e:
125
+ if "409" in str(e): # HTTP 409 Conflict - repo already exists
126
+ logger.info("Space already exists, continuing with upload...")
127
+ else:
128
+ raise
129
+
130
+ # Upload files
131
+ logger.info("Uploading files to space...")
132
+ api.upload_folder(
133
+ folder_path=".",
134
+ repo_id=space_name,
135
+ repo_type="space",
136
+ ignore_patterns=["*.pyc", "__pycache__", ".git", ".env", "*.gguf"]
137
+ )
138
+
139
+ logger.info("Upload completed successfully!")
140
+
141
+ except Exception as e:
142
+ logger.error(f"Upload failed: {str(e)}")
143
  sys.exit(1)
144
+ finally:
145
+ # Clean up credentials if they exist
146
+ if creds_path and os.path.exists(creds_path):
147
+ os.unlink(creds_path)
148
 
149
+ if __name__ == "__main__":
150
+ upload_to_huggingface()