lyimo commited on
Commit
82c9586
·
verified ·
1 Parent(s): 8d2437f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -47
app.py CHANGED
@@ -1,66 +1,66 @@
1
  import os
2
  import requests
3
  import gradio as gr
4
- import time
 
5
 
6
- def download_sam_model(progress=gr.Progress()):
7
  """
8
- Download the SAM model weights with visible progress indicator
9
  """
10
- url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
11
-
12
  try:
13
- # Get the repository root directory
14
- root_dir = os.path.dirname(os.path.abspath(__file__))
15
- filename = url.split('/')[-1]
16
- save_path = os.path.join(root_dir, filename)
17
 
18
- # Check if file already exists
19
- if os.path.exists(save_path):
20
- return "Model file already exists in the repository root"
21
 
22
- # Get file size
23
- response = requests.head(url)
24
- total_size = int(response.headers.get('content-length', 0))
25
-
26
- # Download with progress tracking
27
- response = requests.get(url, stream=True)
28
- progress(0, desc="Starting download...")
29
-
30
- downloaded_size = 0
31
- chunk_size = 1024 * 1024 # 1MB chunks
32
-
33
- with open(save_path, 'wb') as file:
34
- for data in response.iter_content(chunk_size=chunk_size):
35
- file.write(data)
36
- downloaded_size += len(data)
37
- # Update progress bar
38
- progress(downloaded_size/total_size,
39
- desc=f"Downloading... {downloaded_size/(1024*1024):.1f}MB / {total_size/(1024*1024):.1f}MB")
40
-
41
- if downloaded_size != total_size:
42
- if os.path.exists(save_path):
43
- os.remove(save_path)
44
- return "Error: Download incomplete. Please try again."
 
 
 
 
 
45
 
46
- return f"✅ Model successfully downloaded! Saved as {filename}"
47
-
48
  except Exception as e:
49
- if os.path.exists(save_path):
50
- os.remove(save_path)
51
- return f"❌ Error downloading file: {str(e)}"
52
 
53
- # Create a Gradio interface
54
  with gr.Blocks() as demo:
55
- gr.Markdown("# Download SAM Model")
56
- gr.Markdown("This will download the Segment Anything Model (SAM) weights (~2.4GB)")
57
 
58
  with gr.Row():
59
- download_button = gr.Button("📥 Download Model", variant="primary")
60
  status_text = gr.Textbox(label="Status", interactive=False)
61
 
62
  download_button.click(
63
- fn=download_sam_model,
64
  outputs=status_text,
65
  show_progress=True,
66
  )
@@ -68,8 +68,9 @@ with gr.Blocks() as demo:
68
  gr.Markdown("""
69
  ### Notes:
70
  - Download size is approximately 2.4GB
71
- - The model will be saved in the Space's root directory
72
- - Please wait for the download to complete
 
73
  """)
74
 
75
  if __name__ == "__main__":
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ from huggingface_hub import HfApi
5
+ import tempfile
6
 
7
+ def download_and_push_model(progress=gr.Progress()):
8
  """
9
+ Download SAM model and push it to Hugging Face Space
10
  """
 
 
11
  try:
12
+ # Initialize Hugging Face API
13
+ api = HfApi()
14
+ space_id = "lyimo/downloadmodel"
15
+ model_url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
16
 
17
+ # Create a temporary directory for downloading
18
+ with tempfile.TemporaryDirectory() as temp_dir:
19
+ progress(0.1, desc="Started download process...")
20
 
21
+ # Download file
22
+ local_path = os.path.join(temp_dir, "sam_vit_h_4b8939.pth")
23
+ response = requests.get(model_url, stream=True)
24
+ total_size = int(response.headers.get('content-length', 0))
25
+
26
+ progress(0.2, desc="Downloading model...")
27
+ downloaded_size = 0
28
+
29
+ with open(local_path, 'wb') as file:
30
+ for chunk in response.iter_content(chunk_size=1024*1024):
31
+ if chunk:
32
+ file.write(chunk)
33
+ downloaded_size += len(chunk)
34
+ progress(0.2 + 0.6 * (downloaded_size/total_size),
35
+ desc=f"Downloading... {downloaded_size/(1024*1024):.1f}MB / {total_size/(1024*1024):.1f}MB")
36
+
37
+ progress(0.8, desc="Upload to Hugging Face Space...")
38
+
39
+ # Upload to Hugging Face
40
+ api.upload_file(
41
+ path_or_fileobj=local_path,
42
+ path_in_repo="sam_vit_h_4b8939.pth",
43
+ repo_id=space_id,
44
+ repo_type="space"
45
+ )
46
+
47
+ progress(1.0, desc="Complete!")
48
+ return "✅ Model successfully downloaded and pushed to your Space!"
49
 
 
 
50
  except Exception as e:
51
+ return f"❌ Error: {str(e)}"
 
 
52
 
53
+ # Create Gradio interface
54
  with gr.Blocks() as demo:
55
+ gr.Markdown("# Download SAM Model to Space")
56
+ gr.Markdown("This will download the Segment Anything Model (SAM) weights (~2.4GB) and push to this Space")
57
 
58
  with gr.Row():
59
+ download_button = gr.Button("📥 Download & Push Model", variant="primary")
60
  status_text = gr.Textbox(label="Status", interactive=False)
61
 
62
  download_button.click(
63
+ fn=download_and_push_model,
64
  outputs=status_text,
65
  show_progress=True,
66
  )
 
68
  gr.Markdown("""
69
  ### Notes:
70
  - Download size is approximately 2.4GB
71
+ - The model will be pushed to the Space repository
72
+ - Please wait for both download and upload to complete
73
+ - You can check the files tab after completion
74
  """)
75
 
76
  if __name__ == "__main__":