|
1 | 1 | import base64 |
| 2 | +import logging |
2 | 3 | import os |
3 | 4 | import platform |
4 | 5 | import subprocess |
|
7 | 8 | import httpx |
8 | 9 | from cache_to_disk import cache_to_disk |
9 | 10 |
|
| 11 | +# Configure logging |
| 12 | +logging.basicConfig(level=logging.INFO) |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class AudioGenerationError(Exception): |
| 17 | + """Custom exception for errors during audio generation.""" |
| 18 | + |
| 19 | + pass |
| 20 | + |
10 | 21 |
|
11 | 22 | def encode(content: bytes) -> str: |
12 | 23 | encoded_content = base64.b64encode(content).decode("utf-8") |
@@ -41,12 +52,25 @@ def generate_audio_mac_wav(prompt: str) -> bytes: |
41 | 52 | # Read the WAV file into memory |
42 | 53 | with open(temp_wav_path, "rb") as f: |
43 | 54 | audio_bytes = f.read() |
| 55 | + |
| 56 | + except subprocess.CalledProcessError as e: |
| 57 | + logger.error(f"Subprocess error: {e}") |
| 58 | + raise AudioGenerationError("Failed to generate or convert audio.") from e |
| 59 | + except FileNotFoundError as e: |
| 60 | + logger.error(f"File not found: {e}") |
| 61 | + raise AudioGenerationError("Required file not found.") from e |
| 62 | + except Exception as e: |
| 63 | + logger.exception("Unexpected error occurred.") |
| 64 | + raise AudioGenerationError( |
| 65 | + "An unexpected error occurred during audio generation." |
| 66 | + ) from e |
44 | 67 | finally: |
45 | | - # Clean up the temporary files |
46 | | - if os.path.exists(temp_aiff_path): |
47 | | - os.remove(temp_aiff_path) |
48 | | - if os.path.exists(temp_wav_path): |
49 | | - os.remove(temp_wav_path) |
| 68 | + for path in (temp_aiff_path, temp_wav_path): |
| 69 | + try: |
| 70 | + if os.path.exists(path): |
| 71 | + os.remove(path) |
| 72 | + except Exception as e: |
| 73 | + logger.warning(f"Failed to delete temporary file {path}: {e}") |
50 | 74 |
|
51 | 75 | # Return the audio bytes |
52 | 76 | return audio_bytes |
|
0 commit comments