""" Utilitaires de stockage pour le worker """ import os import tempfile from minio import Minio from minio.error import S3Error import logging logger = logging.getLogger(__name__) # Configuration MinIO MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "localhost:9000") MINIO_ACCESS_KEY = os.getenv("MINIO_ROOT_USER", "minio") MINIO_SECRET_KEY = os.getenv("MINIO_ROOT_PASSWORD", "minio_pwd") MINIO_BUCKET = os.getenv("MINIO_BUCKET", "ingest") MINIO_SECURE = False # True en production avec HTTPS # Client MinIO minio_client = Minio( MINIO_ENDPOINT, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=MINIO_SECURE ) def get_document(doc_id: str, object_name: str = None) -> bytes: """ Récupération d'un document depuis MinIO """ try: if not object_name: # Recherche du fichier original prefix = f"{doc_id}/original" objects = list(minio_client.list_objects(MINIO_BUCKET, prefix=prefix, recursive=True)) if not objects: raise FileNotFoundError(f"Aucun fichier original trouvé pour le document {doc_id}") object_name = objects[0].object_name response = minio_client.get_object(MINIO_BUCKET, object_name) return response.read() except S3Error as e: logger.error(f"Erreur MinIO lors de la récupération du document {doc_id}: {e}") raise except Exception as e: logger.error(f"Erreur lors de la récupération du document {doc_id}: {e}") raise def store_artifact(doc_id: str, artifact_name: str, content: bytes, content_type: str = "application/octet-stream") -> str: """ Stockage d'un artefact de traitement """ try: object_name = f"{doc_id}/artifacts/{artifact_name}" from io import BytesIO minio_client.put_object( MINIO_BUCKET, object_name, BytesIO(content), length=len(content), content_type=content_type ) logger.info(f"Artefact {artifact_name} stocké pour le document {doc_id}") return object_name except S3Error as e: logger.error(f"Erreur MinIO lors du stockage de l'artefact {artifact_name}: {e}") raise except Exception as e: logger.error(f"Erreur lors du stockage de l'artefact {artifact_name}: {e}") raise def get_local_temp_file(doc_id: str, suffix: str = ".pdf") -> str: """ Télécharge un document et le sauvegarde dans un fichier temporaire local """ try: # Récupération du document content = get_document(doc_id) # Création d'un fichier temporaire temp_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False) temp_file.write(content) temp_file.close() return temp_file.name except Exception as e: logger.error(f"Erreur lors de la création du fichier temporaire pour {doc_id}: {e}") raise def cleanup_temp_file(file_path: str): """ Nettoyage d'un fichier temporaire """ try: if os.path.exists(file_path): os.unlink(file_path) except Exception as e: logger.warning(f"Impossible de supprimer le fichier temporaire {file_path}: {e}")