forked from scanny/python-pptx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
68 lines (53 loc) · 2.39 KB
/
api.py
File metadata and controls
68 lines (53 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Directly exposed API classes, Presentation for now.
Provides some syntactic sugar for interacting with the pptx.presentation.Package graph and also
provides some insulation so not so many classes in the other modules need to be named as internal
(leading underscore).
"""
from __future__ import annotations
import os
from typing import IO, TYPE_CHECKING
from pptx.opc.constants import CONTENT_TYPE as CT
from pptx.package import Package
if TYPE_CHECKING:
from pptx import presentation
from pptx.parts.presentation import PresentationPart
def Presentation(
pptx: str | os.PathLike[str] | IO[bytes] | None = None,
) -> presentation.Presentation:
"""
Return a |Presentation| object loaded from *pptx*, where *pptx* can be
a path to a ``.pptx`` file (a |str| or any |os.PathLike| object such as
|pathlib.Path|) or a file-like object. If *pptx* is missing or ``None``,
the built-in default presentation "template" is loaded.
"""
# ---accept os.PathLike (pathlib.Path, etc.) by coercing to str at the
# ---boundary; collapse the union to (str | IO[bytes]) for downstream---
pkg_file: str | IO[bytes]
if pptx is None:
pkg_file = _default_pptx_path()
elif isinstance(pptx, os.PathLike):
pkg_file = os.fspath(pptx)
else:
pkg_file = pptx
presentation_part = Package.open(pkg_file).main_document_part
if not _is_pptx_package(presentation_part):
tmpl = "file '%s' is not a PowerPoint file, content type is '%s'"
raise ValueError(tmpl % (pkg_file, presentation_part.content_type))
return presentation_part.presentation
def _default_pptx_path() -> str:
"""Return the path to the built-in default .pptx package."""
_thisdir = os.path.split(__file__)[0]
return os.path.join(_thisdir, "templates", "default.pptx")
def _is_pptx_package(prs_part: PresentationPart):
"""Return |True| if *prs_part* is a valid main document part, |False| otherwise.
The allowlist includes ``PML_TEMPLATE_MAIN`` so ``.potx`` template packages
open as ordinary presentations (issue #19 / scanny/python-pptx#1070,
#1095). A ``.potx`` differs from a ``.pptx`` only in this content-type;
every downstream part graph is identical.
"""
valid_content_types = (
CT.PML_PRESENTATION_MAIN,
CT.PML_PRES_MACRO_MAIN,
CT.PML_TEMPLATE_MAIN,
)
return prs_part.content_type in valid_content_types