AI-Assisted Development of a Batch Audio and Video Extraction Tool
This practical guide explains how to design and validate a desktop tool that batch-converts video files into audio. It covers requirement decomposition, responsive threading, safe external process execution, recursive file scanning, progress reporting, error handling, cancellation, output-file conflict prevention, and testing strategies for AI-generated or manually written code.
1. Breaking Requirements into Testable Items
Desktop tool requirements often begin as informal requests such as “Batch-convert videos to audio, keep the interface responsive, and show errors.” These statements cannot be implemented or validated directly. Before development begins, convert them into specific functional and non-functional requirements.
Typical functional requirements include:
- File import: Support single-file selection, multi-file selection, and recursive directory scanning.
- Format detection: Filter video files by extension and allow users to configure the supported format set.
- Output settings: Select the target audio format, such as MP3 or WAV, and specify the output directory.
- Execution and control: Start conversion, cancel tasks, and exit the application.
Non-functional requirements determine whether the tool is usable in practice:
- Responsiveness: The interface must continue responding to clicks, dragging, and window resizing during conversion.
- Observability: A progress bar should show overall progress, while the status bar should display the current file and result.
- Fault tolerance: A failure in one file should not stop the entire batch, and the cause should be shown to the user.
- Environment validation: Check that external dependencies are available before starting conversion.
After the requirements have been decomposed, each item can be mapped to a test case. This step also determines the quality of later prompts or development documentation. The more specific the requirements are, the less likely generated code is to deviate from the intended behavior.
2. Threading Model: Separate the Interface from Long-Running Work
Desktop UI frameworks generally use a single main thread to process the event loop. If conversion is executed directly inside a button callback, the main thread becomes blocked. The window cannot repaint during conversion and appears to freeze. This is one of the most common defects in desktop tools.
The solution is to move long-running work to a worker thread and transfer messages through a thread-safe queue:
- The main thread handles user actions and UI updates only.
- The worker thread processes files one by one and places progress, success, and failure events into the queue.
- The interface checks the queue approximately every 100 milliseconds using a timer, then updates the controls.
The key rule is that the worker thread must not directly modify UI controls. UI widgets are generally not thread-safe, and cross-thread updates can cause exceptions or crashes. All interface updates should be performed by the main thread.
The following example shows the core worker and queue logic independently of any specific UI framework:
import queueimport shutilimport subprocessimport threadingfrom pathlib import Path# The executable name of the external conversion component.# The actual value depends on the deployment environment.ENCODER_NAME = "media-encoder"def worker(encoder: str, files: list[Path], out_dir: Path,out_fmt: str, events: queue.Queue, stop_flag: threading.Event) -> None:total = len(files)for index, src in enumerate(files, start=1):if stop_flag.is_set():breakdst = unique_output_path(out_dir / f"{src.stem}.{out_fmt}")events.put(("status", f"Processing {src.name} ({index}/{total})"))try:convert_one(encoder, src, dst)events.put(("ok", src.name))except Exception as exc:events.put(("error", f"{src.name}: {exc}"))events.put(("progress", index / total * 100))events.put(("done", None))def start_job(files, out_dir, out_fmt):encoder = shutil.which(ENCODER_NAME)if encoder is None:raise EnvironmentError("The conversion component was not found. ""Install it and confirm that it is available on the system path.")events: queue.Queue = queue.Queue()stop_flag = threading.Event()thread = threading.Thread(target=worker,args=(encoder, files, out_dir, out_fmt, events, stop_flag),daemon=True,)thread.start()return events, stop_flag
The UI layer only needs a polling function. A UI timer can call it every 100 milliseconds to retrieve and handle all currently available events:
def poll_events(events: queue.Queue, handle_event) -> None:while True:try:kind, payload = events.get_nowait()except queue.Empty:breakhandle_event(kind, payload) # Update UI controls on the main thread
get_nowait does not block, so the polling function does not slow down the interface.
3. Conversion Flow and External Process Execution
3.1 Dependency Detection
When conversion depends on an external command-line component, check its availability before the task begins. shutil.which can determine whether an executable with the specified name exists on the system path. If the check fails, show a clear message immediately instead of waiting until the first file conversion fails.
Environment validation should also cover cases where the component exists but is too old or does not support the required parameters. During the validation phase, the application can run a version query and record the result in the log for troubleshooting.
3.2 Safe Subprocess Invocation
File names obtained from users or directory scans may contain spaces, quotation marks, or other special characters. Building a command as a single string creates injection risks and can cause paths containing spaces to be split incorrectly.
The recommended approach is to:
- Pass arguments as a list rather than using
shell=True. - Pass every argument separately and convert paths to strings consistently.
- Capture standard error output and display it when conversion fails.
def convert_one(encoder: str, src: Path, dst: Path) -> None:# The exact arguments depend on the component being used.# This example only demonstrates the invocation pattern.cmd = [encoder, "--input", str(src), "--output", str(dst)]result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)if result.returncode != 0:raise RuntimeError(result.stderr.strip() or f"Exit code {result.returncode}")
The timeout parameter prevents a damaged file from keeping the worker thread blocked indefinitely. When the timeout is reached, subprocess.run raises an exception, and the surrounding error handler records that file as failed.
3.3 Preventing Output Overwrites
In a batch task, files with the same name may exist in different subdirectories. Writing them directly to the same output path could silently overwrite an earlier result. A practical strategy is to detect whether the target exists and append a numeric suffix when necessary:
def unique_output_path(path: Path) -> Path:if not path.exists():return pathcounter = 1while True:candidate = path.with_name(f"{path.stem}_{counter}{path.suffix}")if not candidate.exists():return candidatecounter += 1
The actual output path should also be recorded in the log so users can locate the generated file.
3.4 Recursive Scanning and Format Filtering
When scanning directories recursively, use Path.rglob together with a set of supported extensions. Normalize extensions to lowercase before comparison; otherwise, .MP4 and .mp4 would be treated as different formats.
VIDEO_SUFFIXES = {".mp4", ".mkv", ".mov", ".avi", ".flv", ".webm"}def collect_videos(root: Path) -> list[Path]:return sorted(p for p in root.rglob("*")if p.is_file() and p.suffix.lower() in VIDEO_SUFFIXES)
Display the scan results before conversion starts so users can confirm the number of files. When scanning a large directory, perform the scan in a worker thread as well to prevent the interface from becoming unresponsive.
4. Designing Progress and Status Displays
The simplest progress calculation is based on the number of files: completed files divided by the total number of files. This is sufficient for most batch-processing scenarios.
If progress within an individual file is required, the application must read duration or progress information from the conversion component and convert it into a percentage. This requires parsing the component’s output, and formats differ between tools. Confirm the output structure in a test environment before implementing this feature. If the output cannot be parsed reliably, it is better to show file-level progress than to display inaccurate numbers.
The status bar should provide three types of information:
- Current state: For example, “Processing file 3 of 10.”
- Summary statistics: The number of successful and failed files.
- The latest error: A brief explanation, with the complete log available in a separate panel.
5. Error Handling and User Notifications
Error handling should be layered. Common errors can be grouped into four categories:
- Environment errors: The external component is missing or incompatible. Intercept these before the task begins and prevent the task from starting.
- Input errors: A file is damaged, encoded unexpectedly, or cannot be read. These errors should affect only the current file.
- Output errors: The destination directory does not exist or is not writable. These errors may affect the entire batch and should be checked before execution.
- Runtime errors: Conversion times out or the process exits unexpectedly. These errors should generally affect only the current file.
Each file should be processed inside its own exception handler, as shown in the worker function above. If one file fails, the task should continue with the remaining files. The final summary should list every failed item.
User notifications should also be layered. Dialog boxes are appropriate for errors that require immediate attention, such as a missing dependency. Logs are better for recording results for individual files. Displaying every error in a dialog would make batch processing difficult to use.
6. Exiting and Canceling Tasks
When a user exits while a task is running, the application needs to:
- Set the stop flag.
- Wait for the current file to finish or interrupt it.
- Close the interface.
Closing the interface without notifying the worker thread can leave background processes running or produce incomplete output files. The stop_flag shown earlier is designed for this purpose. The worker checks the flag before beginning each file.
If faster cancellation is required, the application can manage the subprocess handle outside subprocess.run and terminate the child process when cancellation is requested. This approach is more complex and is suitable when response time is especially important.
The worker thread is configured as a daemon thread, so the main program does not have to wait for it before exiting. This helps avoid delays during shutdown, but it also means that an unfinished file may leave an incomplete output. Before exiting, the application should confirm the user’s intent and clean up incomplete output files.
7. Validation: How to Confirm the Code Is Reliable
Whether the code is written by a developer or generated by AI, it should go through the following checks before delivery.
7.1 Static Checks
Start with syntax compilation to confirm that the interpreter can parse the code correctly:
import py_compilepy_compile.compile("batch_extract.py", doraise=True)
Then use type-checking and code-style tools to inspect interface signatures, unused variables, and related issues. Static checks cannot replace runtime testing, but they can identify many low-level problems early.
7.2 Functional Test Cases
At a minimum, test the following scenarios:
- Empty directory: Display a message indicating that no processable files were found.
- Mixed directory: When video and non-video files coexist, process only the video files.
- Duplicate names: When files with the same name exist in multiple subdirectories, automatically number the generated outputs.
- Damaged file: If one file cannot be parsed, the remaining files should still complete.
- Non-writable output directory: Reject the task before it starts.
- Missing conversion component: Prompt the user to install the required component before starting.
- File names containing spaces: Confirm that the files are processed correctly without incorrectly splitting their paths.
