同步完整源码 - 2026-05-25

This commit is contained in:
xiaoxue
2026-05-25 00:32:43 +08:00
commit 77248c0d06
46 changed files with 1806 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
__version__ = "0.1"
__all__ = ["config", "pipeline", "report"]
+162
View File
@@ -0,0 +1,162 @@
import argparse
from typing import Any, Dict
from . import __version__
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="document-image-extractor",
description=(
"Extract embedded images from PDF, DOCX, PPTX and XLSX files. "
"Supports deduplication, filters and ZIP/folder output."
),
)
parser.add_argument(
"-c",
"--config",
dest="config_path",
default="config.json",
help="Ruta del archivo de configuración. Default: config.json",
)
parser.add_argument(
"-i",
"--input",
dest="input_path",
default=None,
help="Archivo o carpeta de entrada. Default: paths.input_dir del config.",
)
parser.add_argument(
"-o",
"--output",
dest="output_dir",
default=None,
help="Carpeta de salida. Default: paths.output_dir del config.",
)
parser.add_argument(
"--temp-dir",
dest="temp_dir",
default=None,
help="Carpeta temporal. Default: paths.temp_dir del config.",
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="Procesa archivos dentro de subcarpetas cuando --input es una carpeta.",
)
parser.add_argument(
"--min-kb",
dest="min_kb",
type=int,
default=None,
help="Tamaño mínimo en KB para guardar una imagen.",
)
parser.add_argument(
"--min-width",
dest="min_width",
type=int,
default=None,
help="Ancho mínimo en pixeles. 0 desactiva el filtro.",
)
parser.add_argument(
"--min-height",
dest="min_height",
type=int,
default=None,
help="Alto mínimo en pixeles. 0 desactiva el filtro.",
)
dedup_group = parser.add_mutually_exclusive_group()
dedup_group.add_argument(
"--dedup",
dest="dedup_enabled",
action="store_true",
help="Activa deduplicación por hash.",
)
dedup_group.add_argument(
"--no-dedup",
dest="dedup_enabled",
action="store_false",
help="Desactiva deduplicación por hash.",
)
parser.set_defaults(dedup_enabled=None)
parser.add_argument(
"--format",
dest="output_format",
choices=["zip", "folder"],
default=None,
help="Formato de salida. Opciones: zip, folder. Default: config output.format.",
)
parser.add_argument(
"--log-level",
dest="log_level",
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
default=None,
help="Nivel de logs.",
)
parser.add_argument(
"--log-file",
dest="log_file",
default=None,
help="Ruta del archivo de logs. Ejemplo: logs/run.log",
)
parser.add_argument(
"--version",
action="version",
version=f"%(prog)s {__version__}",
)
return parser.parse_args()
def apply_cli_overrides(cfg: Dict[str, Any], args: argparse.Namespace) -> Dict[str, Any]:
cfg.setdefault("runtime", {})
# Input runtime: puede ser archivo o carpeta
cfg["runtime"]["input_path"] = args.input_path or cfg["paths"]["input_dir"]
cfg["runtime"]["input_was_provided"] = bool(args.input_path)
cfg["runtime"]["recursive"] = bool(args.recursive)
# Paths
if args.output_dir is not None:
cfg["paths"]["output_dir"] = args.output_dir
if args.temp_dir is not None:
cfg["paths"]["temp_dir"] = args.temp_dir
# Filters
if args.min_kb is not None:
cfg["filters"]["min_kb"] = int(args.min_kb)
if args.min_width is not None:
cfg["filters"]["min_width"] = int(args.min_width)
if args.min_height is not None:
cfg["filters"]["min_height"] = int(args.min_height)
# Dedup
if args.dedup_enabled is not None:
cfg["dedup"]["enabled"] = bool(args.dedup_enabled)
# Output
if args.output_format is not None:
cfg["output"]["format"] = args.output_format
# Logging
if args.log_level is not None:
cfg["logging"]["level"] = args.log_level
if args.log_file is not None:
cfg["logging"]["log_file"] = args.log_file
return cfg
+54
View File
@@ -0,0 +1,54 @@
import json
from pathlib import Path
from typing import Any, Dict
DEFAULT_CONFIG: Dict[str, Any] = {
"paths": {
"input_dir": "Entradas_archivos",
"output_dir": "Salidas_archivos",
"temp_dir": "temp",
},
"filters": {
"min_kb": 5,
"min_width": 0,
"min_height": 0,
},
"dedup": {"enabled": True},
"output": {"format": "zip"},
"logging": {
"level": "INFO",
"log_file": "logs/run.log",
"format": "%(asctime)s | %(levelname)s | %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
}
}
# Cargar la configuracion del programa y parametros basicos
def load_config(config_path: Path = Path("config.json")) -> Dict[str, Any]:
# Carga de archivo config.json y en caso de configuraciones faltantes he hace mescla con DEFAULT_CONFIG
cfg = json.loads(json.dumps(DEFAULT_CONFIG))
if not config_path.exists(): return cfg
try:
user_cfg = json.loads(config_path.read_text(encoding="utf-8"))
except Exception:
return cfg
for section in ("paths", "filters", "dedup", "output", "logging"):
if isinstance(user_cfg.get(section), dict): cfg[section].update(user_cfg[section])
# Normalizacion minima
cfg["filters"]["min_kb"] = int(cfg["filters"].get("min_kb", 5))
cfg["filters"]["min_width"] = int(cfg["filters"].get("min_width", 0))
cfg["filters"]["min_height"] = int(cfg["filters"].get("min_height", 0))
cfg["dedup"]["enabled"] = bool(cfg["dedup"].get("enabled", True))
cfg["output"]["format"] = str(cfg["output"].get("format", "zip")).lower()
cfg["logging"]["level"] = str(cfg["logging"].get("level", "INFO")).upper()
cfg["logging"]["format"] = str(cfg["logging"].get("format", DEFAULT_CONFIG["logging"]["format"]))
cfg["logging"]["datefmt"] = str(cfg["logging"].get("datefmt", DEFAULT_CONFIG["logging"]["datefmt"]))
log_file = str(cfg["logging"].get("log_file", "")).strip()
if not log_file:
log_file = DEFAULT_CONFIG["logging"]["log_file"]
cfg["logging"]["log_file"] = log_file
return cfg
@@ -0,0 +1 @@
__all__ = ["docx_extractor", "pdf_extractor","pptx_extractor","xlsx_extractor","ooxml_media_extractor"]
@@ -0,0 +1,70 @@
from pathlib import Path
from typing import Any, Dict, Set
from docx import Document
from ..utils.hashing import md5_bytes
from ..utils.files import is_small_kb
from ..utils.images import get_image_size, fails_dimension_filter, normalize_ext
def _docx_image_ext(image_part) -> str:
ct = getattr(image_part, "content_type", None)
if ct and "/" in ct:
return normalize_ext(ct.split("/")[-1])
partname = str(getattr(image_part, "partname", "")).lower()
if "." in partname:
return normalize_ext(partname.split(".")[-1])
return "bin"
def extract_docx_images(docx_path: Path, temp_folder: Path, cfg: Dict[str, Any]) -> Dict[str, int]:
filters = cfg["filters"]
min_kb = int(filters["min_kb"])
min_w = int(filters["min_width"])
min_h = int(filters["min_height"])
dedup_enabled = bool(cfg["dedup"]["enabled"])
stats: Dict[str, int] = {"found": 0, "saved": 0, "duplicates": 0, "filtered_small": 0, "filtered_dims": 0, "errors": 0}
doc = Document(str(docx_path))
image_parts = list(doc.part.package.image_parts)
stats["found"] = len(image_parts)
hashes: Set[str] = set()
for i, image_part in enumerate(image_parts, start=1):
out_path = None
try:
blob = image_part.blob
digest = md5_bytes(blob)
if dedup_enabled and digest in hashes:
stats["duplicates"] += 1
continue
ext = _docx_image_ext(image_part)
out_path = temp_folder / f"image_{i:03d}.{ext}"
out_path.write_bytes(blob)
if is_small_kb(out_path, min_kb):
stats["filtered_small"] += 1
out_path.unlink(missing_ok=True)
continue
dims = get_image_size(out_path)
if fails_dimension_filter(dims, min_w, min_h):
stats["filtered_dims"] += 1
out_path.unlink(missing_ok=True)
continue
if dedup_enabled:
hashes.add(digest)
stats["saved"] += 1
except Exception:
stats["errors"] += 1
if out_path is not None:
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
return stats
@@ -0,0 +1,67 @@
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterable, Set, Tuple
from ..utils.hashing import md5_bytes
from ..utils.files import is_small_kb
from ..utils.images import get_image_size, fails_dimension_filter, normalize_ext
IMAGE_EXTS = {"png", "jpg", "jpeg", "gif", "bmp", "tiff", "tif", "webp", "emf", "wmf", "svg"}
def extract_ooxml_media_images(archive_path: Path, media_prefixes: Tuple[str, ...], temp_folder: Path, cfg: Dict[str, Any], source_tag: str) -> Dict[str, int]:
# Extraer imagenes desde un OOXML (pptx, xlsx) leyendo lor archivos en media/
filters = cfg["filters"]
min_kb = int(filters["min_kb"])
min_w = int(filters["min_width"])
min_h = int(filters["min_height"])
dedup_enabled = bool(cfg["dedup"]["enabled"])
stats: Dict[str, int] = {"found": 0, "saved": 0, "duplicates": 0, "filtered_small": 0, "filtered_dims": 0, "errors": 0}
hashes: Set[str] = set()
counter = 0
with zipfile.ZipFile(archive_path, "r") as zf:
for info in zf.infolist():
name = info.filename
if name.endswith("/"): continue
if not any(name.startswith(prefix) for prefix in media_prefixes): continue
ext = normalize_ext(Path(name).suffix.replace(".",""))
if not ext or ext not in IMAGE_EXTS: continue
out_path = None
try:
data = zf.read(name)
stats["found"] += 1
digest = md5_bytes(data)
if dedup_enabled and digest in hashes:
stats["duplicates"] += 1
continue
counter += 1
out_path = temp_folder / f"image_{counter:03d}_{source_tag}.{ext}"
out_path.write_bytes(data)
if is_small_kb(out_path, min_kb):
stats["filtered_small"] += 1
out_path.unlink(missing_ok=True)
continue
dims = get_image_size(out_path)
if fails_dimension_filter(dims, min_w, min_h):
stats["filtered_dims"] += 1
out_path.unlink(missing_ok=True)
continue
if dedup_enabled: hashes.add(digest)
stats["saved"] += 1
except Exception:
stats["errors"] += 1
if out_path is not None:
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
return stats
@@ -0,0 +1,68 @@
from pathlib import Path
from typing import Any, Dict, Set
import fitz
from ..utils.hashing import md5_bytes
from ..utils.files import is_small_kb
from ..utils.images import get_image_size, fails_dimension_filter, normalize_ext
def extract_pdf_images(pdf_path: Path, temp_folder: Path, cfg: Dict[str, Any]) -> Dict[str, int]:
# Extraer las imagenes de vienen en el documento pdf
filters = cfg["filters"]
min_kb = filters["min_kb"]
min_w = filters["min_width"]
min_h = filters["min_height"]
dedup_enabled = cfg["dedup"]["enabled"]
stats = {"found": 0,"saved": 0, "duplicates": 0, "filtered_small": 0, "filtered_dims": 0, "errors": 0}
hashes: Set[str] = set()
counter = 0
with fitz.open(str(pdf_path)) as pdf:
for page_index in range(len(pdf)):
page = pdf[page_index]
for img in page.get_images(full=True):
out_path = None
try:
xref = img[0]
base = pdf.extract_image(xref)
data = base.get("image", b"")
ext = normalize_ext(base.get("ext", "bin"))
stats["found"] += 1
digest = md5_bytes(data)
if dedup_enabled and digest in hashes:
stats["duplicates"] += 1
continue
counter += 1
out_path = temp_folder / f"image_{counter:03d}_p{page_index+1:03d}.{ext}"
out_path.write_bytes(data)
# Filtro KB
if is_small_kb(out_path, min_kb):
stats["filtered_small"] += 1
out_path.unlink(missing_ok=True)
continue
# Filtro de dimenciones
dims = get_image_size(out_path)
if fails_dimension_filter(dims, min_w, min_h):
stats["filtered_dims"] += 1
out_path.unlink(missing_ok=True)
continue
if dedup_enabled:
hashes.add(digest)
stats["saved"] += 1
except Exception:
stats["errors"] += 1
if out_path is not None:
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
return stats
@@ -0,0 +1,12 @@
from pathlib import Path
from typing import Any, Dict
from .ooxml_media_extractor import extract_ooxml_media_images
def extract_pptx_images(pptx_path: Path, temp_folder: Path, cfg: Dict[str, Any]) -> Dict[str, int]:
return extract_ooxml_media_images(archive_path=pptx_path,
media_prefixes=("ppt/media/",),
temp_folder=temp_folder,
cfg=cfg,
source_tag="pptx")
@@ -0,0 +1,12 @@
from pathlib import Path
from typing import Any, Dict
from .ooxml_media_extractor import extract_ooxml_media_images
def extract_xlsx_images(xlsx_path: Path, temp_folder: Path, cfg: Dict[str, Any]) -> Dict[str, int]:
return extract_ooxml_media_images(
archive_path=xlsx_path,
media_prefixes=("xl/media/",),
temp_folder=temp_folder,
cfg=cfg,
source_tag="xlsx",
)
+20
View File
@@ -0,0 +1,20 @@
import logging
from pathlib import Path
from typing import Any, Dict
def setup_logging(cfg: Dict[str, Any]) -> None:
log_cfg = cfg.get("logging", {}) if isinstance(cfg, dict) else {}
level_name = str(log_cfg.get("level", "INFO")).upper()
level = getattr(logging, level_name, logging.INFO)
fmt = str(log_cfg.get("format", "%(asctime)s | %(levelname)s | %(message)s"))
datefmt = str(log_cfg.get("datefmt", "%Y-%m-%d %H:%M:%S"))
log_file = str(log_cfg.get("log_file", "logs/run.log")).strip() or "logs/run.log"
log_path = Path(log_file)
log_path.parent.mkdir(parents=True, exist_ok=True)
handlers = [logging.StreamHandler(), logging.FileHandler(log_path, encoding="utf-8")]
logging.basicConfig(level=level, format=fmt, datefmt=datefmt, handlers=handlers, force=True)
+74
View File
@@ -0,0 +1,74 @@
from pathlib import Path
from typing import Any, Dict, List
from .extractors.docx_extractor import extract_docx_images
from .extractors.pdf_extractor import extract_pdf_images
from .extractors.pptx_extractor import extract_pptx_images
from .extractors.xlsx_extractor import extract_xlsx_images
from .utils.files import clean_dir, ensure_dir, create_zip_from_folder, copy_folder
SUPPORTED_EXTS = {".pdf", ".docx", ".pptx", ".xlsx"}
def process_file(file_path: Path, cfg: Dict[str, Any]) -> Dict:
paths = cfg["paths"]
temp_root = Path(paths["temp_dir"])
output_dir = Path(paths["output_dir"])
output_format = cfg["output"]["format"]
ensure_dir(temp_root)
ensure_dir(output_dir)
name = file_path.stem
temp_folder = temp_root / name
clean_dir(temp_folder)
ensure_dir(temp_folder)
try:
ext = file_path.suffix.lower()
if ext == ".pdf":
stats = extract_pdf_images(file_path, temp_folder, cfg)
elif ext == ".docx":
stats = extract_docx_images(file_path, temp_folder, cfg)
elif ext == ".pptx":
stats = extract_pptx_images(file_path, temp_folder, cfg)
elif ext == ".xlsx":
stats = extract_xlsx_images(file_path, temp_folder, cfg)
else:
return {"skipped": True, "reason": f"extencion no soportada ({ext})"}
if stats["saved"] > 0:
if output_format == "zip":
zip_path = output_dir / f"{name}.zip"
create_zip_from_folder(temp_folder, zip_path)
elif output_format == "folder":
folder_path = output_dir / name
copy_folder(temp_folder, folder_path)
else:
return {"error": f"formato de salida no soportado: {output_format}"}
return stats
except Exception as e:
return {"error": str(e)}
finally:
clean_dir(temp_folder)
def list_input_files(input_path: Path, recursive: bool = False) -> List[Path]:
if input_path.is_file():
if input_path.suffix.lower() in SUPPORTED_EXTS:
return [input_path]
return []
if not input_path.is_dir():
return []
pattern = "**/*" if recursive else "*"
files = [
f for f in input_path.glob(pattern)
if f.is_file() and f.suffix.lower() in SUPPORTED_EXTS
]
return sorted(files)
+52
View File
@@ -0,0 +1,52 @@
import logging
from typing import Dict
logger = logging.getLogger("document_image_extractor")
def log_file_report(filename: str, stats: Dict) -> None:
if stats.get("skipped"):
logger.warning("%s: %s", filename, stats.get("reason"))
return
if "error" in stats:
logger.error("%s: %s", filename, stats["error"])
return
if stats.get("saved", 0) > 0:
logger.info(
"%s | found=%s, saved=%s, dupes=%s, filtered_small=%s, filtered_dims=%s, errors=%s",
filename,
stats.get("found", 0),
stats.get("saved", 0),
stats.get("duplicates", 0),
stats.get("filtered_small", 0),
stats.get("filtered_dims", 0),
stats.get("errors", 0),
)
else:
logger.warning(
"%s | No hay imágenes válidas | found=%s, dupes=%s, filtered_small=%s, filtered_dims=%s, errors=%s",
filename,
stats.get("found", 0),
stats.get("duplicates", 0),
stats.get("filtered_small", 0),
stats.get("filtered_dims", 0),
stats.get("errors", 0),
)
def accumulate_totals(total: Dict[str, int], stats: Dict) -> None:
for k in total:
total[k] += int(stats.get(k, 0))
def log_summary(files: int, skipped: int, failed: int, total: Dict[str, int]) -> None:
logger.info("=== RESUMEN ===")
logger.info(
"files=%s, skipped=%s, failed=%s | found=%s, saved=%s, dupes=%s, filtered_small=%s, filtered_dims=%s, errors=%s",
files, skipped, failed,
total.get("found", 0),
total.get("saved", 0),
total.get("duplicates", 0),
total.get("filtered_small", 0),
total.get("filtered_dims", 0),
total.get("errors", 0),
)
@@ -0,0 +1 @@
__all_ = ["files", "hashing", "images"]
+27
View File
@@ -0,0 +1,27 @@
import shutil
import zipfile
from pathlib import Path
def ensure_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def clean_dir(path: Path) -> None:
# Eliminar archivos de la carpeta esfecifica
if path.exists(): shutil.rmtree(path, ignore_errors=True)
def create_zip_from_folder(folder: Path, zip_destine: Path) -> None:
# Crear un zip con el contenido de folder
with zipfile.ZipFile(zip_destine, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for file in folder.rglob("*"):
if file.is_file(): zf.write(file, arcname=file.relative_to(folder))
def is_small_kb(path: Path, min_kb: int) -> bool:
# Validacion booleana si la imagen es mas chica que el parametro min_kb configurado
return (path.stat().st_size / 1024) < min_kb
def copy_folder(src: Path, dest: Path) -> None:
# Copia una carpeta al destino, si el destino existe lo remplaza
if dest.exists(): shutil.rmtree(dest, ignore_errors=True)
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(src, dest)
@@ -0,0 +1,4 @@
import hashlib
def md5_bytes(data: bytes) -> str:
return hashlib.md5(data).hexdigest()
+32
View File
@@ -0,0 +1,32 @@
from pathlib import Path
from typing import Optional, Tuple
from PIL import Image
def get_image_size(path: Path) -> Optional[Tuple[int, int]]:
# Devolver el ancho y el alto de las imagenes, En caso de no poder abrir regresa None
try:
with Image.open(path) as im:
return im.size
except Exception:
return None
def fails_dimension_filter(dims: Optional[Tuple[int, int]], min_w: int, min_h: int) -> bool:
# En caso de que dims sea None se omiten validaciones
if min_w <= 0 and min_h <= 0: return False
if dims is None: return False
w, h = dims
if min_w > 0 and w < min_w: return True
if min_h > 0 and h < min_h: return True
return False
def normalize_ext(ext: str) -> str:
# Normalizacion de extenciones para imagenes
ext = (ext or "bin").lower().strip(".")
if ext in ("jpeg", "jpe"):
return "jpg"
if ext == "tif":
return "tiff"
return ext