zach commited on
Commit
605e635
·
1 Parent(s): 3f2c59d

Add logic to clean up temp audio files on application exit

Browse files
Files changed (1) hide show
  1. src/config.py +34 -0
src/config.py CHANGED
@@ -10,8 +10,10 @@ Key Features:
10
  """
11
 
12
  # Standard Library Imports
 
13
  import logging
14
  import os
 
15
 
16
  # Third-Party Library Imports
17
  from dotenv import load_dotenv
@@ -43,3 +45,35 @@ if DEBUG:
43
  AUDIO_DIR = os.path.join(os.getcwd(), "static", "audio")
44
  os.makedirs(AUDIO_DIR, exist_ok=True)
45
  logger.info(f"Audio directory set to {AUDIO_DIR}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  """
11
 
12
  # Standard Library Imports
13
+ import atexit
14
  import logging
15
  import os
16
+ import shutil
17
 
18
  # Third-Party Library Imports
19
  from dotenv import load_dotenv
 
45
  AUDIO_DIR = os.path.join(os.getcwd(), "static", "audio")
46
  os.makedirs(AUDIO_DIR, exist_ok=True)
47
  logger.info(f"Audio directory set to {AUDIO_DIR}")
48
+
49
+
50
+ def cleanup_audio_directory_contents() -> None:
51
+ """
52
+ Delete all audio files within AUDIO_DIR, leaving the directory intact.
53
+
54
+ This function is intended to be registered to run when the application exits.
55
+ It assumes that AUDIO_DIR contains only audio files (or symbolic links), and no subdirectories.
56
+ """
57
+ if not os.path.exists(AUDIO_DIR):
58
+ logger.info(
59
+ "Audio directory %s does not exist. Nothing to clean up.", AUDIO_DIR
60
+ )
61
+ return
62
+
63
+ # Use os.scandir for efficient directory iteration.
64
+ with os.scandir(AUDIO_DIR) as entries:
65
+ for entry in entries:
66
+ if entry.is_file() or entry.is_symlink():
67
+ try:
68
+ os.unlink(entry.path)
69
+ logger.info("Deleted file: %s", entry.path)
70
+ except Exception as exc:
71
+ logger.error(
72
+ "Failed to delete file %s. Reason: %s", entry.path, exc
73
+ )
74
+ else:
75
+ logger.warning("Skipping non-file entry: %s", entry.path)
76
+
77
+
78
+ # Register the cleanup function to be called on normal program termination.
79
+ atexit.register(cleanup_audio_directory_contents)