AI-Generated Python Tkinter FFmpeg Batch Audio Extractor: A Practical Test of Requirements, Threading, and UI Responsiveness
This article describes a single-task test of an AI coding model building a Python/tkinter batch video-to-audio extractor that calls ffmpeg. It covers prerequisites, an acceptance checklist, prompt construction, review of the generated behavior, threading and UI update risks, and a reference implementation. The goal is to show how to verify runnable code, simultaneous constraints, and non-freezing GUI behavior rather than to present benchmark data.
1. Why This Test
When developers evaluate AI coding capability, they usually ask three things: Can the generated code run directly? Can multiple constraints be satisfied at the same time? Can the program avoid the most common GUI problem, interface freezing? This test focuses on those three questions.
The test task is complex enough to examine the model’s engineering judgment. Note that this article does not cite external benchmark data. All observations come from the same task and the same generation. A single result cannot prove the model’s general capability, and readers should repeat the verification in their own projects.
2. Test Task and Prerequisites
The task is to develop a batch video and audio extraction tool using Python and tkinter. The tool should import common video files, export MP3 or WAV, and provide entry points for a file list, output format selection, file import, start conversion, and exit. The interface should include a progress bar and a status bar, show clear prompts when errors occur, and remain responsive during conversion.
Three conditions must be met before running:
- Python 3 is installed, and
import tkinterdoes not report an error. Some Linux distributions require installing the tkinter package separately. - ffmpeg is installed and can be called directly from the terminal.
- An output directory is prepared, and the current user has write permission for that directory.
3. Requirements Acceptance Checklist
Before checking the generated result, break the requirements into items that can be verified one by one. The following table can be reused directly:
| Requirement | Verification method |
|---|---|
| Import common video formats | Import mp4, mkv, mov, and other files separately, and confirm that all of them enter the list |
| Import folders | Import a directory containing subfolders, and confirm that videos in subdirectories are also added to the list |
| Export MP3 and WAV | Select both formats for the same video and check whether the output files can be played |
| File list and format settings | Add and remove files, switch the output format, and confirm that the state is correct |
| Do not overwrite files with the same name | Convert the same source file twice in a row, and confirm that a numbered new file is generated while the old file remains unchanged |
| Output directory writable | Select a read-only directory and start conversion, and confirm that a clear prompt appears |
| Progress bar and status bar | Observe during batch conversion whether the progress increases and the status text updates |
| Error prompts | Use a damaged file or a file with no audio track, and confirm that a clear prompt appears |
| UI does not freeze | Drag the window and click buttons during conversion; the interface should remain responsive |
| Dependency detection | Temporarily remove ffmpeg from PATH, and a prompt should appear when conversion starts |
Each item in the table needs to be verified through actual operation, not just by checking whether code exists. For example, “UI does not freeze” must be verified by actually dragging the window and clicking buttons during conversion and observing whether the interface responds.
4. Prompt Construction
We organized the requirements into a structured prompt and submitted it once to the platform’s integrated development environment. The model’s processing flow was requirement parsing, code generation, syntax validation and environment checking, and functional description output. The original article recorded a total time of about ten minutes, including environment checking. That is only a single observation and should not be treated as general data.
When writing the prompt, specify extensions, output directory rules, and error handling as clearly as possible. Models often follow the literal wording of a prompt, and constraints that are not written are easy to miss. The following is a template for reference:
Role: Senior Python desktop development engineerGoal: Develop a batch video and audio extraction toolTech stack: Python 3, tkinter, call ffmpeg through subprocessFeatures:1. Support importing common video formats (list specific extensions) and support importing an entire folder (recursive)2. Export MP3 and WAV; the user can select the output format3. The file list supports adding and removing files4. Provide buttons for import, output directory selection, start conversion, and exitConstraints:- Run time-consuming conversions in a worker thread; update UI controls only in the main thread- Include a progress bar and status bar, and show clear prompts on errors- Check whether ffmpeg is available before starting conversion- Check whether the output directory exists and is writable before starting conversion- Automatically number output files with the same name and do not overwrite existing files- Delete incomplete output files produced by a failed conversionOutput: Complete runnable code with a functional description and dependency installation steps
5. Reviewing the Generated Result
Based on the functional description in the original article, the model added several details that were not explicitly mentioned in the original requirements: recursive directory recognition to batch-import content from subfolders; automatic completion of the support list for common video and audio formats; automatic numbering for output files with the same name; and checking whether ffmpeg is installed before conversion. These details show that the model adds engineering handling that is reasonable for the use case, but the added content also needs verification.
Passing syntax validation does not mean the functionality is correct. The code shown in the original article only reaches the point where the thread starts; the main conversion flow is not fully presented. Therefore, it cannot be concluded that “none of the requirement items were missed.” To confirm functionality, at least three things are needed. First, run the program, export MP3 and WAV once each using mp4, mkv, mov, and other samples, and check the results with a player. Second, trigger error prompts with damaged files and files that have no audio track. Third, temporarily modify PATH to verify whether dependency detection works. Verification results should be saved as run logs or screenshots and attached as evidence.
6. Threading and UI Updates
The model puts time-consuming tasks in a worker thread, which is the right direction. However, how the worker thread updates the interface determines whether the program will fail. tkinter widgets are not thread-safe. If a worker thread directly modifies the progress bar or label text, it may cause program exceptions or interface corruption.
A safer approach has two parts. The worker thread only calls ffmpeg and puts messages into a queue after each step. The main thread periodically reads the queue through root.after, then updates the progress bar, status bar, and button state. In this way, widgets are accessed only in the main thread, and the interface does not freeze while waiting for conversion results.
The following is the reference implementation used in this article. It covers import, removal, output directory selection, dependency checking, output directory checking, overwrite prevention, error collection, and progress updates. The code does not come with run records on a specific system, and readers should verify it in their own environment before using it.
import osimport queueimport shutilimport subprocessimport threadingimport tkinter as tkfrom tkinter import ttk, filedialog, messageboxVIDEO_EXTS = (".mp4", ".mkv", ".mov", ".avi", ".flv", ".wmv", ".webm", ".m4v")OUTPUT_FORMATS = ("mp3", "wav")def check_ffmpeg():return shutil.which("ffmpeg") is not Nonedef check_writable_dir(path):return bool(path) and os.path.isdir(path) and os.access(path, os.W_OK)def unique_path(path):base, ext = os.path.splitext(path)candidate, n = path, 1while os.path.exists(candidate):candidate = f"{base}_{n}{ext}"n += 1return candidateclass ConverterApp:def __init__(self, root):self.root = rootself.root.title("Audio Extractor")self.files = []self.output_dir = ""self.messages = queue.Queue()self.worker = Noneself.status = tk.StringVar(value="Ready")bar = tk.Frame(root)bar.pack(fill="x", padx=10, pady=5)tk.Button(bar, text="Import Files", command=self.import_files).pack(side="left")tk.Button(bar, text="Import Folder", command=self.import_folder).pack(side="left", padx=5)tk.Button(bar, text="Remove Selected", command=self.remove_selected).pack(side="left")tk.Button(bar, text="Choose Output Directory", command=self.choose_output).pack(side="left")tk.Button(bar, text="Exit", command=root.destroy).pack(side="right")self.listbox = tk.Listbox(root, height=10)self.listbox.pack(fill="both", expand=True, padx=10)opts = tk.Frame(root)opts.pack(fill="x", padx=10, pady=5)tk.Label(opts, text="Output format:").pack(side="left")self.fmt = ttk.Combobox(opts, values=[f.upper() for f in OUTPUT_FORMATS],state="readonly", width=8)self.fmt.set("MP3")self.fmt.pack(side="left")self.start_btn = tk.Button(opts, text="Start Conversion", command=self.start)self.start_btn.pack(side="right")self.progress = ttk.Progressbar(root, maximum=100)self.progress.pack(fill="x", padx=10, pady=5)tk.Label(root, textvariable=self.status, anchor="w").pack(fill="x", padx=10, pady=(0, 10))self.root.after(100, self.poll_messages)def is_running(self):return self.worker is not None and self.worker.is_alive()def add_files(self, paths):for p in paths:if p.lower().endswith(VIDEO_EXTS) and p not in self.files:self.files.append(p)self.listbox.insert("end", p)def import_files(self):if self.is_running():returnpattern = " ".join(f"*{e}" for e in VIDEO_EXTS)paths = filedialog.askopenfilenames(filetypes=[("Video files", pattern), ("All files", "*.*")])self.add_files(paths)def import_folder(self):if self.is_running():returnfolder = filedialog.askdirectory()if not folder:returnfound = []for dirpath, _, names in os.walk(folder):for name in names:found.append(os.path.join(dirpath, name))self.add_files(found)def remove_selected(self):if self.is_running():returnfor i in reversed(self.listbox.curselection()):del self.files[i]self.listbox.delete(i)def choose_output(self):if self.is_running():returnfolder = filedialog.askdirectory()if folder:self.output_dir = folderself.status.set(f"Output directory: {folder}")def start(self):if self.is_running():returnif not self.files:messagebox.showinfo("Notice", "Please import files first.")returnif not check_ffmpeg():messagebox.showerror("Missing dependency", "ffmpeg was not found. Install it and add it to the system PATH.")returnif not self.output_dir:messagebox.showinfo("Notice", "Please select an output directory first.")returnif not check_writable_dir(self.output_dir):messagebox.showerror("Output directory unavailable", "The output directory does not exist or is not writable.")returnself.start_btn.config(state="disabled")self.progress["value"] = 0self.status.set("Starting conversion...")self.worker = threading.Thread(target=self.convert_files,args=(list(self.files), self.fmt.get().lower(), self.output_dir),daemon=True)self.worker.start()def convert_files(self, files, fmt, out_dir):# The worker thread does not access widgets; it sends messages through a queue.total = len(files)errors = []for i, src in enumerate(files, start=1):name = os.path.splitext(os.path.basename(src))[0]dst = unique_path(os.path.join(out_dir, f"{name}.{fmt}"))self.messages.put(("status", f"Converting {i}/{total}: {os.path.basename(src)}"))cmd = ["ffmpeg", "-nostdin", "-loglevel", "error", "-i", src, "-vn", dst]try:subprocess.run(cmd, capture_output=True,encoding="utf-8", errors="replace", check=True)except subprocess.CalledProcessError as e:errors.append(f"{os.path.basename(src)}: {e.stderr.strip()[-200:]}")# dst is a new file chosen by unique_path; delete partial output on failure.if os.path.exists(dst):os.remove(dst)except OSError as e:errors.append(f"{os.path.basename(src)}: {e}")breakself.messages.put(("progress", i * 100 / total))self.messages.put(("done", errors))def poll_messages(self):try:while True:kind
The source excerpt ends at this point; the message-polling method is not shown in full in the original material.
