-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_download_box_files.py
More file actions
260 lines (213 loc) Β· 8.79 KB
/
Copy pathsearch_download_box_files.py
File metadata and controls
260 lines (213 loc) Β· 8.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import os
import re
import webbrowser
import pandas as pd
from boxsdk import OAuth2, Client
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import threading
import time
#################################################################################
# RUN LOCAL SERVER FOR 2 FACTOR AUTHENTICATION
#################################################################################
class OAuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
# suppress server logs
self.log_message = lambda format, *args: None
query = urlparse(self.path).query
params = parse_qs(query)
self.server.auth_code = params.get('code', [None])[0]
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Authentication successful. You can close this window.')
# signal the server to shutdown
self.server.shutdown_requested = True
#################################################################################
# FETCH AUTHENTICATION CODE
#################################################################################
def get_auth_code(client_id, redirect_uri, port=8080):
auth_url = (
f"https://account.box.com/api/oauth2/authorize?"
f"response_type=code&client_id={client_id}&redirect_uri={redirect_uri}"
f"&scope=root_readwrite"
)
# update redirect_uri to include the port
redirect_with_port = f"{redirect_uri}:{port}"
auth_url = auth_url.replace(redirect_uri, redirect_with_port)
print(f"Opening browser to authorize: {auth_url}")
webbrowser.open(auth_url)
server_address = ('localhost', port)
server = HTTPServer(server_address, OAuthHandler)
server.auth_code = None
server.shutdown_requested = False
# run server in interruptable thread
def server_thread():
while not server.shutdown_requested:
server.handle_request()
thread = threading.Thread(target=server_thread)
thread.daemon = True
thread.start()
# wait for auth code with timeout
timeout = 300 # 5 mins timeout
start_time = time.time()
while server.auth_code is None:
if time.time() - start_time > timeout:
print("Timeout waiting for authentication")
return None
time.sleep(0.5)
# give the server time to send the response
time.sleep(1)
return server.auth_code
#################################################################################
# AUTHENTICATING ON BROWSER
# using info from box developer interface
#################################################################################
CLIENT_ID = os.environ.get("BOX_CLIENT_ID")
CLIENT_SECRET = os.environ.get("BOX_CLIENT_SECRET")
# hardcoded values as fallback for environment variables
if not CLIENT_ID:
CLIENT_ID = "vdxa3xbitg99n9oi6fwjgdnz7d152omd"
if not CLIENT_SECRET:
CLIENT_SECRET = "5W12sHkJZP2mKtkBebLk4h2HlHlMsvsR"
REDIRECT_URI = "http://localhost"
PORT = 8080
print("π Opening browser for Box login...")
auth_code = get_auth_code(CLIENT_ID, REDIRECT_URI, PORT)
if not auth_code:
print("β Failed to get authentication code. Exiting.")
exit(1)
oauth = OAuth2(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
)
try:
access_token, refresh_token = oauth.authenticate(auth_code)
client = Client(oauth)
print("β
Authenticated with Box!")
except Exception as e:
print(f"β Authentication failed: {e}")
exit(1)
#################################################################################
# LOADING SPREADSHEET
# contains multispeaker recordings identified with identify_multiparty_recs.py
#################################################################################
try:
df = pd.read_excel("multispeaker_output.xlsx")
print(f"π Loaded spreadsheet with {len(df)} rows")
except Exception as e:
print(f"β Failed to load spreadsheet: {e}")
exit(1)
#################################################################################
# SUBFOLDER LOGIC
# if file has been supercoded, want .eaf file from completed/XX/checks
# else, completed/XX where XX is initials of coder/supercoder
# super coder is under "Super coder" col, annotator is under "Annotator" col
#################################################################################
def determine_subfolder(row):
super_coder = row.get("Super coder", "")
annotator = row.get("Annotator", "")
if pd.notna(super_coder) and re.search(r'[A-Za-z]', str(super_coder)):
return f"{str(super_coder).strip()}/checks"
elif pd.notna(annotator):
return str(annotator).strip()
else:
return None
#################################################################################
# FIND BASE BOX DIRECTORY
#################################################################################
def find_base_directory(client):
path_parts = ["ChatterLab", "Member work directories", "CAREER transcription team", "annotator_files", "completed"]
current = client.folder(folder_id='0') # root
print("π Finding base directory...")
for part in path_parts:
found = False
try:
items = list(current.get_items(limit=1000))
for item in items:
if item.type == 'folder':
item_info = item.get()
if item_info.name == part:
current = item
print(f" β Found: {part}")
found = True
break
if not found:
print(f"β Could not find '{part}' subfolder. Please check the path.")
return None
except Exception as e:
print(f"β Error navigating to base directory: {str(e)}")
return None
print(f"β
Found base directory: {path_parts[-1]}")
return current
#################################################################################
# TRAVERSE GIVEN DIRECTORY TO LOCATE FILE
#################################################################################
def get_folder_by_path(path_parts, base_folder):
current = base_folder
for part in path_parts:
if not part: # skip empty parts
continue
found = False
try:
items = list(current.get_items(limit=1000))
for item in items:
if item.type == 'folder':
item_info = item.get()
if item_info.name == part:
current = item
found = True
break
if not found:
print(f"β Subfolder '{part}' not found in '{current.get().name}'")
return None
except Exception as e:
print(f"β Error accessing folder: {str(e)}")
return None
return current
# download loop
download_dir = "downloaded_eafs"
os.makedirs(download_dir, exist_ok=True)
print(f"π Files will be downloaded to: {os.path.abspath(download_dir)}")
# find the base directory once
base_folder = find_base_directory(client)
if not base_folder:
print("β Could not find the base directory. Exiting.")
exit(1)
success_count = 0
failed_count = 0
for idx, row in df.iterrows():
rec_name = str(row.get("Recording", "")).strip()
folder_path = determine_subfolder(row)
if not rec_name or not folder_path:
print(f"β οΈ Skipping row {idx+1} with missing info: {row}")
failed_count += 1
continue
target_file = f"{rec_name}.eaf"
sarah_file = f"{rec_name}_SS.eaf" # naming discrepancies :')
path_parts = folder_path.split("/")
print(f"\nπ [{idx+1}/{len(df)}] Looking for {target_file} in folder: {folder_path}")
folder = get_folder_by_path(path_parts, base_folder)
if not folder:
print(f"β Folder {folder_path} not found in Box.")
failed_count += 1
continue
found_file = None
for item in folder.get_items(limit=1000):
if item.type == 'file' and (item.name == target_file or item.name == sarah_file):
found_file = item
break
if not found_file:
print(f"β {target_file} not found in {folder_path}")
failed_count += 1
continue
try:
local_path = os.path.join(download_dir, target_file)
with open(local_path, 'wb') as f:
found_file.download_to(f)
print(f"β
Downloaded: {target_file}")
success_count += 1
except Exception as e:
print(f"β Failed to download {target_file}: {e}")
failed_count += 1
print(f"\nπ Summary: {success_count} files downloaded, {failed_count} failed")