Here's a refactored version of your check_for_corrupted_files function. The refactoring focuses on improving readability, modularity, and leveraging Python's modern features such as type annotations and improved error handling.
import subprocess
import time
from pathlib import Path
from queue import Queue
from typing import List, Tuple
def check_for_corrupted_files() -> None:
"""Check for corrupted files in the input folder."""
image_processor.reset_results()
if not ffmpeg_is_available():
return
valid_extensions = Config.VIDEO_EXTENSIONS | Config.AUDIO_EXTENSIONS | Config.IMAGE_EXTENSIONS
tasks = list(get_valid_file_paths(Config.INPUT_FOLDER, valid_extensions))
if not tasks:
log_error(f"No valid media files found in '{Config.INPUT_FOLDER}'")
return
error_queue: Queue[Tuple[Path, List[str]]] = Queue()
start_time = time.time()
total_files = len(tasks)
shared_state.processed_files_count = 0
shared_state.total_files_count = total_files
for file_path in tasks:
run_with_thread_pool(process_file, file_path, valid_extensions, error_queue, start_time, total_files)
log_errors(error_queue)
def ffmpeg_is_available() -> bool:
"""Check if FFmpeg is available in the system."""
try:
check_ffmpeg()
return True
except FileNotFoundError as error:
log_error(str(error))
return False
def get_valid_file_paths(root: Path, valid_extensions: set) -> List[Path]:
"""Yield file paths with valid extensions."""
return (
file_path
for file_path in root.rglob("*")
if file_path.is_file() and file_path.suffix.lower() in valid_extensions
)
def process_file(
file_path: Path,
valid_extensions: set,
error_queue: Queue,
start_time: float,
total_files: int
) -> None:
"""Check a file for corruption using FFmpeg and update status."""
try:
if file_path.suffix.lower() not in valid_extensions:
return
command = build_ffmpeg_command(file_path)
result = subprocess.run(
command,
capture_output=True,
text=True,
encoding="utf-8",
errors="ignore",
)
error_messages = extract_error_messages(result)
if error_messages:
error_queue.put((file_path.resolve(), error_messages))
except Exception as e:
error_queue.put(
(
file_path.resolve(),
[f"Error processing file {file_path}: {e}"],
)
)
finally:
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
def build_ffmpeg_command(file_path: Path) -> List[str]:
"""Construct the FFmpeg command based on file extension."""
base_command = [
str(Config.FFMPEG),
"-v",
"error",
"-i",
str(file_path),
]
if file_path.suffix.lower() in Config.VIDEO_EXTENSIONS:
base_command += ["-map", "0:a:0"]
base_command += ["-f", "null", "-"]
return base_command
def extract_error_messages(result: subprocess.CompletedProcess) -> List[str]:
"""Extract error messages from FFmpeg's output."""
combined_output = f"{result.stdout}\n{result.stderr}"
return [
line.strip()
for line in combined_output.splitlines()
if "error" in line.lower()
]
Changes and Improvements:
-
Modularization:
ffmpeg_is_available: Checks the availability of FFmpeg and logs an error if not found.
get_valid_file_paths: Generates valid file paths based on the provided extensions.
process_file: Moves the inner process_file function outside to enhance readability and testability.
build_ffmpeg_command: Constructs the FFmpeg command based on the file type.
extract_error_messages: Parses FFmpeg output to extract error messages.
-
Type Annotations:
- Added type hints for better code clarity and to assist with static type checking.
-
List Conversion:
- Converted the generator from
get_valid_file_paths to a list immediately to determine total_files.
-
Error Handling:
- Simplified the FFmpeg availability check with a separate function.
-
Thread Pool Usage:
- Assumed
run_with_thread_pool can accept the process_file function along with its arguments. If run_with_thread_pool is a thread pool executor, you might need to adjust how process_file is submitted.
-
Queue Typing:
- Specified the types stored in the
Queue for better clarity.
-
String Formatting:
- Maintained the use of f-strings for consistency and readability.
-
Single Responsibility Principle:
- Each function now has a single responsibility, making the code easier to maintain and test.
Notes:
-
Thread Pool Execution: The refactored code assumes that run_with_thread_pool is a function that takes a callable and its arguments, submitting them to a thread pool. Ensure that this function correctly handles the submission of tasks with multiple arguments.
-
Shared State Management: The shared_state object is used to keep track of processed files. Ensure that it's thread-safe, especially when accessed concurrently.
-
Logging and Error Handling: The refactored code maintains your existing logging strategy. Make sure that log_error and log_errors are thread-safe if they can be called from multiple threads.
Feel free to adjust the structure further based on the broader context of your application and any specific requirements you might have.