|
| 1 | +import io |
| 2 | +import tempfile |
| 3 | +from typing import List |
| 4 | +import logging |
| 5 | +from starlette.datastructures import UploadFile as StarletteUploadFile |
| 6 | +import requests |
| 7 | +from advanced_omi_backend.app_config import get_app_config |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | +audio_logger = logging.getLogger("audio_processing") |
| 11 | + |
| 12 | +AUDIO_EXTENSIONS = (".wav", ".mp3", ".flac", ".ogg", ".m4a") |
| 13 | + |
| 14 | +class AudioValidationError(Exception): |
| 15 | + pass |
| 16 | + |
| 17 | + |
| 18 | +async def download_and_wrap_dropbox_file(file_metadata: dict): |
| 19 | + access_token = get_app_config().dropbox_access_token |
| 20 | + if not access_token: |
| 21 | + raise AudioValidationError("Dropbox access token is missing.") |
| 22 | + |
| 23 | + file_path = file_metadata["path_lower"] |
| 24 | + name = file_metadata["name"] |
| 25 | + |
| 26 | + headers = { |
| 27 | + "Authorization": f"Bearer {access_token}", |
| 28 | + "Dropbox-API-Arg": f'{{"path": "{file_path}"}}' |
| 29 | + } |
| 30 | + |
| 31 | + response = requests.post( |
| 32 | + "https://content.dropboxapi.com/2/files/download", |
| 33 | + headers=headers |
| 34 | + ) |
| 35 | + |
| 36 | + if response.status_code != 200: |
| 37 | + raise AudioValidationError( |
| 38 | + f"Failed to download Dropbox file {name}: {response.text}" |
| 39 | + ) |
| 40 | + |
| 41 | + content = response.content |
| 42 | + if not content: |
| 43 | + raise AudioValidationError(f"Downloaded Dropbox file '{name}' was empty") |
| 44 | + |
| 45 | + tmp_file = tempfile.SpooledTemporaryFile(max_size=10 * 1024 * 1024) |
| 46 | + tmp_file.write(content) |
| 47 | + tmp_file.seek(0) |
| 48 | + |
| 49 | + upload_file = StarletteUploadFile(filename=name, file=tmp_file) |
| 50 | + |
| 51 | + original_close = upload_file.close |
| 52 | + |
| 53 | + def wrapped_close(): |
| 54 | + try: |
| 55 | + original_close() |
| 56 | + finally: |
| 57 | + pass |
| 58 | + |
| 59 | + upload_file.close = wrapped_close |
| 60 | + return upload_file |
| 61 | + |
| 62 | + |
| 63 | +async def download_audio_files_from_dropbox(folder_path: str) -> List[StarletteUploadFile]: |
| 64 | + if not folder_path: |
| 65 | + raise AudioValidationError("Dropbox folder path is required.") |
| 66 | + |
| 67 | + access_token = get_app_config().dropbox_access_token |
| 68 | + if not access_token: |
| 69 | + raise AudioValidationError("Dropbox access token is missing.") |
| 70 | + |
| 71 | + try: |
| 72 | + # ----------------------------------------------- |
| 73 | + # Step 1: List files in folder |
| 74 | + # ----------------------------------------------- |
| 75 | + list_headers = { |
| 76 | + "Authorization": f"Bearer {access_token}", |
| 77 | + "Content-Type": "application/json" |
| 78 | + } |
| 79 | + |
| 80 | + list_body = { |
| 81 | + "path": folder_path, |
| 82 | + "recursive": False |
| 83 | + } |
| 84 | + |
| 85 | + list_res = requests.post( |
| 86 | + "https://api.dropboxapi.com/2/files/list_folder", |
| 87 | + headers=list_headers, |
| 88 | + json=list_body |
| 89 | + ) |
| 90 | + |
| 91 | + if list_res.status_code != 200: |
| 92 | + raise AudioValidationError(f"Dropbox API list_folder error: {list_res.text}") |
| 93 | + |
| 94 | + items = list_res.json().get("entries", []) |
| 95 | + |
| 96 | + # Filter audio files |
| 97 | + audio_files_metadata = [ |
| 98 | + f for f in items |
| 99 | + if f[".tag"] == "file" and f["name"].lower().endswith(AUDIO_EXTENSIONS) |
| 100 | + ] |
| 101 | + |
| 102 | + if not audio_files_metadata: |
| 103 | + raise AudioValidationError("No audio files found in folder.") |
| 104 | + |
| 105 | + wrapped_files = [] |
| 106 | + skipped_count = 0 |
| 107 | + |
| 108 | + # ----------------------------------------------- |
| 109 | + # Step 2: Download each audio file |
| 110 | + # ----------------------------------------------- |
| 111 | + for item in audio_files_metadata: |
| 112 | + dropbox_id = item["id"] # Dropbox file ID |
| 113 | + |
| 114 | + # Check if already processed |
| 115 | + if await is_dropbox_file_already_processed(dropbox_id): |
| 116 | + audio_logger.info(f"Skipping already processed file: {item['name']}") |
| 117 | + skipped_count += 1 |
| 118 | + continue |
| 119 | + |
| 120 | + wrapped_file = await download_and_wrap_dropbox_file(access_token, item) |
| 121 | + |
| 122 | + # Attach Dropbox file ID |
| 123 | + setattr(wrapped_file, "dropbox_file_id", dropbox_id) |
| 124 | + |
| 125 | + wrapped_files.append(wrapped_file) |
| 126 | + |
| 127 | + if not wrapped_files and skipped_count > 0: |
| 128 | + raise AudioValidationError( |
| 129 | + f"All {skipped_count} files in the folder have already been processed." |
| 130 | + ) |
| 131 | + |
| 132 | + return wrapped_files |
| 133 | + |
| 134 | + except Exception as e: |
| 135 | + if isinstance(e, AudioValidationError): |
| 136 | + raise |
| 137 | + raise AudioValidationError(f"Dropbox API Error: {e}") from e |
| 138 | + |
| 139 | + |
| 140 | +async def is_dropbox_file_already_processed(dropbox_file_id: str) -> bool: |
| 141 | + if not dropbox_file_id: |
| 142 | + return False |
| 143 | + |
| 144 | + from advanced_omi_backend.models.audio_file import AudioFile |
| 145 | + |
| 146 | + existing_file = await AudioFile.find_one( |
| 147 | + AudioFile.dropbox_file_id == dropbox_file_id |
| 148 | + ) |
| 149 | + |
| 150 | + return existing_file is not None |
0 commit comments