-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjpeg_changer.py
341 lines (290 loc) · 11.4 KB
/
jpeg_changer.py
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from dotenv import load_dotenv
import os
import logging
# Load environment variables and setup logging
load_dotenv()
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def setup_driver():
#Set up and return the Chrome WebDriver.
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
return webdriver.Chrome(options=options)
def wait_for_input():
#Wait for user input with clear prompt.
print("\nWhat would you like to do?")
print("1: Rename to ID (for driver's license JPGs)")
print("2: Skip this item")
print("3: Go to next entry")
print("4: Quit program")
while True:
try:
choice = input("Choice (1-4): ").strip()
if choice in ['1', '2', '3', '4']:
return choice
print("Invalid choice, please enter 1-4")
except Exception:
print("Invalid input, please try again")
def login(driver, username, password):
#Log in to ShelterManager.
try:
logging.info("Attempting to log in...")
driver.get("https://service.sheltermanager.com/asmlogin")
time.sleep(0.5)
#Fill in login details
driver.find_element(By.ID, "smaccount").send_keys('hsnba')
driver.find_element(By.ID, "username").send_keys(username)
driver.find_element(By.ID, "password").send_keys(password)
driver.find_element(By.ID, "login").click()
#Wait for login to complete
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "asm-menu-reports"))
)
logging.info("Login successful")
return True
except Exception as e:
logging.error(f"Login failed: {e}")
return False
def navigate_to_jpegs(driver):
#Navigate to the Jpegs Unnamed section.
try:
logging.info("Navigating to Jpegs Unnamed...")
#Click Reports
reports = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "asm-menu-reports"))
)
reports.click()
time.sleep(0.3)
#Click Media submenu
media = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "ui-id-15"))
)
media.click()
time.sleep(0.3)
#click Jpegs Unnamed
jpegs = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, "Jpegs Unnamed"))
)
jpegs.click()
time.sleep(0.5)
#Verify on the correct page
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//table/tbody/tr"))
)
logging.info("Successfully navigated to Jpegs Unnamed")
return True
except Exception as e:
logging.error(f"Navigation failed: {e}")
return False
def safe_click(driver, element, use_js=True):
### Safely click an element using either JavaScript or regular click.
try:
#scroll into view
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", element)
time.sleep(0.2)
if use_js:
driver.execute_script("arguments[0].click();", element)
else:
element.click()
return True
except Exception as e:
logging.error(f"Click failed: {e}")
return False
def close_dialog_if_open(driver):
#Try to close any open dialog.
try:
cancel_buttons = driver.find_elements(
By.XPATH,
"//button[contains(@class, 'ui-button') and (text()='Cancel' or text()='Close')]"
)
if cancel_buttons:
safe_click(driver, cancel_buttons[0])
time.sleep(0.3)
except Exception:
pass
def move_dialog_down(driver, pixels=300):
#Move the dialog box down by dragging the Edit media title.
try:
time.sleep(0.5)
#find "Edit media" title text
edit_media_title = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "ui-dialog-title"))
)
print("Found Edit media title, attempting to drag...")
actions = ActionChains(driver)
# Move to the exact title element
actions.move_to_element(edit_media_title)
# Pause briefly to simulate human hover
actions.pause(0.5)
# Click and hold left mouse button
actions.click_and_hold()
# Pause briefly to simulate human holding
actions.pause(0.5)
# Move straight down
actions.move_by_offset(0, pixels)
# Release mouse button
actions.release()
# Execute the action sequence
actions.perform()
print("Drag action completed")
return True
except Exception as e:
logging.error(f"Failed to move dialog with error: {str(e)}")
return False
def rename_to_id(driver):
#Rename the current file to ID.
try:
# Wait for textarea
textarea = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "medianotes"))
)
#select all and type ID - no wait needed between these
textarea.send_keys(Keys.COMMAND + "a")
textarea.send_keys("ID")
#click the Change button
change_button = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((
By.XPATH,
"//button[contains(@class, 'asm-dialog-actionbutton') and text()='Change']"
))
)
safe_click(driver, change_button)
time.sleep(0.3) # Brief wait for change
# Go back immediately
driver.back()
time.sleep(0.3)
return True
except Exception as e:
logging.error(f"Error renaming file: {e}")
close_dialog_if_open(driver)
return False
def is_pdf_link(link):
#check if link is pdf vs normal image
try:
#get parent and find thumbnail
parent = link.find_element(By.XPATH, "./..")
img = parent.find_element(By.CLASS_NAME, "asm-thumbnail")
src = img.get_attribute("src")
#check for pdf icon or if not a regular image
if "pdf-media.png" in src or "mode=media" not in src:
return True
return False
except:
return False
def process_entries(driver):
#Interactive processing of entries.
try:
continue_processing = True
current_entry_index = 0
while continue_processing:
# Find entries
entries = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.XPATH, "//table/tbody/tr/td[2]/b/a"))
)
if not entries:
print("No more entries found.")
break
if current_entry_index >= len(entries):
print("Processed all entries.")
break
#get the current entry
entry = entries[current_entry_index]
entry_name = entry.text
#skip if it looks like an animal entry (typically single word names)
if len(entry_name.split()) == 1:
print(f"Skipping likely animal entry: {entry_name}")
current_entry_index += 1
continue
#click the entry
print(f"\nNavigating to entry {current_entry_index + 1} of {len(entries)}: {entry_name}")
if not safe_click(driver, entry):
print("Failed to click entry, trying next one...")
current_entry_index += 1
continue
time.sleep(0.3)
#find edit links (dates)
edit_links = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, "a.link-edit[data-id]"))
)
print(f"Found {len(edit_links)} items to process")
for i, link in enumerate(edit_links):
#skip PDFs automatically
if is_pdf_link(link):
print(f"Skipping PDF file (item {i+1})")
continue
date_text = link.text or "No date"
print(f"\nProcessing item {i+1} of {len(edit_links)} (Date: {date_text})")
# add delay BEFORE clicking the link
time.sleep(2)
if safe_click(driver, link):
time.sleep(0.3)
action = wait_for_input()
if action == "1":
if rename_to_id(driver):
print("Successfully renamed to ID")
current_entry_index += 1
break # Exit the loop for this entry's items
else:
print("Failed to rename")
close_dialog_if_open(driver)
elif action == "2":
print("Skipping this item")
close_dialog_if_open(driver)
elif action == "3":
print("Moving to next entry")
close_dialog_if_open(driver)
current_entry_index += 1
driver.back()
time.sleep(0.3)
break # Exit the loop for this entry's items
elif action == "4":
print("Quitting program")
return
else:
print(f"Failed to click item {i+1}")
#go back to list if we haven't already (if we skipped all items)
if not action in ["1", "3"]:
driver.back()
time.sleep(0.3)
current_entry_index += 1
print("\nReady for next entry")
except Exception as e:
logging.error(f"Error in process_entries: {e}")
print("\nAn error occurred. Press Enter to continue...")
input()
def main():
driver = None
try:
# Setup
driver = setup_driver()
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
if not username or not password:
raise ValueError("Username or password not found in environment variables")
#login and navigate
if not login(driver, username, password):
raise Exception("Login failed")
if not navigate_to_jpegs(driver):
raise Exception("Navigation failed")
#start interactive processing
process_entries(driver)
except Exception as e:
logging.error(f"Main process error: {e}")
print("\nAn error occurred. Press Enter to continue...")
input()
finally:
try:
if driver:
driver.quit()
logging.info("Browser closed successfully")
except Exception as e:
logging.error(f"Error closing browser: {e}")
if __name__ == "__main__":
main()