Source code

Download source archive ↓

src/rdflib/parser.py

1"""Parser plugin interface.
2
3This module defines the parser plugin interface and contains other
4related parser support code.
5
6The module is mainly useful for those wanting to write a parser that
7can plugin to rdflib. If you are wanting to invoke a parser you likely
8want to do so through the Graph class parse method.
9"""
10
11from __future__ import annotations
12
13import codecs
14import os
15import pathlib
16import sys
17from io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOBase, TextIOWrapper
18from typing import (
19    IO,
20    TYPE_CHECKING,
21    Any,
22    BinaryIO,
23    List,
24    Optional,
25    TextIO,
26    Tuple,
27    Union,
28    cast,
29)
30from urllib.parse import urljoin
31from urllib.request import Request, url2pathname
32from xml.sax import xmlreader
33
34import rdflib.util
35from rdflib import __version__
36from rdflib._networking import _urlopen
37from rdflib.namespace import Namespace
38from rdflib.term import URIRef
39
40if TYPE_CHECKING:
41    from email.message import Message
42    from io import BufferedReader
43    from urllib.response import addinfourl
44
45    from typing_extensions import Buffer
46
47    from rdflib.graph import Graph
48
49
50__all__ = [
51    "Parser",
52    "InputSource",
53    "StringInputSource",
54    "URLInputSource",
55    "FileInputSource",
56    "PythonInputSource",
57]
58
59
60class Parser:
61    __slots__ = ()
62
63    def __init__(self):
64        pass
65
66    def parse(self, source: InputSource, sink: Graph) -> None:
67        pass
68
69
70class BytesIOWrapper(BufferedIOBase):
71    __slots__ = (
72        "wrapped",
73        "enc_str",
74        "text_str",
75        "encoding",
76        "encoder",
77        "has_read1",
78        "has_seek",
79        "_name",
80        "_fileno",
81        "_isatty",
82        "_leftover",
83        "_bytes_per_char",
84        "_text_bytes_offset",
85    )
86
87    def __init__(self, wrapped: Union[str, StringIO, TextIOBase], encoding="utf-8"):
88        super(BytesIOWrapper, self).__init__()
89        self.wrapped = wrapped
90        self.encoding = encoding
91        self.encoder = codecs.getencoder(self.encoding)
92        self.enc_str: Optional[Union[BytesIO, BufferedIOBase]] = None
93        self.text_str: Optional[Union[StringIO, TextIOBase]] = None
94        self.has_read1: Optional[bool] = None
95        self.has_seek: Optional[bool] = None
96        self._name: Optional[str] = None
97        self._fileno: Optional[Union[int, BaseException]] = None
98        self._isatty: Optional[Union[bool, BaseException]] = None
99        self._leftover: bytes = b""
100        self._text_bytes_offset: int = 0
101        norm_encoding = encoding.lower().replace("_", "-")
102        if norm_encoding in ("utf-8", "utf8", "u8", "cp65001"):
103            # utf-8 has a variable number of bytes per character, 1-4
104            self._bytes_per_char: int = 1  # assume average of 1 byte per character
105        elif norm_encoding in (
106            "latin1",
107            "latin-1",
108            "iso-8859-1",
109            "iso8859-1",
110            "ascii",
111            "us-ascii",
112        ):
113            # these are all 1-byte-per-character encodings
114            self._bytes_per_char = 1
115        elif norm_encoding.startswith("utf-16") or norm_encoding.startswith("utf16"):
116            # utf-16 has a variable number of bytes per character, 2-3
117            self._bytes_per_char = 2  # assume average of 2 bytes per character
118        elif norm_encoding.startswith("utf-32") or norm_encoding.startswith("utf32"):
119            # utf-32 is fixed length with 4 bytes per character
120            self._bytes_per_char = 4
121        else:
122            # not sure, just assume it is 2 bytes per character
123            self._bytes_per_char = 2
124
125    def _init(self):
126        name: Optional[str] = None
127        if isinstance(self.wrapped, str):
128            b, blen = self.encoder(self.wrapped)
129            self.enc_str = BytesIO(b)
130            name = "string"
131        elif isinstance(self.wrapped, TextIOWrapper):
132            inner = self.wrapped.buffer
133            if isinstance(inner, BytesIOWrapper):
134                raise Exception(
135                    "BytesIOWrapper cannot be wrapped in TextIOWrapper, "
136                    "then wrapped in another BytesIOWrapper"
137                )
138            else:
139                self.enc_str = cast(BufferedIOBase, inner)
140        elif isinstance(self.wrapped, (TextIOBase, StringIO)):
141            self.text_str = self.wrapped
142        use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
143        if self.enc_str is not None:
144            use_stream = self.enc_str
145        elif self.text_str is not None:
146            use_stream = self.text_str
147        else:
148            raise Exception("No stream to read from")
149        if name is None:
150            try:
151                name = use_stream.name  # type: ignore[union-attr]
152            except AttributeError:
153                name = "stream"
154        self.has_read1 = hasattr(use_stream, "read1")
155        try:
156            self.has_seek = use_stream.seekable()
157        except AttributeError:
158            self.has_seek = hasattr(use_stream, "seek")
159
160        self._name = name
161
162    def _check_fileno(self):
163        use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
164        if self.enc_str is None and self.text_str is None:
165            self._init()
166        if self.enc_str is not None:
167            use_stream = self.enc_str
168        elif self.text_str is not None:
169            use_stream = self.text_str
170        try:
171            self._fileno = use_stream.fileno()
172        except OSError as e:
173            self._fileno = e
174        except AttributeError:
175            self._fileno = -1
176
177    def _check_isatty(self):
178        use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
179        if self.enc_str is None and self.text_str is None:
180            self._init()
181        if self.enc_str is not None:
182            use_stream = self.enc_str
183        elif self.text_str is not None:
184            use_stream = self.text_str
185        try:
186            self._isatty = use_stream.isatty()
187        except OSError as e:
188            self._isatty = e
189        except AttributeError:
190            self._isatty = False
191
192    @property
193    def name(self) -> Any:
194        if self._name is None:
195            self._init()
196        return self._name
197
198    @property
199    def closed(self) -> bool:
200        if self.enc_str is None and self.text_str is None:
201            return False
202        closed: Optional[bool] = None
203        if self.enc_str is not None:
204            try:
205                closed = self.enc_str.closed
206            except AttributeError:
207                closed = None
208        elif self.text_str is not None:
209            try:
210                closed = self.text_str.closed
211            except AttributeError:
212                closed = None
213        return False if closed is None else closed
214
215    def readable(self) -> bool:
216        return True
217
218    def writable(self) -> bool:
219        return False
220
221    def truncate(self, size: Optional[int] = None) -> int:
222        raise NotImplementedError("Cannot truncate on BytesIOWrapper")
223
224    def isatty(self) -> bool:
225        if self._isatty is None:
226            self._check_isatty()
227        if isinstance(self._isatty, BaseException):
228            raise self._isatty
229        else:
230            return bool(self._isatty)
231
232    def fileno(self) -> int:
233        if self._fileno is None:
234            self._check_fileno()
235        if isinstance(self._fileno, BaseException):
236            raise self._fileno
237        else:
238            return -1 if self._fileno is None else self._fileno
239
240    def close(self):
241        if self.enc_str is None and self.text_str is None:
242            return
243        if self.enc_str is not None:
244            try:
245                self.enc_str.close()
246            except AttributeError:
247                pass
248        elif self.text_str is not None:
249            try:
250                self.text_str.close()
251            except AttributeError:
252                pass
253
254    def flush(self):
255        return  # Does nothing on read-only streams
256
257    def _read_bytes_from_text_stream(self, size: Optional[int] = -1, /) -> bytes:
258        if TYPE_CHECKING:
259            assert self.text_str is not None
260        if size is None or size < 0:
261            try:
262                ret_str: str = self.text_str.read()
263            except EOFError:
264                ret_str = ""
265            ret_encoded, enc_len = self.encoder(ret_str)
266            if self._leftover:
267                ret_bytes = self._leftover + ret_encoded
268                self._leftover = b""
269            else:
270                ret_bytes = ret_encoded
271        elif size == len(self._leftover):
272            ret_bytes = self._leftover
273            self._leftover = b""
274        elif size < len(self._leftover):
275            ret_bytes = self._leftover[:size]
276            self._leftover = self._leftover[size:]
277        else:
278            d, m = divmod(size, self._bytes_per_char)
279            get_per_loop = int(d) + (1 if m > 0 else 0)
280            got_bytes: bytes = self._leftover
281            while len(got_bytes) < size:
282                try:
283                    got_str: str = self.text_str.read(get_per_loop)
284                except EOFError:
285                    got_str = ""
286                if len(got_str) < 1:
287                    break
288                ret_encoded, enc_len = self.encoder(got_str)
289                got_bytes += ret_encoded
290            if len(got_bytes) == size:
291                self._leftover = b""
292                ret_bytes = got_bytes
293            else:
294                ret_bytes = got_bytes[:size]
295                self._leftover = got_bytes[size:]
296                del got_bytes
297        self._text_bytes_offset += len(ret_bytes)
298        return ret_bytes
299
300    def read(self, size: Optional[int] = -1, /) -> bytes:
301        """
302        Read at most size bytes, returned as a bytes object.
303
304        If the size argument is negative or omitted read until EOF is reached.
305        Return an empty bytes object if already at EOF.
306        """
307        if size is not None and size == 0:
308            return b""
309        if self.enc_str is None and self.text_str is None:
310            self._init()
311        if self.enc_str is not None:
312            ret_bytes = self.enc_str.read(size)
313        else:
314            ret_bytes = self._read_bytes_from_text_stream(size)
315        return ret_bytes
316
317    def read1(self, size: Optional[int] = -1, /) -> bytes:
318        """
319        Read at most size bytes, with at most one call to the underlying raw stream’s
320        read() or readinto() method. Returned as a bytes object.
321
322        If the size argument is negative or omitted, read until EOF is reached.
323        Return an empty bytes object at EOF.
324        """
325        if (self.enc_str is None and self.text_str is None) or self.has_read1 is None:
326            self._init()
327        if not self.has_read1:
328            raise NotImplementedError()
329        if self.enc_str is not None:
330            if size is None or size < 0:
331                return self.enc_str.read1()
332            return self.enc_str.read1(size)
333        raise NotImplementedError("read1() not supported for TextIO in BytesIOWrapper")
334
335    def readinto(self, b: Buffer, /) -> int:
336        """
337        Read len(b) bytes into buffer b.
338
339        Returns number of bytes read (0 for EOF), or error if the object
340        is set not to block and has no data to read.
341        """
342        if TYPE_CHECKING:
343            assert isinstance(b, (memoryview, bytearray))
344        if len(b) == 0:
345            return 0
346        if self.enc_str is None and self.text_str is None:
347            self._init()
348        if self.enc_str is not None:
349            return self.enc_str.readinto(b)
350        else:
351            size = len(b)
352            read_data: bytes = self._read_bytes_from_text_stream(size)
353            read_len = len(read_data)
354            if read_len == 0:
355                return 0
356            b[:read_len] = read_data
357            return read_len
358
359    def readinto1(self, b: Buffer, /) -> int:
360        """
361        Read len(b) bytes into buffer b, with at most one call to the underlying raw
362        stream's read() or readinto() method.
363
364        Returns number of bytes read (0 for EOF), or error if the object
365        is set not to block and has no data to read.
366        """
367        if TYPE_CHECKING:
368            assert isinstance(b, (memoryview, bytearray))
369        if (self.enc_str is None and self.text_str is None) or self.has_read1 is None:
370            self._init()
371        if not self.has_read1:
372            raise NotImplementedError()
373        if self.enc_str is not None:
374            return self.enc_str.readinto1(b)
375        raise NotImplementedError(
376            "readinto1() not supported for TextIO in BytesIOWrapper"
377        )
378
379    def seek(self, offset: int, whence: int = 0, /) -> int:
380        if self.has_seek is not None and not self.has_seek:
381            raise NotImplementedError()
382        if (self.enc_str is None and self.text_str is None) or self.has_seek is None:
383            self._init()
384
385        if not whence == 0:
386            raise NotImplementedError("Only SEEK_SET is supported on BytesIOWrapper")
387        if offset != 0:
388            raise NotImplementedError(
389                "Only seeking to zero is supported on BytesIOWrapper"
390            )
391        if self.enc_str is not None:
392            self.enc_str.seek(offset, whence)
393        elif self.text_str is not None:
394            self.text_str.seek(offset, whence)
395        self._text_bytes_offset = 0
396        self._leftover = b""
397        return 0
398
399    def seekable(self):
400        if (self.enc_str is None and self.text_str is None) or self.has_seek is None:
401            self._init()
402        return self.has_seek
403
404    def tell(self) -> int:
405        if self.has_seek is not None and not self.has_seek:
406            raise NotImplementedError("Cannot tell() pos because file is not seekable.")
407        if self.enc_str is not None:
408            try:
409                self._text_bytes_offset = self.enc_str.tell()
410            except AttributeError:
411                pass
412        return self._text_bytes_offset
413
414    def write(self, b, /):
415        raise NotImplementedError("Cannot write to a BytesIOWrapper")
416
417
418class InputSource(xmlreader.InputSource):
419    """
420    TODO:
421    """
422
423    def __init__(self, system_id: Optional[str] = None):
424        xmlreader.InputSource.__init__(self, system_id=system_id)
425        self.content_type: Optional[str] = None
426        self.auto_close = False  # see Graph.parse(), true if opened by us
427
428    def close(self) -> None:
429        c = self.getCharacterStream()
430        if c and hasattr(c, "close"):
431            try:
432                c.close()
433            except Exception:
434                pass
435        f = self.getByteStream()
436        if f and hasattr(f, "close"):
437            try:
438                f.close()
439            except Exception:
440                pass
441
442
443class PythonInputSource(InputSource):
444    """
445    Constructs an RDFLib Parser InputSource from a Python data structure,
446    for example, loaded from JSON with json.load or json.loads:
447
448    >>> import json
449    >>> as_string = \"\"\"{
450    ...   "@context" : {"ex" : "http://example.com/ns#"},
451    ...   "@graph": [{"@type": "ex:item", "@id": "#example"}]
452    ... }\"\"\"
453    >>> as_python = json.loads(as_string)
454    >>> source = create_input_source(data=as_python)
455    >>> isinstance(source, PythonInputSource)
456    True
457    """
458
459    def __init__(self, data: Any, system_id: Optional[str] = None):
460        self.content_type = None
461        self.auto_close = False  # see Graph.parse(), true if opened by us
462        self.public_id: Optional[str] = None
463        self.system_id: Optional[str] = system_id
464        self.data = data
465
466    def getPublicId(self) -> Optional[str]:  # noqa: N802
467        return self.public_id
468
469    def setPublicId(self, public_id: Optional[str]) -> None:  # noqa: N802
470        self.public_id = public_id
471
472    def getSystemId(self) -> Optional[str]:  # noqa: N802
473        return self.system_id
474
475    def setSystemId(self, system_id: Optional[str]) -> None:  # noqa: N802
476        self.system_id = system_id
477
478    def close(self) -> None:
479        self.data = None
480
481
482class StringInputSource(InputSource):
483    """
484    Constructs an RDFLib Parser InputSource from a Python String or Bytes
485    """
486
487    def __init__(
488        self,
489        value: Union[str, bytes],
490        encoding: str = "utf-8",
491        system_id: Optional[str] = None,
492    ):
493        super(StringInputSource, self).__init__(system_id)
494        stream: Union[BinaryIO, TextIO]
495        if isinstance(value, str):
496            stream = StringIO(value)
497            self.setCharacterStream(stream)
498            self.setEncoding(encoding)
499            b_stream = BytesIOWrapper(value, encoding)
500            self.setByteStream(b_stream)
501        else:
502            stream = BytesIO(value)
503            self.setByteStream(stream)
504            c_stream = TextIOWrapper(stream, encoding)
505            self.setCharacterStream(c_stream)
506            self.setEncoding(c_stream.encoding)
507
508
509headers = {
510    "User-agent": "rdflib-%s (https://rdflib.github.io/; eikeon@eikeon.com)"
511    % __version__
512}
513
514
515class URLInputSource(InputSource):
516    """
517    Constructs an RDFLib Parser InputSource from a URL to read it from the Web.
518    """
519
520    links: List[str]
521
522    @classmethod
523    def getallmatchingheaders(cls, message: Message, name) -> List[str]:
524        # This is reimplemented here, because the method
525        # getallmatchingheaders from HTTPMessage is broken since Python 3.0
526        name = name.lower()
527        return [val for key, val in message.items() if key.lower() == name]
528
529    @classmethod
530    def get_links(cls, response: addinfourl) -> List[str]:
531        linkslines = cls.getallmatchingheaders(response.headers, "Link")
532        retarray: List[str] = []
533        for linksline in linkslines:
534            links = [linkstr.strip() for linkstr in linksline.split(",")]
535            for link in links:
536                retarray.append(link)
537        return retarray
538
539    def get_alternates(self, type_: Optional[str] = None) -> List[str]:
540        typestr: Optional[str] = f'type="{type_}"' if type_ else None
541        relstr = 'rel="alternate"'
542        alts = []
543        for link in self.links:
544            parts = [p.strip() for p in link.split(";")]
545            if relstr not in parts:
546                continue
547            if typestr:
548                if typestr in parts:
549                    alts.append(parts[0].strip("<>"))
550            else:
551                alts.append(parts[0].strip("<>"))
552        return alts
553
554    def __init__(self, system_id: Optional[str] = None, format: Optional[str] = None):
555        super(URLInputSource, self).__init__(system_id)
556        self.url = system_id
557
558        # copy headers to change
559        myheaders = dict(headers)
560        if format == "xml":
561            myheaders["Accept"] = "application/rdf+xml, */*;q=0.1"
562        elif format == "n3":
563            myheaders["Accept"] = "text/n3, */*;q=0.1"
564        elif format in ["turtle", "ttl"]:
565            myheaders["Accept"] = "text/turtle, application/x-turtle, */*;q=0.1"
566        elif format == "nt":
567            myheaders["Accept"] = "text/plain, */*;q=0.1"
568        elif format == "trig":
569            myheaders["Accept"] = "application/trig, */*;q=0.1"
570        elif format == "trix":
571            myheaders["Accept"] = "application/trix, */*;q=0.1"
572        elif format == "json-ld":
573            myheaders["Accept"] = (
574                "application/ld+json, application/json;q=0.9, */*;q=0.1"
575            )
576        else:
577            # if format not given, create an Accept header from all registered
578            # parser Media Types
579            from rdflib.parser import Parser
580            from rdflib.plugin import plugins
581
582            acc = []
583            for p in plugins(kind=Parser):  # only get parsers
584                if "/" in p.name:  # all Media Types known have a / in them
585                    acc.append(p.name)
586
587            myheaders["Accept"] = ", ".join(acc)
588
589        req = Request(system_id, None, myheaders)  # type: ignore[arg-type]
590
591        response: addinfourl = _urlopen(req)
592        self.url = response.geturl()  # in case redirections took place
593        self.links = self.get_links(response)
594        if format in ("json-ld", "application/ld+json"):
595            alts = self.get_alternates(type_="application/ld+json")
596            for link in alts:
597                full_link = urljoin(self.url, link)
598                if full_link != self.url and full_link != system_id:
599                    response = _urlopen(Request(full_link))
600                    self.url = response.geturl()  # in case redirections took place
601                    break
602
603        self.setPublicId(self.url)
604        content_types = self.getallmatchingheaders(response.headers, "content-type")
605        self.content_type = content_types[0] if content_types else None
606        if self.content_type is not None:
607            self.content_type = self.content_type.split(";", 1)[0]
608        self.setByteStream(response)
609        # TODO: self.setEncoding(encoding)
610        self.response_info = response.info()  # a mimetools.Message instance
611
612    def __repr__(self) -> str:
613        # type error: Incompatible return value type (got "Optional[str]", expected "str")
614        return self.url  # type: ignore[return-value]
615
616
617class FileInputSource(InputSource):
618    def __init__(
619        self,
620        file: Union[BinaryIO, TextIO, TextIOBase, RawIOBase, BufferedIOBase],
621        /,
622        encoding: Optional[str] = None,
623    ):
624        base = pathlib.Path.cwd().as_uri()
625        system_id = URIRef(pathlib.Path(file.name).absolute().as_uri(), base=base)  # type: ignore[union-attr]
626        super(FileInputSource, self).__init__(system_id)
627        self.file = file
628        if isinstance(file, TextIOBase):  # Python3 unicode fp
629            self.setCharacterStream(file)
630            self.setEncoding(file.encoding)
631            try:
632                b = file.buffer  # type: ignore[attr-defined]
633                self.setByteStream(b)
634            except (AttributeError, LookupError):
635                self.setByteStream(BytesIOWrapper(file, encoding=file.encoding))
636        else:
637            if TYPE_CHECKING:
638                assert isinstance(file, BufferedReader)
639            self.setByteStream(file)
640            if encoding is not None:
641                self.setEncoding(encoding)
642                self.setCharacterStream(TextIOWrapper(file, encoding=encoding))
643            else:
644                # We cannot set characterStream here because
645                # we do not know the Raw Bytes File encoding.
646                pass
647
648    def __repr__(self) -> str:
649        return repr(self.file)
650
651
652def create_input_source(
653    source: Optional[
654        Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
655    ] = None,
656    publicID: Optional[str] = None,  # noqa: N803
657    location: Optional[str] = None,
658    file: Optional[Union[BinaryIO, TextIO]] = None,
659    data: Optional[Union[str, bytes, dict]] = None,
660    format: Optional[str] = None,
661) -> InputSource:
662    """
663    Return an appropriate InputSource instance for the given
664    parameters.
665    """
666
667    # test that exactly one of source, location, file, and data is not None.
668    non_empty_arguments = list(
669        filter(
670            lambda v: v is not None,
671            [source, location, file, data],
672        )
673    )
674
675    if len(non_empty_arguments) != 1:
676        raise ValueError(
677            "exactly one of source, location, file or data must be given",
678        )
679
680    input_source = None
681
682    if source is not None:
683        if TYPE_CHECKING:
684            assert file is None
685            assert data is None
686            assert location is None
687        if isinstance(source, InputSource):
688            input_source = source
689        else:
690            if isinstance(source, str):
691                location = source
692            elif isinstance(source, pathlib.PurePath):
693                location = str(source)
694            elif isinstance(source, bytes):
695                data = source
696            elif hasattr(source, "read") and not isinstance(source, Namespace):
697                f = source
698                input_source = InputSource()
699                if hasattr(source, "encoding"):
700                    input_source.setCharacterStream(source)
701                    input_source.setEncoding(source.encoding)
702                    try:
703                        b = source.buffer  # type: ignore[union-attr]
704                        input_source.setByteStream(b)
705                    except (AttributeError, LookupError):
706                        input_source.setByteStream(source)
707                else:
708                    input_source.setByteStream(f)
709                if f is sys.stdin:
710                    input_source.setSystemId("file:///dev/stdin")
711                elif hasattr(f, "name"):
712                    input_source.setSystemId(f.name)
713            else:
714                raise Exception(
715                    "Unexpected type '%s' for source '%s'" % (type(source), source)
716                )
717
718    absolute_location = None  # Further to fix for issue 130
719
720    auto_close = False  # make sure we close all file handles we open
721
722    if location is not None:
723        if TYPE_CHECKING:
724            assert file is None
725            assert data is None
726            assert source is None
727        (
728            absolute_location,
729            auto_close,
730            file,
731            input_source,
732        ) = _create_input_source_from_location(
733            file=file,
734            format=format,
735            input_source=input_source,
736            location=location,
737        )
738
739    if file is not None:
740        if TYPE_CHECKING:
741            assert location is None
742            assert data is None
743            assert source is None
744        input_source = FileInputSource(file)
745
746    if data is not None:
747        if TYPE_CHECKING:
748            assert location is None
749            assert file is None
750            assert source is None
751        if isinstance(data, dict):
752            input_source = PythonInputSource(data)
753            auto_close = True
754        elif isinstance(data, (str, bytes, bytearray)):
755            input_source = StringInputSource(data)
756            auto_close = True
757        else:
758            raise RuntimeError(f"parse data can only str, or bytes. not: {type(data)}")
759
760    if input_source is None:
761        raise Exception("could not create InputSource")
762    else:
763        input_source.auto_close |= auto_close
764        if publicID is not None:  # Further to fix for issue 130
765            input_source.setPublicId(publicID)
766        # Further to fix for issue 130
767        elif input_source.getPublicId() is None:
768            input_source.setPublicId(absolute_location or "")
769        return input_source
770
771
772def _create_input_source_from_location(
773    file: Optional[Union[BinaryIO, TextIO]],
774    format: Optional[str],
775    input_source: Optional[InputSource],
776    location: str,
777) -> Tuple[URIRef, bool, Optional[Union[BinaryIO, TextIO]], Optional[InputSource]]:
778    # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 and
779    # https://github.com/RDFLib/rdflib/issues/1430
780    # NOTE: using pathlib.Path.exists on a URL fails on windows as it is not a
781    # valid path. However os.path.exists() returns false for a URL on windows
782    # which is why it is being used instead.
783    if os.path.exists(location):
784        location = pathlib.Path(location).absolute().as_uri()
785
786    base = pathlib.Path.cwd().as_uri()
787
788    absolute_location = URIRef(rdflib.util._iri2uri(location), base=base)
789
790    if absolute_location.startswith("file:///"):
791        filename = url2pathname(absolute_location.replace("file:///", "/"))
792        file = open(filename, "rb")
793    else:
794        input_source = URLInputSource(absolute_location, format)
795
796    auto_close = True
797    # publicID = publicID or absolute_location  # Further to fix
798    # for issue 130
799
800    return absolute_location, auto_close, file, input_source