Skip to content

Commit bfcf6c8

Browse files
committed
fixed formatting
1 parent 36c75b5 commit bfcf6c8

File tree

4 files changed

+88
-83
lines changed

4 files changed

+88
-83
lines changed

core/image_converter.py

Lines changed: 67 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -103,37 +103,37 @@ def to_frames(
103103
# Converting to image frame sets
104104
# This works for images and movies only
105105
format = "jpeg" if format == "jpg" else format
106-
106+
107107
# Handle GIF files first
108108
gif_to_frames(output, file_paths, self.file_handler)
109-
109+
110110
# Process regular image files
111111
for image_path_set in file_paths[Category.IMAGE]:
112112
try:
113113
if image_path_set[2] == format:
114114
continue
115-
115+
116116
if image_path_set[2] == "gif":
117117
# gif_to_frames already processed these
118118
self.file_handler.post_process(image_path_set, output, delete)
119119
continue
120-
120+
121121
# Ensure output directory exists
122122
output_dir = os.path.dirname(os.path.join(output, image_path_set[1]))
123123
os.makedirs(output_dir, exist_ok=True)
124-
124+
125125
# Construct full output path
126126
img_path = os.path.abspath(
127127
os.path.join(output, f"{image_path_set[1]}.{format}")
128128
)
129-
129+
130130
# Convert and save the image
131131
with Image.open(self.file_handler.join_back(image_path_set)) as img:
132132
# Convert to RGB if needed (important for WebP to PNG)
133-
if img.mode != 'RGB':
134-
img = img.convert('RGB')
133+
if img.mode != "RGB":
134+
img = img.convert("RGB")
135135
img.save(img_path, format=format.upper())
136-
136+
137137
# Verify the file was created before deleting source
138138
if os.path.exists(img_path):
139139
self.file_handler.post_process(image_path_set, img_path, delete)
@@ -142,7 +142,7 @@ def to_frames(
142142
f"[!] {lang.get_translation('conversion_failed', self.locale)}: "
143143
f"{self.file_handler.join_back(image_path_set)}"
144144
)
145-
145+
146146
except Exception as e:
147147
self.event_logger.error(
148148
f"[!] {lang.get_translation('error', self.locale)} "
@@ -477,47 +477,56 @@ def to_gif(
477477
images = []
478478
total_images = len(file_paths[Category.IMAGE])
479479
processed = 0
480-
480+
481481
# Log start of GIF creation
482-
if hasattr(self, 'prog_logger') and hasattr(self.prog_logger, 'bars_callback'):
483-
self.prog_logger.bars_callback('gif', 'index', 0, 0)
484-
482+
if hasattr(self, "prog_logger") and hasattr(
483+
self.prog_logger, "bars_callback"
484+
):
485+
self.prog_logger.bars_callback("gif", "index", 0, 0)
486+
485487
# Create tqdm progress bar
486488
progress_bar = tqdm(
487489
total=total_images,
488490
unit="img",
489491
leave=False,
490-
disable=not getattr(self, 'verbose', True) # Respect verbosity setting
492+
disable=not getattr(self, "verbose", True), # Respect verbosity setting
491493
)
492-
494+
493495
try:
494496
for i, image_path_set in enumerate(file_paths[Category.IMAGE], 1):
495497
if image_path_set[2] == format:
496498
progress_bar.update(1) # Update for skipped images too
497499
continue
498-
500+
499501
try:
500-
with Image.open(self.file_handler.join_back(image_path_set)) as image:
502+
with Image.open(
503+
self.file_handler.join_back(image_path_set)
504+
) as image:
501505
images.append(image.convert("RGB"))
502506
processed += 1
503-
507+
504508
# Update progress after each image
505-
if hasattr(self, 'prog_logger') and hasattr(self.prog_logger, 'bars_callback'):
506-
self.prog_logger.bars_callback('gif', 'index', i, i-1)
507-
508-
progress_bar.set_postfix({"current": os.path.basename(image_path_set[1])}, refresh=False)
509+
if hasattr(self, "prog_logger") and hasattr(
510+
self.prog_logger, "bars_callback"
511+
):
512+
self.prog_logger.bars_callback("gif", "index", i, i - 1)
513+
514+
progress_bar.set_postfix(
515+
{"current": os.path.basename(image_path_set[1])},
516+
refresh=False,
517+
)
509518
progress_bar.update(1)
510-
519+
511520
except Exception as e:
512521
error_msg = f"Error processing image {os.path.basename(image_path_set[1])}: {str(e)}"
513-
if hasattr(self, 'prog_logger'):
522+
if hasattr(self, "prog_logger"):
514523
self.prog_logger.log(error_msg)
515524
progress_bar.write(error_msg) # Show error in tqdm output
516525
raise # Re-raise to maintain original error handling
517-
526+
518527
finally:
519528
progress_bar.close()
520-
529+
521530
if images:
522531
output_path = os.path.join(output, f"{output}_merged.{format}")
523532
try:
@@ -527,45 +536,57 @@ def to_gif(
527536
append_images=images[1:],
528537
)
529538
# Log completion
530-
if hasattr(self, 'prog_logger') and hasattr(self.prog_logger, 'bars_callback'):
531-
self.prog_logger.bars_callback('gif', 'index', total_images, total_images-1)
539+
if hasattr(self, "prog_logger") and hasattr(
540+
self.prog_logger, "bars_callback"
541+
):
542+
self.prog_logger.bars_callback(
543+
"gif", "index", total_images, total_images - 1
544+
)
532545
except Exception as e:
533-
if hasattr(self, 'prog_logger'):
534-
self.prog_logger.log(f"Error saving GIF {output_path}: {str(e)}")
546+
if hasattr(self, "prog_logger"):
547+
self.prog_logger.log(
548+
f"Error saving GIF {output_path}: {str(e)}"
549+
)
535550
raise
536551
# Movies are converted to gifs as well, retaining 1/3 of the frames
537552
for i, movie_path_set in enumerate(file_paths[Category.MOVIE], 1):
538553
if self.file_handler.has_visuals(movie_path_set):
539554
try:
540555
# Log start of video to GIF conversion
541-
if hasattr(self, 'prog_logger') and hasattr(self.prog_logger, 'bars_callback'):
542-
self.prog_logger.bars_callback('video_gif', 'index', 0, 0)
543-
556+
if hasattr(self, "prog_logger") and hasattr(
557+
self.prog_logger, "bars_callback"
558+
):
559+
self.prog_logger.bars_callback("video_gif", "index", 0, 0)
560+
544561
video = VideoFileClip(
545562
self.file_handler.join_back(movie_path_set),
546563
audio=False,
547564
fps_source="tbr",
548565
)
549566
gif_path = os.path.join(output, f"{movie_path_set[1]}.{format}")
550-
567+
551568
# Calculate target fps, ensuring it's at least 1
552569
target_fps = max(1, int(video.fps // 3))
553-
570+
554571
# Write GIF with progress logging
555572
video.write_gif(
556-
gif_path,
557-
fps=target_fps,
573+
gif_path,
574+
fps=target_fps,
558575
logger=self.prog_logger,
559-
verbose=False # Disable moviepy's default progress bar
576+
verbose=False, # Disable moviepy's default progress bar
560577
)
561-
578+
562579
# Log completion of this video
563-
if hasattr(self, 'prog_logger') and hasattr(self.prog_logger, 'bars_callback'):
564-
self.prog_logger.bars_callback('video_gif', 'index', i, i-1)
565-
580+
if hasattr(self, "prog_logger") and hasattr(
581+
self.prog_logger, "bars_callback"
582+
):
583+
self.prog_logger.bars_callback("video_gif", "index", i, i - 1)
584+
566585
except Exception as e:
567-
if hasattr(self, 'prog_logger'):
568-
self.prog_logger.log(f"Error converting video {movie_path_set} to GIF: {str(e)}")
586+
if hasattr(self, "prog_logger"):
587+
self.prog_logger.log(
588+
f"Error converting video {movie_path_set} to GIF: {str(e)}"
589+
)
569590
raise # Re-raise to maintain original error handling
570591
video.close()
571592
self.file_handler.post_process(movie_path_set, gif_path, delete)
@@ -614,7 +635,7 @@ def to_gif(
614635
prs = pptx.Presentation(input_path)
615636
for slide in prs.slides:
616637
for shape in slide.shapes:
617-
if shape.shape_type == 13: # Picture
638+
if shape.shape_type == 13: # Picture
618639
image = shape.image
619640
img_bytes = image.blob
620641
img = Image.open(img_bytes)

core/utils/directory_watcher.py

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
"""
2-
Directory watcher implementation for monitoring file system events.
3-
"""
41
import time
52
from pathlib import Path
63
from typing import Callable, Optional
@@ -9,15 +6,7 @@
96

107

118
class DirectoryWatcher:
12-
"""
13-
A class to watch for file system events in a directory and its subdirectories.
14-
15-
Args:
16-
watch_path: Directory path to watch
17-
event_handler: Callback function that takes (event_type, src_path)
18-
recursive: Whether to watch subdirectories (default: True)
19-
"""
20-
9+
# Watches for file system events in a directory and its subdirectories
2110
def __init__(self, watch_path: str, event_handler: Callable, recursive: bool = True):
2211
self.watch_path = Path(watch_path).resolve()
2312
self.event_handler = event_handler
@@ -26,7 +15,7 @@ def __init__(self, watch_path: str, event_handler: Callable, recursive: bool = T
2615
self._running = False
2716

2817
def start(self) -> None:
29-
"""Start watching the directory."""
18+
# Start watching the directory
3019
if self._running:
3120
return
3221

@@ -59,33 +48,28 @@ def on_modified(_, event):
5948
raise RuntimeError(f"Failed to start directory watcher: {e}")
6049

6150
def stop(self) -> None:
62-
"""Stop watching the directory."""
51+
# Stop watching the directory
6352
if self.observer:
6453
self.observer.stop()
6554
self.observer.join()
6655
self.observer = None
6756
self._running = False
6857

6958
def __enter__(self):
70-
"""Context manager entry."""
59+
# Context manager entry
7160
self.start()
7261
return self
7362

7463
def __exit__(self, exc_type, exc_val, exc_tb):
75-
"""Context manager exit."""
64+
# Context manager exit
7665
self.stop()
7766

7867
def is_running(self) -> bool:
79-
"""Check if the watcher is running."""
68+
# Check if the watcher is running
8069
return self._running and self.observer is not None and self.observer.is_alive()
8170

8271
def watch(self, interval: float = 1.0) -> None:
83-
"""
84-
Start watching and block until KeyboardInterrupt.
85-
86-
Args:
87-
interval: Sleep interval between checks in seconds (default: 1.0)
88-
"""
72+
# Start watching and block until KeyboardInterrupt
8973
self.start()
9074
try:
9175
while self.is_running():

core/utils/exit.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

22
def end_with_msg(event_logger, exception: Exception, msg: str) -> None:
3-
# Single point of exit in the entire application
4-
if exception is not None:
5-
event_logger.warning(msg)
6-
raise exception(msg)
7-
else:
8-
event_logger.info(msg)
9-
exit(1)
3+
# Single point of exit in the entire application
4+
if exception is not None:
5+
event_logger.warning(msg)
6+
raise exception(msg)
7+
else:
8+
event_logger.info(msg)
9+
exit(1)

core/utils/file_handler.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def join_back(self, file_path_set: tuple) -> str:
1414
return os.path.abspath(
1515
f"{file_path_set[0]}{file_path_set[1]}.{file_path_set[2]}"
1616
)
17-
17+
1818
def post_process(
1919
self,
2020
file_path_set: tuple,
@@ -24,14 +24,14 @@ def post_process(
2424
) -> None:
2525
try:
2626
source_path = self.join_back(file_path_set)
27-
27+
2828
# Only log if the conversion was successful and output exists
2929
if show_status and os.path.exists(out_path):
3030
self.event_logger.info(
31-
f'[+] {lang.get_translation("converted", self.locale)} '
31+
f"[+] {lang.get_translation('converted', self.locale)} "
3232
f'"{source_path}" 🡢 "{out_path}"'
3333
)
34-
34+
3535
# Only delete source file if requested, output exists, and source exists
3636
if delete and os.path.exists(out_path) and os.path.exists(source_path):
3737
try:
@@ -41,13 +41,13 @@ def post_process(
4141
)
4242
except OSError as e:
4343
self.event_logger.warning(
44-
f'[!] {lang.get_translation("error", self.locale)}: '
44+
f"[!] {lang.get_translation('error', self.locale)}: "
4545
f'{lang.get_translation("could_not_remove", self.locale)} "{source_path}": {str(e)}'
4646
)
47-
47+
4848
except Exception as e:
4949
self.event_logger.error(
50-
f'[!] {lang.get_translation("error", self.locale)} in post_process: {str(e)}'
50+
f"[!] {lang.get_translation('error', self.locale)} in post_process: {str(e)}"
5151
)
5252
raise
5353

0 commit comments

Comments
 (0)