Download app/pdf_processor.py from puyol85/pvgfd: direct link, hf CLI and curl.
- Browser
- Download file 2.95 kB
-
https://huggingface.co/spaces/puyol85/pvgfd/resolve/main/app/pdf_processor.py
- Command line
-
hf download hf://spaces/puyol85/pvgfd/app/pdf_processor.py
-
curl -L -o pdf_processor.py https://huggingface.co/spaces/puyol85/pvgfd/resolve/main/app/pdf_processor.py
2.95 kB
| """Traitement des fichiers PDF""" | |
| import fitz # PyMuPDF | |
| from typing import List, Tuple | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| class PDFProcessor: | |
| """Classe pour traiter les fichiers PDF""" | |
| def __init__(self, chunk_size: int = 500, chunk_overlap: int = 50): | |
| """ | |
| Args: | |
| chunk_size: Taille des chunks en tokens (approximatif) | |
| chunk_overlap: Chevauchement entre les chunks | |
| """ | |
| self.chunk_size = chunk_size | |
| self.chunk_overlap = chunk_overlap | |
| def extract_text(self, pdf_path: str) -> str: | |
| """ | |
| Extrait le texte d'un PDF | |
| Args: | |
| pdf_path: Chemin vers le fichier PDF | |
| Returns: | |
| Texte extrait | |
| """ | |
| try: | |
| doc = fitz.open(pdf_path) | |
| text = "" | |
| for page_num in range(len(doc)): | |
| page = doc[page_num] | |
| text += page.get_text() | |
| doc.close() | |
| logger.info(f"Extrait {len(text)} caractères de {pdf_path}") | |
| return text | |
| except Exception as e: | |
| logger.error(f"Erreur lors de l'extraction du PDF {pdf_path}: {e}") | |
| raise | |
| def chunk_text(self, text: str) -> List[Tuple[str, int]]: | |
| """ | |
| Découpe le texte en chunks avec overlap | |
| Args: | |
| text: Texte à découper | |
| Returns: | |
| Liste de tuples (chunk_text, start_position) | |
| """ | |
| # Approximation: 1 token ≈ 4 caractères | |
| chunk_size_chars = self.chunk_size * 4 | |
| overlap_chars = self.chunk_overlap * 4 | |
| chunks = [] | |
| start = 0 | |
| while start < len(text): | |
| end = start + chunk_size_chars | |
| chunk = text[start:end] | |
| # Éviter de couper au milieu d'un mot | |
| if end < len(text): | |
| last_space = chunk.rfind(' ') | |
| if last_space > chunk_size_chars * 0.8: # Au moins 80% du chunk | |
| end = start + last_space | |
| chunk = text[start:end] | |
| if chunk.strip(): # Ignorer les chunks vides | |
| chunks.append((chunk.strip(), start)) | |
| start = end - overlap_chars | |
| # Éviter les boucles infinies | |
| if start >= len(text): | |
| break | |
| logger.info(f"Texte découpé en {len(chunks)} chunks") | |
| return chunks | |
| def process_pdf(self, pdf_path: str) -> List[Tuple[str, int]]: | |
| """ | |
| Traite un PDF: extraction + chunking | |
| Args: | |
| pdf_path: Chemin vers le fichier PDF | |
| Returns: | |
| Liste de chunks avec leurs positions | |
| """ | |
| text = self.extract_text(pdf_path) | |
| chunks = self.chunk_text(text) | |
| return chunks | |