AI-Assisted Development of a Desktop Tool for Batch Audio and Video Extraction
This article presents the practical development of a desktop batch media extraction tool with the help of large language models. It covers requirement decomposition, layered architecture, responsive GUI design, background task execution, external converter integration, file collision handling, recursive file discovery, error reporting, and a verification workflow for AI-generated code.
1. Why Choose This Scenario?
Batch audio and video extraction is a typical small desktop-tool requirement. It combines file traversal, external process execution, long-running tasks, graphical user interface interaction, and error handling—covering many of the core concerns in desktop application development.
This makes it a more meaningful test of AI-assisted programming than generating a simple calculation function. Whether the code runs directly, whether the interface remains stable, and whether exceptions are handled properly can all be evaluated in this scenario.
The practical use cases are also clear. Organizing video assets, extracting speech from meeting recordings, and converting course materials into audio all require processing multiple files in a consistent format. Handling files one by one is inefficient and makes it easy to miss items.
2. Requirements: Turning Vague Needs into Verifiable Criteria
Giving a model an unstructured list of requirements often produces unpredictable results. A more reliable approach is to rewrite the requirements as verifiable items. Each item should be testable through a clear validation step.
Functional requirements include:
- Support common video container formats as input and common audio formats, such as MP3 and WAV, as output.
- Provide file import options for selecting a single file, multiple files, or an entire directory.
- When importing a directory, allow users to choose whether subdirectories should be traversed recursively.
- Provide input-format filtering and output-format selection.
- Provide controls for starting conversion, stopping the task, or exiting the application.
Non-functional requirements include:
- Keep the interface responsive during conversion. Users should be able to move the window and click buttons without the application appearing frozen.
- Provide an overall progress bar and status area that display the current file and processing result in real time.
- Show clear error messages that identify the failed file and explain the reason for failure.
- Detect missing required components before a task starts and notify the user instead of crashing midway through execution.
Boundary conditions also need to be defined in advance. These include how to handle output files with duplicate names, where the default output directory should be, and whether filenames containing non-ASCII characters or spaces should work correctly.
Making these rules explicit helps the model generate more appropriate code and gives developers clear criteria for acceptance testing.
3. Overall Architecture
The tool can be divided into four layers. Each layer has a focused responsibility, making the system easier to test and replace.
- UI layer: Responsible for window layout, control-event binding, and status display. It should not contain conversion logic.
- Task scheduling layer: Responsible for starting background threads, collecting results, and sending progress updates back to the UI.
- Conversion layer: Responsible for constructing external transcoding commands, executing them, and evaluating their results.
- Utility layer: Responsible for file traversal, path processing, duplicate-name checks, environment validation, and other shared functions.
Layering makes future changes easier. If the interface needs to be redesigned, the conversion logic does not need to change. If the transcoding method is replaced, only the conversion layer should require modification.
If generated code places all logic inside a single callback function, asking the model to refactor it is a reasonable and necessary change.
4. Keeping the Interface Responsive: Using Threads Correctly
A graphical application has a main thread that processes interface events. If a time-consuming conversion is executed directly inside a button callback, the main thread becomes blocked. The window can no longer repaint or respond to input, making the application appear frozen.
This is one of the most common mistakes made by beginners and an important indicator of generated-code quality.
The correct approach is to move the conversion task to a worker thread. The worker thread sends progress and result messages back through a queue, while the main thread updates the interface. UI controls should only be modified from the main thread; worker threads should not access them directly.
import queueimport threadingimport tkinter as tkfrom tkinter import ttkdef start_conversion(files, out_dir, fmt, msg_queue):thread = threading.Thread(target=worker, args=(files, out_dir, fmt, msg_queue), daemon=True)thread.start()def worker(files, out_dir, fmt, msg_queue):total = len(files)for index, path in enumerate(files, start=1):try:convert_one(path, out_dir, fmt)msg_queue.put(("progress", index / total * 100))except Exception as exc:msg_queue.put(("error", f"{path}: {exc}"))msg_queue.put(("done", None))def poll_results(root, msg_queue, bar, status):while True:try:kind, payload = msg_queue.get_nowait()except queue.Empty:breakif kind == "progress":bar["value"] = payloadelif kind == "error":status.set(f"Failed: {payload}")elif kind == "done":status.set("All tasks completed")returnroot.after(100, poll_results, root, msg_queue, bar, status)
This example highlights three points:
daemon=Truecauses the worker thread to end when the main program exits. A production tool should also use a cancellation flag so the worker can stop before processing the next file, preventing leftover processes.root.afterperiodically polls the queue from the main thread, ensuring that all UI updates occur on the main thread.- Exceptions are caught and converted into error messages, so a failure affecting one file does not interrupt the entire batch.
5. Important Details in the Conversion and Utility Layers
5.1 Environment Validation
The external transcoding program should be checked before a task starts. shutil.which can determine whether the executable is available in the system path. If the check fails, the application should provide an installation message immediately.
import osimport shutilCONVERTER = "media-converter" # Example placeholder; replace it with the actual converterdef check_converter():if shutil.which(CONVERTER) is None:raise RuntimeError(f"Converter {CONVERTER} was not found. ""Install it and add it to the system path.")
5.2 Safely Calling an External Program
External programs should be called using an argument list rather than a shell command string. This prevents spaces, quotation marks, and special characters in filenames from being misinterpreted, and it reduces command-injection risks.
File paths selected by users or discovered during directory traversal should be treated as untrusted input. They must not be concatenated directly into a command string.
import subprocessdef convert_one(src, out_dir, fmt):stem = os.path.splitext(os.path.basename(src))[0]dst = unique_path(out_dir, stem, f".{fmt}")cmd = [CONVERTER, "-i", src, dst]result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode != 0:raise RuntimeError(result.stderr.strip() or "Conversion failed")return dst
5.3 Preventing Output-File Collisions
Multiple files with the same name may exist in different directories. For example, two source directories might both contain lecture.mp4. If both are converted directly to lecture.mp3, the later result could overwrite the earlier one.
A general solution is to append a numeric suffix until an unused filename is found.
def unique_path(directory, stem, ext):candidate = os.path.join(directory, f"{stem}{ext}")counter = 1while os.path.exists(candidate):candidate = os.path.join(directory, f"{stem}_{counter}{ext}")counter += 1return candidate
5.4 Recursive Traversal and Format Filtering
def collect_media(root_dir, exts, recursive=True):found = []if recursive:for dirpath, _, filenames in os.walk(root_dir):for name in filenames:if os.path.splitext(name)[1].lower() in exts:found.append(os.path.join(dirpath, name))else:for name in os.listdir(root_dir):full = os.path.join(root_dir, name)if os.path.isfile(full) and os.path.splitext(name)[1].lower() in exts:found.append(full)return found
File extensions should be converted to lowercase before comparison. Otherwise, .MP4 and .mp4 may be treated as different formats.
Relying only on file extensions also has limitations because files may be incorrectly named. A stricter approach is to combine extension filtering with media-type detection performed by the transcoding program.
5.5 Choosing the Default Output Directory
The default output directory is an easy design detail to overlook. If the application uses its own installation directory, writing may fail when the tool is installed in a location that requires administrator permissions. The application directory may also be read-only.
A more practical approach is to use the source file’s directory or the user’s documents directory by default, while allowing the user to change the location explicitly in the interface.
Regardless of the selected strategy, the current output path should be clearly displayed in the UI. This prevents confusion about where the generated files were saved.
6. Error Handling and Status Feedback
The goal of error handling is to tell users what happened, how much was affected, and what they should do next. Common errors can be divided into three categories:
- Environment errors: The transcoding program is missing or the output directory is not writable. These errors should be detected before the task starts and should prevent execution.
- File errors: The source file is corrupted, the format is unsupported, or the path is too long. These errors should be recorded in an error list while allowing subsequent files to continue processing.
- Runtime errors: The disk runs out of space or the external process terminates unexpectedly. These errors should stop the current task while preserving results that have already been completed.
The status area should display the overall progress, the current file, and the most recent error. Error details can also be written to a log file for later investigation.
Logs should not include personal information beyond what is necessary for identifying file paths. They should also avoid printing complete command-line arguments, which could expose the user’s directory structure.
7. A Validation Workflow for Generated Code
Code generated by a large language model should not be used simply because it looks reasonable. A recommended validation sequence is as follows:
- Static checks: Use a syntax-checking command to confirm that the code can be parsed, then use static-analysis tools to identify unused variables, missing imports, and obvious type issues.
- Dependency checks: Confirm that the code uses only the standard library or declared third-party libraries, and verify the required versions.
- Functional testing: Test the core behavior with representative files and conditions, including successful conversion, duplicate filenames, recursive and non-recursive directory traversal, unsupported files, missing converters, and conversion failures.
