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 tkinter does 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:

    1. Role: Senior Python desktop development engineer
    2. Goal: Develop a batch video and audio extraction tool
    3. Tech stack: Python 3, tkinter, call ffmpeg through subprocess
    4. Features:
    5. 1. Support importing common video formats (list specific extensions) and support importing an entire folder (recursive)
    6. 2. Export MP3 and WAV; the user can select the output format
    7. 3. The file list supports adding and removing files
    8. 4. Provide buttons for import, output directory selection, start conversion, and exit
    9. Constraints:
    10. - Run time-consuming conversions in a worker thread; update UI controls only in the main thread
    11. - Include a progress bar and status bar, and show clear prompts on errors
    12. - Check whether ffmpeg is available before starting conversion
    13. - Check whether the output directory exists and is writable before starting conversion
    14. - Automatically number output files with the same name and do not overwrite existing files
    15. - Delete incomplete output files produced by a failed conversion
    16. Output: 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.

    1. import os
    2. import queue
    3. import shutil
    4. import subprocess
    5. import threading
    6. import tkinter as tk
    7. from tkinter import ttk, filedialog, messagebox
    8. VIDEO_EXTS = (".mp4", ".mkv", ".mov", ".avi", ".flv", ".wmv", ".webm", ".m4v")
    9. OUTPUT_FORMATS = ("mp3", "wav")
    10. def check_ffmpeg():
    11. return shutil.which("ffmpeg") is not None
    12. def check_writable_dir(path):
    13. return bool(path) and os.path.isdir(path) and os.access(path, os.W_OK)
    14. def unique_path(path):
    15. base, ext = os.path.splitext(path)
    16. candidate, n = path, 1
    17. while os.path.exists(candidate):
    18. candidate = f"{base}_{n}{ext}"
    19. n += 1
    20. return candidate
    21. class ConverterApp:
    22. def __init__(self, root):
    23. self.root = root
    24. self.root.title("Audio Extractor")
    25. self.files = []
    26. self.output_dir = ""
    27. self.messages = queue.Queue()
    28. self.worker = None
    29. self.status = tk.StringVar(value="Ready")
    30. bar = tk.Frame(root)
    31. bar.pack(fill="x", padx=10, pady=5)
    32. tk.Button(bar, text="Import Files", command=self.import_files).pack(side="left")
    33. tk.Button(bar, text="Import Folder", command=self.import_folder).pack(side="left", padx=5)
    34. tk.Button(bar, text="Remove Selected", command=self.remove_selected).pack(side="left")
    35. tk.Button(bar, text="Choose Output Directory", command=self.choose_output).pack(side="left")
    36. tk.Button(bar, text="Exit", command=root.destroy).pack(side="right")
    37. self.listbox = tk.Listbox(root, height=10)
    38. self.listbox.pack(fill="both", expand=True, padx=10)
    39. opts = tk.Frame(root)
    40. opts.pack(fill="x", padx=10, pady=5)
    41. tk.Label(opts, text="Output format:").pack(side="left")
    42. self.fmt = ttk.Combobox(opts, values=[f.upper() for f in OUTPUT_FORMATS],
    43. state="readonly", width=8)
    44. self.fmt.set("MP3")
    45. self.fmt.pack(side="left")
    46. self.start_btn = tk.Button(opts, text="Start Conversion", command=self.start)
    47. self.start_btn.pack(side="right")
    48. self.progress = ttk.Progressbar(root, maximum=100)
    49. self.progress.pack(fill="x", padx=10, pady=5)
    50. tk.Label(root, textvariable=self.status, anchor="w").pack(
    51. fill="x", padx=10, pady=(0, 10))
    52. self.root.after(100, self.poll_messages)
    53. def is_running(self):
    54. return self.worker is not None and self.worker.is_alive()
    55. def add_files(self, paths):
    56. for p in paths:
    57. if p.lower().endswith(VIDEO_EXTS) and p not in self.files:
    58. self.files.append(p)
    59. self.listbox.insert("end", p)
    60. def import_files(self):
    61. if self.is_running():
    62. return
    63. pattern = " ".join(f"*{e}" for e in VIDEO_EXTS)
    64. paths = filedialog.askopenfilenames(
    65. filetypes=[("Video files", pattern), ("All files", "*.*")])
    66. self.add_files(paths)
    67. def import_folder(self):
    68. if self.is_running():
    69. return
    70. folder = filedialog.askdirectory()
    71. if not folder:
    72. return
    73. found = []
    74. for dirpath, _, names in os.walk(folder):
    75. for name in names:
    76. found.append(os.path.join(dirpath, name))
    77. self.add_files(found)
    78. def remove_selected(self):
    79. if self.is_running():
    80. return
    81. for i in reversed(self.listbox.curselection()):
    82. del self.files[i]
    83. self.listbox.delete(i)
    84. def choose_output(self):
    85. if self.is_running():
    86. return
    87. folder = filedialog.askdirectory()
    88. if folder:
    89. self.output_dir = folder
    90. self.status.set(f"Output directory: {folder}")
    91. def start(self):
    92. if self.is_running():
    93. return
    94. if not self.files:
    95. messagebox.showinfo("Notice", "Please import files first.")
    96. return
    97. if not check_ffmpeg():
    98. messagebox.showerror("Missing dependency", "ffmpeg was not found. Install it and add it to the system PATH.")
    99. return
    100. if not self.output_dir:
    101. messagebox.showinfo("Notice", "Please select an output directory first.")
    102. return
    103. if not check_writable_dir(self.output_dir):
    104. messagebox.showerror("Output directory unavailable", "The output directory does not exist or is not writable.")
    105. return
    106. self.start_btn.config(state="disabled")
    107. self.progress["value"] = 0
    108. self.status.set("Starting conversion...")
    109. self.worker = threading.Thread(
    110. target=self.convert_files,
    111. args=(list(self.files), self.fmt.get().lower(), self.output_dir),
    112. daemon=True)
    113. self.worker.start()
    114. def convert_files(self, files, fmt, out_dir):
    115. # The worker thread does not access widgets; it sends messages through a queue.
    116. total = len(files)
    117. errors = []
    118. for i, src in enumerate(files, start=1):
    119. name = os.path.splitext(os.path.basename(src))[0]
    120. dst = unique_path(os.path.join(out_dir, f"{name}.{fmt}"))
    121. self.messages.put(("status", f"Converting {i}/{total}: {os.path.basename(src)}"))
    122. cmd = ["ffmpeg", "-nostdin", "-loglevel", "error", "-i", src, "-vn", dst]
    123. try:
    124. subprocess.run(cmd, capture_output=True,
    125. encoding="utf-8", errors="replace", check=True)
    126. except subprocess.CalledProcessError as e:
    127. errors.append(f"{os.path.basename(src)}: {e.stderr.strip()[-200:]}")
    128. # dst is a new file chosen by unique_path; delete partial output on failure.
    129. if os.path.exists(dst):
    130. os.remove(dst)
    131. except OSError as e:
    132. errors.append(f"{os.path.basename(src)}: {e}")
    133. break
    134. self.messages.put(("progress", i * 100 / total))
    135. self.messages.put(("done", errors))
    136. def poll_messages(self):
    137. try:
    138. while True:
    139. kind

    The source excerpt ends at this point; the message-polling method is not shown in full in the original material.