|
| 1 | +import io |
| 2 | +import os |
| 3 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 4 | +from typing import Any, Dict, List, Optional |
| 5 | + |
| 6 | +from app.config import SCOPES, SERVICE_ACCOUNT_FILE_PATH |
| 7 | +from app.utils import setup_logger |
| 8 | +from google.oauth2 import service_account |
| 9 | +from googleapiclient.discovery import build |
| 10 | +from googleapiclient.http import MediaIoBaseDownload |
| 11 | + |
| 12 | +logger = setup_logger() |
| 13 | + |
| 14 | + |
| 15 | +def extract_file_id(gdrive_url: str) -> str: |
| 16 | + if "id=" in gdrive_url: |
| 17 | + file_id = gdrive_url.split("id=")[1].split("&")[0] |
| 18 | + if file_id: |
| 19 | + return file_id |
| 20 | + else: |
| 21 | + raise ValueError( |
| 22 | + "Invalid Google Drive URL format: missing file ID after 'id='." |
| 23 | + ) |
| 24 | + else: |
| 25 | + parts = gdrive_url.strip("/").split("/") |
| 26 | + if "d" in parts: |
| 27 | + d_index = parts.index("d") |
| 28 | + try: |
| 29 | + file_id = parts[d_index + 1] |
| 30 | + if file_id: |
| 31 | + return file_id |
| 32 | + else: |
| 33 | + raise ValueError( |
| 34 | + "Invalid Google Drive URL format: missing file ID after '/d/'." |
| 35 | + ) |
| 36 | + except IndexError as e: |
| 37 | + raise ValueError( |
| 38 | + "Invalid Google Drive URL format: incomplete URL." |
| 39 | + ) from e |
| 40 | + else: |
| 41 | + raise ValueError( |
| 42 | + """URL format not recognized. Ensure it contains 'id=' or follows the |
| 43 | + standard Drive URL format.""" |
| 44 | + ) |
| 45 | + |
| 46 | + |
| 47 | +def determine_file_type(file_name: str) -> str: |
| 48 | + _, ext = os.path.splitext(file_name.lower()) |
| 49 | + if ext == ".pdf": |
| 50 | + return "pdf" |
| 51 | + elif ext == ".xlsx": |
| 52 | + return "xlsx" |
| 53 | + else: |
| 54 | + return "other" |
| 55 | + |
| 56 | + |
| 57 | +def download_file(file_id: str) -> Optional[io.BytesIO]: |
| 58 | + """ |
| 59 | + Download a file from Google Drive using the Drive API. |
| 60 | + """ |
| 61 | + creds = service_account.Credentials.from_service_account_file( |
| 62 | + SERVICE_ACCOUNT_FILE_PATH, scopes=SCOPES |
| 63 | + ) |
| 64 | + drive_service = build("drive", "v3", credentials=creds) |
| 65 | + try: |
| 66 | + request = drive_service.files().get_media(fileId=file_id) |
| 67 | + file_buffer = io.BytesIO() |
| 68 | + downloader = MediaIoBaseDownload(file_buffer, request) |
| 69 | + done = False |
| 70 | + while not done: |
| 71 | + status, done = downloader.next_chunk() |
| 72 | + if file_buffer.getbuffer().nbytes == 0: |
| 73 | + raise RuntimeError("No content was downloaded from the file.") |
| 74 | + file_buffer.seek(0) |
| 75 | + return file_buffer |
| 76 | + except Exception as e: |
| 77 | + logger.error(f"Error downloading file with ID '{file_id}': {e}") |
| 78 | + return None |
| 79 | + |
| 80 | + |
| 81 | +def download_file_wrapper(record: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| 82 | + """A wrapper function to process each record and download its file.""" |
| 83 | + try: |
| 84 | + fields = record.get("fields", {}) |
| 85 | + gdrive_link = fields.get("Drive link") |
| 86 | + file_name = fields.get("File name") |
| 87 | + document_id = fields.get("ID") |
| 88 | + survey_name = fields.get("Survey name") |
| 89 | + description = fields.get("Description") |
| 90 | + |
| 91 | + if not gdrive_link or not file_name: |
| 92 | + logger.error("Record is missing 'Drive link' or 'File name'") |
| 93 | + return None |
| 94 | + |
| 95 | + # Check if the file is a PDF (we only want to process PDFs) |
| 96 | + file_type = determine_file_type(file_name) |
| 97 | + if file_type != "pdf": |
| 98 | + logger.info(f"Skipping non-PDF file: '{file_name}'") |
| 99 | + return None |
| 100 | + |
| 101 | + file_id = extract_file_id(gdrive_link) |
| 102 | + if not file_id: |
| 103 | + logger.error(f"Could not extract file ID from link '{gdrive_link}'") |
| 104 | + return None |
| 105 | + |
| 106 | + logger.info(f"Starting download of file '{file_name}'") |
| 107 | + file_buffer = download_file(file_id) |
| 108 | + if file_buffer is None: |
| 109 | + logger.error(f"Failed to download file '{file_name}'") |
| 110 | + return None |
| 111 | + |
| 112 | + logger.info(f"Completed download of file '{file_name}'") |
| 113 | + return { |
| 114 | + "file_name": file_name, |
| 115 | + "file_buffer": file_buffer, |
| 116 | + "file_type": file_type, |
| 117 | + "document_id": document_id, |
| 118 | + "survey_name": survey_name, |
| 119 | + "summary": description, |
| 120 | + "fields": fields, |
| 121 | + } |
| 122 | + except Exception as e: |
| 123 | + logger.error(f"Error downloading file '{file_name}': {e}") |
| 124 | + return None |
| 125 | + |
| 126 | + |
| 127 | +def download_all_files( |
| 128 | + records: List[Dict[str, Any]], n_max_workers: int |
| 129 | +) -> List[Dict[str, Any]]: |
| 130 | + """Download all files concurrently using ThreadPoolExecutor.""" |
| 131 | + downloaded_files = [] |
| 132 | + |
| 133 | + with ThreadPoolExecutor(max_workers=n_max_workers) as executor: |
| 134 | + # Map each record to a future |
| 135 | + future_to_record = { |
| 136 | + executor.submit(download_file_wrapper, record): record for record in records |
| 137 | + } |
| 138 | + |
| 139 | + for future in as_completed(future_to_record): |
| 140 | + record = future_to_record[future] |
| 141 | + file_name = record.get("fields", {}).get("File name", "Unknown") |
| 142 | + try: |
| 143 | + result = future.result() |
| 144 | + if result is not None: |
| 145 | + downloaded_files.append(result) |
| 146 | + except Exception as e: |
| 147 | + logger.error(f"Error downloading file '{file_name}': {e}") |
| 148 | + |
| 149 | + return downloaded_files |
0 commit comments