-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
350 lines (266 loc) · 12.1 KB
/
functions.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
342
343
344
345
346
347
348
349
350
import logging
import time
import sqlite3
import time
from PIL import Image
import os
import re
from pathlib import Path
from termcolor import colored
import sys
import traceback
import threading
logger = logging.getLogger("debug_logger")
def log(message, show=None):
time_now = time.strftime('%H:%M:%S')
date = time.strftime('%Y-%m-%d')
if show:
return logger.info(f"[{date} / {time_now}] {message}")
def traceback_error(detailed=False):
# Get the traceback object
exc_type, exc_value, exc_tb = sys.exc_info()
if exc_type is not None:
# Get the traceback information
formatted_tb = traceback.format_exception_only(exc_type, exc_value)
# Extract the file name, line number, and error message
filename = exc_tb.tb_frame.f_code.co_filename
line_number = exc_tb.tb_lineno
error_message = str(exc_value)
# Format the output with static parts colored red
formatted_message = (
colored("Error in ", 'light_red') + filename +
colored(f", line {line_number}: ", 'light_red') + error_message
)
# Print the formatted short error
print(formatted_message)
# If 'detailed' is True, print the full traceback
if detailed:
# Get the full traceback details
full_traceback = ''.join(traceback.format_exception(exc_type, exc_value, exc_tb))
# Print the detailed traceback in red
print(colored(full_traceback, 'light_red'))
else:
# Optionally, print an additional message or leave it out
print('For more details, use the detailed flag.')
class SpinnerWithMessage:
spinner_cycle = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
def __init__(self, message):
self.message = message
self.stop_running = threading.Event()
self.spinner_thread = threading.Thread(target=self.init_spinner)
self.message_lock = threading.Lock()
def start(self):
self.spinner_thread.start()
def stop(self, message, status='success'):
self.stop_running.set()
self.spinner_thread.join()
print('\r' + ' ' * (len(self.message) + 2 + len(self.spinner_cycle[0])), end='\r')
if status == "success":
print(colored('✔ ', 'green', attrs=['bold']) + message)
elif status == 'error':
print(colored('✘ ', 'red', attrs=['bold']) + message)
else:
print("There has been an error. Most likely with \"par: status\"")
def update(self, new_message):
with self.message_lock:
print('\r' + ' ' * (len(self.message) + 2 + len(self.spinner_cycle[0])), end='\r')
self.message = new_message
def init_spinner(self):
while not self.stop_running.is_set():
for symbol in self.spinner_cycle:
symbol = colored(symbol, 'yellow')
with self.message_lock:
print(f'\r{symbol} {self.message}', end='', flush=True)
time.sleep(0.1)
if self.stop_running.is_set():
break
def update_content_cache_index():
general_db = 'admin_base/general.db'
initial = database.read(general_db, "update_index", "content_update_index")
new = int(initial[0][0]) + 1
database.update(general_db, "update_index", "content_update_index", new)
return initial
class database():
"""
A class for handling basic database operations.
"""
def write(db_path, table, column, value):
"""
Insert a value into a specific column of a table.
Parameters:
db (object): Database connection object
cursor (object): Cursor object for executing queries.
table (str): The name of the table.
column (str): The name of the column.
value (str/int/float): The value to be inserted.
"""
db = sqlite3.connect(db_path, check_same_thread=False)
cursor = db.cursor()
try:
if type(value) == str:
query = f'INSERT INTO {table} ({column}) VALUES ("{value}");'
else:
query = f'INSERT INTO {table} ({column}) VALUES ({value});'
cursor.execute(query)
db.commit()
log(f"Succesfully excuted command {query}")
return True
except:
log(f"Error excuting {query}")
def update(db_path, table, column, new_value, do_log=True):
"""
Update a value in a specific column of a table.
Parameters:
db (object): Database connection object.
cursor (object): Cursor object for executing queries.
table (str): The name of the table.
column (str): The name of the column.
new_value (str/int/float): The new value to update.
"""
db = sqlite3.connect(db_path, check_same_thread=False)
cursor = db.cursor()
try:
query = f"SELECT {column} from {table}"
cursor.execute(query)
old_value = cursor.fetchall()
old_value = old_value[0][0]
# if type(new_value) == str:
# query = f"""
# UPDATE {table}
# SET {column} = '{new_value}'
# WHERE {column} IS \"\"\"{old_value}\"\"\"
# """
# elif type(new_value) == int or type(new_value) == float:
# query = f"""
# UPDATE {table}
# SET {column} = {new_value}
# WHERE {column} = {old_value};
# """
# print(query)
query = f"""
UPDATE {table}
SET {column} = ?
WHERE {column} = ?
"""
cursor.execute(query, (new_value, old_value))
db.commit()
if do_log == True:
log(f"Succesfully excuted command {query}")
except Exception as e:
log(f"Unexpected error: {e}")
def read(db_path, table, column):
"""
Read values from a specific column of a table.
Parameters:
cursor (object): Cursor object for executing queries.
table (str): The name of the table.
column (str): The name of the column.
"""
db = sqlite3.connect(db_path, check_same_thread=False)
cursor = db.cursor()
try:
query = f"SELECT {column} from {table}"
cursor.execute(query)
value = cursor.fetchall()
return value
except Exception as e:
log(f"Unexpected error: {e}")
def read_database(db_path, table):
try:
# Connect to the database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
query = f"SELECT * FROM {table}"
logging.debug(f"Executing query: {query}")
cursor.execute(query)
row = cursor.fetchone() # Fetch one row assuming there's only one
if row is None:
logging.info("No data found.")
return {}
columns = [desc[0] for desc in cursor.description]
# Initialize a dictionary to hold column data
value_list = {column: value for column, value in zip(columns, row)}
# Close the connection
conn.close()
return value_list
except sqlite3.DatabaseError as e:
log(f"Database error: {e}")
except Exception as e:
log(f"Unexpected error: {e}")
finally:
# Ensure the connection is closed if it was opened
try:
conn.close()
except:
log("Failed to close the database connection.")
def clean_old_hashed_images(image_name, static_root):
# Get base image name without extension
base_name = Path(image_name).stem
# Define the pattern to match hashed versions of the image
pattern = re.compile(rf"{base_name}\.[\w\d]+\.v\d+\.\w+")
# Find all matching hashed versions in the static files directory
for file_path in Path(static_root).rglob(f"{base_name}.*"):
if pattern.match(file_path.name):
os.remove(file_path)
def update_image(image_path, db_path, uploaded_image, field_name, db_table_attr):
"""
Handles saving and compressing uploaded images.
Compresses images if they are not PNG; otherwise, saves as-is.
Checks for existing files with the same name but different formats and deletes them if found.
Saves the image in the format corresponding to the original image type.
"""
try:
# Open the uploaded image
image = Image.open(uploaded_image)
image_format = str(image.format.lower())
# Define the base save path without format
base_save_path = os.path.join(image_path, field_name)
image_formats = ['jpg', 'jpeg', 'png', 'webp']
# Remove any other versions of image
for formats in image_formats:
initial_image_path = f"{base_save_path}.{formats}"
if os.path.exists(initial_image_path):
os.remove(initial_image_path)
print("Image format: ", image_format)
# Handle JPG & JPEG images
if image_format == "jpg" or image_format == "jpeg":
print("here in the jpg section")
# Save as JPEG
save_path = f"{base_save_path}.jpg"
image = image.convert("RGB") # Ensure it has no alpha channel (JPEG doesn't support transparency)
image.save(save_path, "JPEG", quality=75, optimize=True) # Adjust quality as needed
log(f"Compressed and saved image {field_name} as JPEG at {save_path}.")
# Save the database with field_name and '.jpg'
database.update(db_path, db_table_attr, field_name, f"{field_name}.jpg", do_log=False)
# Handle PNG images
elif image_format == "png":
print("Got here in PNG section")
print(db_path, db_table_attr, field_name, f"{field_name}.png")
# Save as PNG without compression
save_path = f"{base_save_path}.png"
if image.mode == "P" and "transparency" in image.info:
image = image.convert("RGBA")
image.save(save_path, "PNG")
log(f"Saved image {field_name} as PNG at {save_path}.")
print('passed this')
# Save the database with field_name and '.png'
database.update(db_path, db_table_attr, field_name, f"{field_name}.png", do_log=True)
# Handle all other types of images
else:
print("here in the else section")
# For any other format, save it with its original format
existing_path = f"{base_save_path}.{image_format}"
if os.path.exists(existing_path):
os.remove(existing_path) # Remove the existing file with the same name and different format
log(f"Deleted existing file: {existing_path}")
save_path = f"{base_save_path}.{image_format}"
image.save(save_path, image_format.upper()) # Save with the original format
log(f"Saved image {field_name} as {image_format.upper()} at {save_path}.")
# Save the database with field_name and its respective format
database.update(db_path, db_table_attr, field_name, f"{field_name}.{image_format}", do_log=False)
print("Updated Image")
# if settings.DEBUG == False:
# clean_old_hashed_images(field_name, image_path)
update_content_cache_index()
except Exception as e:
log(f"Error saving image {field_name}: {e}")