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:

    1. 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:

    1. The worker thread executes the subprocess call and puts progress and status into a queue.Queue.
    2. The main thread polls the queue with root.after and updates the UI with the retrieved messages.

    Full example:

    1. import os
    2. import queue
    3. import shutil
    4. import subprocess
    5. import threading
    6. import tkinter as tk
    7. from pathlib import Path
    8. from tkinter import filedialog, messagebox, ttk
    9. VIDEO_EXTS = {".mp4", ".mkv", ".mov", ".avi", ".flv"}
    10. def check_ffmpeg():
    11. """Check whether ffmpeg is available; return (ok, version info or error reason)."""
    12. if shutil.which("ffmpeg") is None:
    13. return False, "ffmpeg not found. Please install it and add its directory to PATH."
    14. try:
    15. result = subprocess.run(
    16. ["ffmpeg", "-version"],
    17. capture_output=True, text=True, timeout=10,
    18. )
    19. first_line = result.stdout.splitlines()[0] if result.stdout else "Unknown version"
    20. return True, first_line
    21. except (OSError, subprocess.TimeoutExpired) as exc:
    22. return False, f"Failed to invoke ffmpeg: {exc}"
    23. def unique_path(path: Path) -> Path:
    24. """If the target file exists, try name_1, name_2, etc."""
    25. if not path.exists():
    26. return path
    27. i = 1
    28. while True:
    29. candidate = path.with_name(f"{path.stem}_{i}{path.suffix}")
    30. if not candidate.exists():
    31. return candidate
    32. i += 1
    33. def collect_videos(paths):
    34. """Accept file or folder paths and return a list of Paths to all video files found."""
    35. found = []
    36. for raw in paths:
    37. p = Path(raw)
    38. if p.is_file() and p.suffix.lower() in VIDEO_EXTS:
    39. found.append(p)
    40. elif p.is_dir():
    41. for root_dir, _, names in os.walk(p, onerror=lambda e: None):
    42. for name in names:
    43. f = Path(root_dir) / name
    44. if f.suffix.lower() in VIDEO_EXTS:
    45. found.append(f)
    46. return found
    47. def worker(files, out_dir, fmt, msg_queue):
    48. """Convert files one by one in a worker thread; communicate with the UI only via the queue."""
    49. total = len(files)
    50. for idx, src in enumerate(files, start=1):
    51. msg_queue.put(("status", f"Processing {src.name} ({idx}/{total})"))
    52. dst = unique_path(out_dir / f"{src.stem}.{fmt}")
    53. # Pass arguments as a list, not a concatenated string, to avoid shell injection.
    54. # -n means never overwrite existing files, a second safeguard on top of unique_path.
    55. cmd = ["ffmpeg", "-n", "-i", str(src), "-vn", str(dst)]
    56. try:
    57. subprocess.run(cmd, check=True, capture_output=True, timeout=3600)
    58. except subprocess.CalledProcessError as exc:
    59. tail = exc.stderr.decode(errors="ignore")[-200:]
    60. msg_queue.put(("error", f"{src.name} conversion failed: {tail}"))
    61. except subprocess.TimeoutExpired:
    62. msg_queue.put(("error", f"{src.name} timed out, skipped"))
    63. except OSError as exc:
    64. # e.g., ffmpeg was deleted mid-conversion; no point continuing, end the task.
    65. msg_queue.put(("error", f"Cannot invoke ffmpeg: {exc}"))
    66. break
    67. msg_queue.put(("progress", idx / total * 100))
    68. msg_queue.put(("done", None))
    69. class App:
    70. def __init__(self, root):
    71. self.root = root
    72. self.msg_queue = queue.Queue()
    73. self.files = []
    74. self.errors = []
    75. self.status = tk.StringVar(value="Ready")
    76. self.fmt = tk.StringVar(value="mp3")
    77. btn_bar = tk.Frame(root)
    78. btn_bar.pack(fill=tk.X, padx=8, pady=4)
    79. tk.Button(btn_bar, text="Add Files", command=self.add_files).pack(side=tk.LEFT)
    80. tk.Button(btn_bar, text="Add Folder", command=self.add_folder).pack(side=tk.LEFT, padx=4)
    81. ttk.Combobox(btn_bar, textvariable=self.fmt, values=["mp3", "wav"],
    82. state="readonly", width=6).pack(side=tk.LEFT)
    83. self.listbox = tk.Listbox(root, selectmode=tk.EXTENDED)
    84. self.listbox.pack(fill=tk.BOTH, expand=True, padx=8)
    85. self.progress = ttk.Progressbar(root, maximum=100)
    86. self.progress.pack(fill=tk.X, padx=8, pady=4)
    87. self.btn_start = tk.Button(root, text="Start Conversion", command=self.start)
    88. self.btn_start.pack(padx=8, pady=4)
    89. tk.Label(root, textvariable=self.status, anchor="w").pack(fill=tk.X, padx=8, pady=4)
    90. def add_files(self):
    91. paths = filedialog.askopenfilenames(
    92. filetypes=[("Video files", "*.mp4 *.mkv *.mov *.avi *.flv")])
    93. self._add([Path(p) for p in paths])
    94. def add_folder(self):
    95. folder = filedialog.askdirectory()
    96. if folder:
    97. self._add(collect_videos([folder]))
    98. def _add(self, paths):
    99. if not paths:
    100. messagebox.showinfo("Notice", "No processable video files found.")
    101. return
    102. for p in paths:
    103. self.files.append(p)
    104. self.listbox.insert(tk.END, str(p))
    105. def start(self):
    106. ok, info = check_ffmpeg()
    107. if not ok:
    108. messagebox.showerror("Missing dependency", info)
    109. return
    110. if not self.files:
    111. messagebox.showwarning("Notice", "The list is empty. Please import files first.")
    112. return
    113. out_dir = filedialog.askdirectory(title="Choose output directory")
    114. if not out_dir:
    115. return
    116. out_dir = Path(out_dir)
    117. out_dir.mkdir(parents=True, exist_ok=True)
    118. self.errors = []
    119. self.progress["value"] = 0
    120. self.btn_start.config(state=tk.DISABLED)
    121. threading.Thread(
    122. target=worker,
    123. args=(list(self.files), out_dir, self.fmt.get(), self.msg_queue),
    124. daemon=True,
    125. ).start()
    126. self.root.after(100, self.poll_queue)
    127. def poll_queue(self):
    128. try:
    129. while True:
    130. kind, value = self.msg_queue.get_nowait()
    131. if kind == "progress":
    132. self.progress["value"] = value
    133. elif kind == "status":
    134. self.status.set(value)
    135. elif kind == "error":
    136. self.errors.append(value)
    137. elif kind == "done":
    138. self.btn_start.config(state=tk.NORMAL)
    139. self.status.set("Done")
    140. if self.errors:
    141. messagebox.showwarning("Some files failed", "\n".join(self.errors[:20]))
    142. return
    143. except queue.Empty:
    144. pass
    145. self.root.after(100, self.poll_queue)
    146. if __name__ == "__main__":
    147. root = tk.Tk()
    148. root.title("Batch Audio Extraction")
    149. App(root)
    150. 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.

    1. Role: You are an experienced Python desktop application engineer, familiar with tkinter, subprocess, and queue.
    2. Task: Build a batch audio extraction tool with tkinter. Output one complete, runnable Python file.
    3. Input: Video files or folders. Support mp4, mkv, mov, avi, flv; extension matching must be case-insensitive; folders must be scanned recursively.
    4. Output: mp3 or wav, saved to a user-selected directory.
    5. UI: File list, format dropdown, progress bar, status bar, start and exit buttons.
    6. Constraints:
    7. - Conversion runs in a worker thread; the worker must not touch widgets directly — communicate via queue and root.after.
    8. - Check for ffmpeg at startup; if missing, show a dialog instead of crashing.
    9. - Same-name output files get an appended sequence number; never overwrite existing files.
    10. - A single failed file must not interrupt the batch; summarize errors at the end.
    11. - Pass external command arguments as a list, not a concatenated string.
    12. - Output complete code, no pseudocode, with comments on key functions.
    13. Self-check list:
    14. - Does the program start and show a prompt when ffmpeg is not installed?
    15. - Do all widget updates happen on the main thread?
    16. - Is the start button re-enabled after tasks finish?
    17. - 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.