LLM-Assisted GUI Development: Building a Batch Audio Extraction Tool
When large language models generate desktop application code, "it runs" and "the UI stays responsive" are often two different things. This article uses a batch audio extraction tool as a test case to show how to break down requirements, which prerequisites need human input, and what a prompt should contain. The included code is a runnable skeleton — verify it locally before use.
LLM-Assisted GUI Development: Building a Batch Audio Extraction Tool
When large language models generate desktop application code, “it runs” and “the UI stays responsive” are often two different things. This article uses a batch audio extraction tool as a test case to show how to break down requirements, which prerequisites need human input, and what a prompt should contain. The included code is a runnable skeleton — verify it locally before use.
1. Why Use a Desktop Tool as the Test Case
LLMs already perform well on algorithm problems, but a desktop application combines UI layout, an event loop, concurrent tasks, and external program calls. When these parts stack together, models tend to miss details. An audio extraction tool covers all of these scenarios: the UI must list files, conversion must invoke an external command-line tool, and batch processing must not block the interface.
Benchmark scores do not directly translate into development efficiency. More practical criteria are: can the generated code launch in the target environment, can it complete one conversion, and does it produce clear error messages when something fails?
2. Requirement Breakdown and Acceptance Criteria
| Requirement | Technical Point | Acceptance Criterion | Common Failure |
|---|---|---|---|
| Multi-format input | Filter by extension, case-insensitive | Both .MP4 and .mp4 are recognized | Only lowercase extensions matched |
| Output format | ffmpeg arguments for MP3, WAV | Output file opens in a player | Missing -vn, video stream mixed into output |
| UI components | Listbox, Combobox, Progressbar, status bar | Widgets don’t overlap when window resizes | Fixed coordinates cause overlapping widgets |
| Batch operations | Import, start, exit form a closed loop | Buttons re-enabled after tasks finish | Buttons remain disabled after tasks finish |
| Error reporting | messagebox dialogs and error summary | One failed file doesn’t affect others | Exception in loop crashes the program |
| Responsiveness | Background thread with queue communication | Window stays draggable during conversion | subprocess.run on main thread freezes the UI |
Once acceptance criteria are written as a table, both the prompt and code review share a common baseline.
3. Prerequisite: Install ffmpeg First
The Python standard library cannot decode video. The tool in this article calls the ffmpeg command-line program to perform conversion, so you must confirm that ffmpeg is installed and available on your PATH before running it. Check with:
ffmpeg -version
If the command is not found, download ffmpeg, extract it, and add its bin directory to your system PATH. On Windows, you can run where ffmpeg in a command prompt to verify the path. After modifying PATH, reopen your terminal — already-open windows will not pick up the new environment variable.
4. Preventing Freezes: Convert in a Worker Thread, Update the UI on the Main Thread
tkinter only allows widget operations on the main thread. If a worker thread directly modifies a Progressbar or Label, the program may crash or exhibit hard-to-reproduce display glitches. The correct approach has two steps:
- The worker thread executes the subprocess call and puts progress and status into a
queue.Queue. - The main thread polls the queue with
root.afterand updates the UI with the retrieved messages.
Full example:
import osimport queueimport shutilimport subprocessimport threadingimport tkinter as tkfrom pathlib import Pathfrom tkinter import filedialog, messagebox, ttkVIDEO_EXTS = {".mp4", ".mkv", ".mov", ".avi", ".flv"}def check_ffmpeg():"""Check whether ffmpeg is available; return (ok, version info or error reason)."""if shutil.which("ffmpeg") is None:return False, "ffmpeg not found. Please install it and add its directory to PATH."try:result = subprocess.run(["ffmpeg", "-version"],capture_output=True, text=True, timeout=10,)first_line = result.stdout.splitlines()[0] if result.stdout else "Unknown version"return True, first_lineexcept (OSError, subprocess.TimeoutExpired) as exc:return False, f"Failed to invoke ffmpeg: {exc}"def unique_path(path: Path) -> Path:"""If the target file exists, try name_1, name_2, etc."""if not path.exists():return pathi = 1while True:candidate = path.with_name(f"{path.stem}_{i}{path.suffix}")if not candidate.exists():return candidatei += 1def collect_videos(paths):"""Accept file or folder paths and return a list of Paths to all video files found."""found = []for raw in paths:p = Path(raw)if p.is_file() and p.suffix.lower() in VIDEO_EXTS:found.append(p)elif p.is_dir():for root_dir, _, names in os.walk(p, onerror=lambda e: None):for name in names:f = Path(root_dir) / nameif f.suffix.lower() in VIDEO_EXTS:found.append(f)return founddef worker(files, out_dir, fmt, msg_queue):"""Convert files one by one in a worker thread; communicate with the UI only via the queue."""total = len(files)for idx, src in enumerate(files, start=1):msg_queue.put(("status", f"Processing {src.name} ({idx}/{total})"))dst = unique_path(out_dir / f"{src.stem}.{fmt}")# Pass arguments as a list, not a concatenated string, to avoid shell injection.# -n means never overwrite existing files, a second safeguard on top of unique_path.cmd = ["ffmpeg", "-n", "-i", str(src), "-vn", str(dst)]try:subprocess.run(cmd, check=True, capture_output=True, timeout=3600)except subprocess.CalledProcessError as exc:tail = exc.stderr.decode(errors="ignore")[-200:]msg_queue.put(("error", f"{src.name} conversion failed: {tail}"))except subprocess.TimeoutExpired:msg_queue.put(("error", f"{src.name} timed out, skipped"))except OSError as exc:# e.g., ffmpeg was deleted mid-conversion; no point continuing, end the task.msg_queue.put(("error", f"Cannot invoke ffmpeg: {exc}"))breakmsg_queue.put(("progress", idx / total * 100))msg_queue.put(("done", None))class App:def __init__(self, root):self.root = rootself.msg_queue = queue.Queue()self.files = []self.errors = []self.status = tk.StringVar(value="Ready")self.fmt = tk.StringVar(value="mp3")btn_bar = tk.Frame(root)btn_bar.pack(fill=tk.X, padx=8, pady=4)tk.Button(btn_bar, text="Add Files", command=self.add_files).pack(side=tk.LEFT)tk.Button(btn_bar, text="Add Folder", command=self.add_folder).pack(side=tk.LEFT, padx=4)ttk.Combobox(btn_bar, textvariable=self.fmt, values=["mp3", "wav"],state="readonly", width=6).pack(side=tk.LEFT)self.listbox = tk.Listbox(root, selectmode=tk.EXTENDED)self.listbox.pack(fill=tk.BOTH, expand=True, padx=8)self.progress = ttk.Progressbar(root, maximum=100)self.progress.pack(fill=tk.X, padx=8, pady=4)self.btn_start = tk.Button(root, text="Start Conversion", command=self.start)self.btn_start.pack(padx=8, pady=4)tk.Label(root, textvariable=self.status, anchor="w").pack(fill=tk.X, padx=8, pady=4)def add_files(self):paths = filedialog.askopenfilenames(filetypes=[("Video files", "*.mp4 *.mkv *.mov *.avi *.flv")])self._add([Path(p) for p in paths])def add_folder(self):folder = filedialog.askdirectory()if folder:self._add(collect_videos([folder]))def _add(self, paths):if not paths:messagebox.showinfo("Notice", "No processable video files found.")returnfor p in paths:self.files.append(p)self.listbox.insert(tk.END, str(p))def start(self):ok, info = check_ffmpeg()if not ok:messagebox.showerror("Missing dependency", info)returnif not self.files:messagebox.showwarning("Notice", "The list is empty. Please import files first.")returnout_dir = filedialog.askdirectory(title="Choose output directory")if not out_dir:returnout_dir = Path(out_dir)out_dir.mkdir(parents=True, exist_ok=True)self.errors = []self.progress["value"] = 0self.btn_start.config(state=tk.DISABLED)threading.Thread(target=worker,args=(list(self.files), out_dir, self.fmt.get(), self.msg_queue),daemon=True,).start()self.root.after(100, self.poll_queue)def poll_queue(self):try:while True:kind, value = self.msg_queue.get_nowait()if kind == "progress":self.progress["value"] = valueelif kind == "status":self.status.set(value)elif kind == "error":self.errors.append(value)elif kind == "done":self.btn_start.config(state=tk.NORMAL)self.status.set("Done")if self.errors:messagebox.showwarning("Some files failed", "\n".join(self.errors[:20]))returnexcept queue.Empty:passself.root.after(100, self.poll_queue)if __name__ == "__main__":root = tk.Tk()root.title("Batch Audio Extraction")App(root)root.mainloop()
Three points are worth noting in this code. First, the worker thread only calls msg_queue.put and never touches any widget. Second, once poll_queue receives the done message, it stops scheduling further polls, so no stray timer tasks remain after the thread finishes. Third, a single failed file is only recorded in the error list — the batch continues.
5. Dependency Detection and Error Reporting
check_ffmpeg runs once when the user clicks “Start Conversion.” It first uses shutil.which to check whether the command exists; if not, it returns the reason immediately without executing anything. If found, it runs ffmpeg -version to read the version, with a 10-second timeout to prevent the command from hanging. On failure it shows messagebox.showerror while the button stays enabled, so the user can install the dependency and retry directly.
This check only covers the state at startup. If ffmpeg is deleted during conversion, subprocess.run raises OSError, which the worker’s except OSError catches to end the task.
6. Preventing Same-Name Overwrites
During batch processing, source files with identical names may exist in different folders, and the output directory may already contain old results. unique_path uses the original name if the target doesn’t exist; otherwise it tries suffixes like _1, _2 until it finds a free name. The -n flag in the ffmpeg command provides an additional layer of protection — even if a race occurs between two tasks’ checks, existing files will not be overwritten.
path.with_name is used instead of string concatenation to preserve the original directory and handle filenames containing multiple dots correctly.
7. Recursively Scanning Folders
collect_videos traverses subdirectories with os.walk and ignores directories without permission via the onerror callback. The reason is that Path.rglob may interrupt iteration and raise an exception when it hits a permission-denied subdirectory; if you use rglob, you need to wrap it in try statements yourself.
This code also handles two edge cases. First, when a folder is empty or contains no videos, _add shows a notice instead of displaying an empty list. Second, a corrupted video file cannot be decoded by ffmpeg, which returns a non-zero exit code; the worker records the error in the summary while the remaining files continue converting.
8. Prompt Structure Template
When working with a model, you can structure your requirements as follows. Each item maps to the acceptance criteria above, making it easier for the model to produce directly runnable code.
Role: You are an experienced Python desktop application engineer, familiar with tkinter, subprocess, and queue.Task: Build a batch audio extraction tool with tkinter. Output one complete, runnable Python file.Input: Video files or folders. Support mp4, mkv, mov, avi, flv; extension matching must be case-insensitive; folders must be scanned recursively.Output: mp3 or wav, saved to a user-selected directory.UI: File list, format dropdown, progress bar, status bar, start and exit buttons.Constraints:- Conversion runs in a worker thread; the worker must not touch widgets directly — communicate via queue and root.after.- Check for ffmpeg at startup; if missing, show a dialog instead of crashing.- Same-name output files get an appended sequence number; never overwrite existing files.- A single failed file must not interrupt the batch; summarize errors at the end.- Pass external command arguments as a list, not a concatenated string.- Output complete code, no pseudocode, with comments on key functions.Self-check list:- Does the program start and show a prompt when ffmpeg is not installed?- Do all widget updates happen on the main thread?- Is the start button re-enabled after tasks finish?- Will same-name files be overwritten?
When writing prompts, the two constraints most easily overlooked are “the worker thread must not touch widgets directly” and “pass arguments as a list.” Without explicit requirements, models tend to follow common examples and write code that modifies widgets directly.
9. Testing and Reproducibility Criteria
This article does not provide performance rankings or timing figures between models. If you want to compare different models, record the following: model name and version, the full prompt text, Python and ffmpeg versions, operating system, number of generations per model, whether each generated program launches, whether it completes one full conversion, and whether it passes the self-check list. Only with all of these conditions documented can others reproduce your results.
Generated code still requires human review. Focus on three categories of issues: whether paths and arguments are safe, whether exceptions are fully caught, and whether the UI behaves correctly with large files, corrupted files, and permission-denied directories.
10. Conclusion
LLMs reduce the amount of boilerplate you need to write, but details like dependency detection, thread communication, and error handling still require human verification. Writing acceptance criteria and constraints clearly usually brings model output closer to a usable state, and correspondingly reduces the changes needed during subsequent debugging.
