YYama0 commited on
Commit
f25a938
·
verified ·
1 Parent(s): 03b1cc9

Upload 3 files

Browse files
Files changed (4) hide show
  1. .gitattributes +2 -0
  2. download_pmc.py +220 -0
  3. pmc-vid_caption.csv +3 -0
  4. pmc-vid_paper.csv +3 -0
.gitattributes CHANGED
@@ -57,3 +57,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ pmc-vid_caption.csv filter=lfs diff=lfs merge=lfs -text
61
+ pmc-vid_paper.csv filter=lfs diff=lfs merge=lfs -text
download_pmc.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PMC Paper Download Script
4
+ Saves all files regardless of MP4 presence.
5
+
6
+ Usage:
7
+ python download_pmc.py input.csv output_dir [--workers 4]
8
+
9
+ Required CSV columns:
10
+ - File: Path to download file (e.g., oa_package/e6/58/PMC176545.tar.gz)
11
+ """
12
+
13
+ import pandas as pd
14
+ import os
15
+ import subprocess
16
+ import tarfile
17
+ import glob
18
+ import shutil
19
+ import time
20
+ import argparse
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from tqdm import tqdm
23
+
24
+
25
+ def download_and_process_file(file_name, base_url, output_dir):
26
+ """Download file and process if it's a tar.gz"""
27
+ url = os.path.join(base_url, file_name)
28
+ save_path = os.path.join(output_dir, file_name.split("/")[-1])
29
+
30
+ # Download the file
31
+ subprocess.run([
32
+ "wget",
33
+ "-q", # quiet mode
34
+ "--header=User-Agent: PMCImageDownloader/1.0",
35
+ "-O",
36
+ save_path,
37
+ url
38
+ ])
39
+
40
+ # Process if it's a tar.gz file
41
+ if save_path.endswith('.tar.gz'):
42
+ has_mp4 = process_tar_gz(save_path, output_dir)
43
+ if has_mp4:
44
+ print(f"Found MP4 in {save_path} - extracted all files")
45
+ else:
46
+ print(f"No MP4 found in {save_path} - files still extracted")
47
+
48
+ return save_path
49
+
50
+
51
+ def process_tar_gz(file_path, output_dir):
52
+ """
53
+ Process tar.gz file and extract all files.
54
+ Flattens directory structure and places all files at top level.
55
+ Always removes the original tar.gz file.
56
+ """
57
+ try:
58
+ # Create subdirectory with same name as tar.gz (without .tar.gz extension)
59
+ base_name = os.path.basename(file_path).replace('.tar.gz', '')
60
+ extract_dir = os.path.join(output_dir, base_name)
61
+ temp_dir = os.path.join(output_dir, f"temp_{base_name}")
62
+ os.makedirs(extract_dir, exist_ok=True)
63
+ os.makedirs(temp_dir, exist_ok=True)
64
+
65
+ # Extract to temporary directory
66
+ with tarfile.open(file_path, 'r:gz') as tar:
67
+ tar.extractall(path=temp_dir)
68
+
69
+ # Check for MP4 files (for information only)
70
+ mp4_files = glob.glob(os.path.join(temp_dir, "**/*.mp4"), recursive=True)
71
+ has_mp4 = len(mp4_files) > 0
72
+
73
+ # Move all files from nested directories to extract_dir
74
+ for root, dirs, files in os.walk(temp_dir):
75
+ for file in files:
76
+ src_path = os.path.join(root, file)
77
+ dst_path = os.path.join(extract_dir, file)
78
+ # Add number suffix if filename already exists
79
+ if os.path.exists(dst_path):
80
+ base, ext = os.path.splitext(file)
81
+ counter = 1
82
+ while os.path.exists(dst_path):
83
+ dst_path = os.path.join(extract_dir, f"{base}_{counter}{ext}")
84
+ counter += 1
85
+ shutil.move(src_path, dst_path)
86
+
87
+ # Cleanup
88
+ os.remove(file_path) # Remove original tar.gz file
89
+ shutil.rmtree(temp_dir) # Remove temporary directory
90
+
91
+ return has_mp4
92
+
93
+ except Exception as e:
94
+ print(f"Error processing {file_path}: {e}")
95
+ # Cleanup on error
96
+ if os.path.exists(file_path):
97
+ os.remove(file_path)
98
+ if os.path.exists(temp_dir):
99
+ shutil.rmtree(temp_dir)
100
+ return False
101
+
102
+
103
+ def parallel_download(file_list, base_url, output_dir, max_workers=4):
104
+ """Execute parallel downloads"""
105
+ os.makedirs(output_dir, exist_ok=True)
106
+ start_time = time.time()
107
+
108
+ # Check for File column
109
+ if 'File' not in file_list.columns:
110
+ raise ValueError("CSV must contain 'File' column")
111
+
112
+ total_files = len(file_list['File'])
113
+ print(f"Starting download of {total_files} files...")
114
+
115
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
116
+ futures = []
117
+ with tqdm(total=total_files) as progress_bar:
118
+ # Submit download and process tasks
119
+ for file_name in file_list['File']:
120
+ futures.append(
121
+ executor.submit(download_and_process_file, file_name, base_url, output_dir)
122
+ )
123
+
124
+ # Update progress
125
+ completed = 0
126
+ for future in as_completed(futures):
127
+ completed += 1
128
+ progress_bar.update(1)
129
+ elapsed_time = time.time() - start_time
130
+ remaining_files = total_files - completed
131
+
132
+ # Calculate and display estimated remaining time
133
+ if completed > 0:
134
+ time_per_file = elapsed_time / completed
135
+ remaining_time = time_per_file * remaining_files
136
+ hours = int(remaining_time // 3600)
137
+ minutes = int((remaining_time % 3600) // 60)
138
+ seconds = int(remaining_time % 60)
139
+ progress_bar.set_description(
140
+ f"Remaining: {hours:02d}:{minutes:02d}:{seconds:02d}"
141
+ )
142
+
143
+ total_time = time.time() - start_time
144
+ print(f"\nCompleted download of {total_files} files in {total_time:.2f} seconds")
145
+
146
+
147
+ def main():
148
+ """Main function"""
149
+ parser = argparse.ArgumentParser(
150
+ description='Download PMC papers from NCBI FTP server'
151
+ )
152
+ parser.add_argument(
153
+ 'csv_file',
154
+ help='Input CSV file containing File column with paths to download'
155
+ )
156
+ parser.add_argument(
157
+ 'output_dir',
158
+ help='Output directory for downloaded and extracted files'
159
+ )
160
+ parser.add_argument(
161
+ '--workers',
162
+ type=int,
163
+ default=4,
164
+ help='Number of parallel download workers (default: 4)'
165
+ )
166
+ parser.add_argument(
167
+ '--base-url',
168
+ default='https://ftp.ncbi.nlm.nih.gov/pub/pmc',
169
+ help='Base URL for PMC FTP server (default: https://ftp.ncbi.nlm.nih.gov/pub/pmc)'
170
+ )
171
+
172
+ args = parser.parse_args()
173
+
174
+ # Read CSV file
175
+ try:
176
+ file_list = pd.read_csv(args.csv_file)
177
+ except FileNotFoundError:
178
+ print(f"Error: CSV file '{args.csv_file}' not found")
179
+ return 1
180
+ except Exception as e:
181
+ print(f"Error reading CSV file: {e}")
182
+ return 1
183
+
184
+ # Check for File column
185
+ if 'File' not in file_list.columns:
186
+ print("Error: CSV must contain 'File' column")
187
+ print(f"Available columns: {', '.join(file_list.columns)}")
188
+ return 1
189
+
190
+ # Remove NaN values
191
+ file_list = file_list.dropna(subset=['File'])
192
+
193
+ if len(file_list) == 0:
194
+ print("Error: No valid files to download in CSV")
195
+ return 1
196
+
197
+ print(f"Found {len(file_list)} files to download")
198
+ print(f"Output directory: {args.output_dir}")
199
+ print(f"Using {args.workers} parallel workers")
200
+
201
+ # Execute download
202
+ try:
203
+ parallel_download(
204
+ file_list=file_list,
205
+ base_url=args.base_url,
206
+ output_dir=args.output_dir,
207
+ max_workers=args.workers
208
+ )
209
+ except KeyboardInterrupt:
210
+ print("\nDownload interrupted by user")
211
+ return 1
212
+ except Exception as e:
213
+ print(f"Error during download: {e}")
214
+ return 1
215
+
216
+ return 0
217
+
218
+
219
+ if __name__ == "__main__":
220
+ exit(main())
pmc-vid_caption.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49d0c5429738d87d7d2927b3666e8c30c3a95596456001b45ea9e0a28134d352
3
+ size 23488012
pmc-vid_paper.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd018fd330339d3b140374cb28795016d052c463d3e8307859ca75fce4c5c25f
3
+ size 57399963