Beispiel #1
0
    def validate_absolute_path(self, root, absolute_path):
        try:
            in_memory_file_manager.get(absolute_path)
        except KeyError:
            LOGGER.error("InMemoryFileManager: Missing file %s" % absolute_path)
            raise tornado.web.HTTPError(404, "not found")

        return absolute_path
Beispiel #2
0
    def test_st_image_PIL_array(self):
        """Test st.image with a PIL array."""
        imgs = [
            Image.new("RGB", (64, 64), color="red"),
            Image.new("RGB", (64, 64), color="blue"),
            Image.new("RGB", (64, 64), color="green"),
        ]

        st.image(
            imgs,
            caption=["some caption"] * 3,
            width=200,
            use_column_width=True,
            clamp=True,
            output_format="PNG",
        )

        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.imgs.width, -2)

        # locate resultant file in the file manager and check its metadata.
        from streamlit.elements.image import _PIL_to_bytes

        for idx in range(len(imgs)):
            file_id = _calculate_file_id(
                _PIL_to_bytes(imgs[idx], format="PNG"), "image/png"
            )
            self.assertEqual(el.imgs.imgs[idx].caption, "some caption")
            self.assertTrue(file_id in in_memory_file_manager)
            afile = in_memory_file_manager.get(file_id)
            self.assertEqual(afile.mimetype, "image/png")
            self.assertEqual(afile.url, el.imgs.imgs[idx].url)
Beispiel #3
0
    def set_extra_headers(self, path: str) -> None:
        """Add Content-Disposition header for downloadable files.

        Set header value to "attachment" indicating that file should be saved
        locally instead of displaying inline in browser.

        We also set filename to specify filename for  downloaded file.
        Used for serve downloadable files, like files stored
        via st.download_button widget
        """
        in_memory_file = in_memory_file_manager.get(path)

        if in_memory_file and in_memory_file.file_type == FILE_TYPE_DOWNLOADABLE:
            file_name = in_memory_file.file_name

            if not file_name:
                title = self.get_argument("title", "", True)
                title = unquote_plus(title)
                filename = generate_download_filename_from_title(title)
                file_name = (
                    f"{filename}{_get_extension_for_mimetype(in_memory_file.mimetype)}"
                )

            try:
                file_name.encode("ascii")
                file_expr = 'filename="{}"'.format(file_name)
            except UnicodeEncodeError:
                file_expr = "filename*=utf-8''{}".format(quote(file_name))

            self.set_header("Content-Disposition", f"attachment; {file_expr}")
Beispiel #4
0
    def get_content(cls, abspath, start=None, end=None):
        LOGGER.debug("MediaFileHandler: GET %s" % abspath)

        try:
            # abspath is the hash as used `get_absolute_path`
            in_memory_file = in_memory_file_manager.get(abspath)
        except:
            LOGGER.error("InMemoryFileManager: Missing file %s" % abspath)
            return

        LOGGER.debug(
            "InMemoryFileManager: Sending %s file %s"
            % (in_memory_file.mimetype, abspath)
        )

        # If there is no start and end, just return the full content
        if start is None and end is None:
            return in_memory_file.content

        if start is None:
            start = 0
        if end is None:
            end = len(in_memory_file.content)

        # content is bytes that work just by slicing supplied by start and end
        return in_memory_file.content[start:end]
Beispiel #5
0
    def get_content_size(self):
        abspath = self.absolute_path
        if abspath is None:
            return 0

        in_memory_file = in_memory_file_manager.get(abspath)
        return in_memory_file.content_size
Beispiel #6
0
    def test_st_audio(self):
        """Test st.audio."""

        # Fake audio data: expect the resultant mimetype to be audio default.
        fake_audio_data = "\x11\x22\x33\x44\x55\x66".encode("utf-8")

        st.audio(fake_audio_data)

        el = self.get_delta_from_queue().new_element

        # locate resultant file in InMemoryFileManager and test its properties.
        file_id = _calculate_file_id(fake_audio_data, "audio/wav")
        self.assertTrue(file_id in in_memory_file_manager)

        afile = in_memory_file_manager.get(file_id)
        self.assertEqual(afile.mimetype, "audio/wav")
        self.assertEqual(afile.url, el.audio.url)

        # Test using generated data in a file-like object.

        sampleRate = 44100
        frequency = 440
        length = 5

        t = np.linspace(0, length,
                        sampleRate * length)  #  Produces a 5 second Audio-File
        y = np.sin(frequency * 2 * np.pi * t)  #  Has frequency of 440Hz

        wavfile.write("test.wav", sampleRate, y)

        with io.open("test.wav", "rb") as f:
            st.audio(f)

        el = self.get_delta_from_queue().new_element
        self.assertTrue(".wav" in el.audio.url)

        os.remove("test.wav")

        # Test using a URL instead of data
        some_url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"
        st.audio(some_url)

        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.audio.url, some_url)

        # Test that a non-URL string is assumed to be a filename
        bad_filename = "blah"
        with self.assertRaises(FileNotFoundError):
            st.audio(bad_filename)

        # Test that we can use an empty/None value without error.
        st.audio(None)
        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.audio.url, "")

        # Test that our other data types don't result in an error.
        st.audio(b"bytes_data")
        st.audio("str_data".encode("utf-8"))
        st.audio(BytesIO(b"bytesio_data"))
        st.audio(np.array([0, 1, 2, 3]))
Beispiel #7
0
    def test_st_video(self):
        """Test st.video."""

        # Make up some bytes to pretend we have a video.  The server should not vet
        # the video before sending it to the browser.
        fake_video_data = "\x12\x10\x35\x44\x55\x66".encode("utf-8")

        st.video(fake_video_data)

        el = self.get_delta_from_queue().new_element

        # locate resultant file in InMemoryFileManager and test its properties.
        file_id = _calculate_file_id(fake_video_data, "video/mp4")
        self.assertTrue(file_id in in_memory_file_manager)

        afile = in_memory_file_manager.get(file_id)
        self.assertEqual(afile.mimetype, "video/mp4")
        self.assertEqual(afile.url, el.video.url)

        # Test with an arbitrary URL in place of data
        some_url = "http://www.marmosetcare.com/video/in-the-wild/intro.webm"
        st.video(some_url)
        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.video.url, some_url)

        # Test with sufficiently varied youtube URLs
        yt_urls = (
            "https://youtu.be/_T8LGqJtuGc",
            "https://www.youtube.com/watch?v=kmfC-i9WgH0",
            "https://www.youtube.com/embed/sSn4e1lLVpA",
        )
        yt_embeds = (
            "https://www.youtube.com/embed/_T8LGqJtuGc",
            "https://www.youtube.com/embed/kmfC-i9WgH0",
            "https://www.youtube.com/embed/sSn4e1lLVpA",
        )
        # url should be transformed into an embed link (or left alone).
        for x in range(0, len(yt_urls)):
            st.video(yt_urls[x])
            el = self.get_delta_from_queue().new_element
            self.assertEqual(el.video.url, yt_embeds[x])

        # Test that a non-URL string is assumed to be a filename
        bad_filename = "blah"
        with self.assertRaises(FileNotFoundError):
            st.video(bad_filename)

        # Test that we can use an empty/None value without error.
        st.video(None)
        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.video.url, "")

        # Test that our other data types don't result in an error.
        st.video(b"bytes_data")
        st.video("str_data".encode("utf-8"))
        st.video(BytesIO(b"bytesio_data"))
        st.video(np.array([0, 1, 2, 3]))
Beispiel #8
0
    def test_st_image_PIL_image(self):
        """Test st.image with PIL image."""
        img = Image.new("RGB", (64, 64), color="red")

        st.image(img, caption="some caption", width=100, output_format="PNG")

        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.imgs.width, 100)
        self.assertEqual(el.imgs.imgs[0].caption, "some caption")

        # locate resultant file in the file manager and check its metadata.
        from streamlit.elements.image import _PIL_to_bytes

        file_id = _calculate_file_id(_PIL_to_bytes(img, format="PNG"), "image/png")
        self.assertTrue(file_id in in_memory_file_manager)

        afile = in_memory_file_manager.get(file_id)
        self.assertEqual(afile.mimetype, "image/png")
        self.assertEqual(afile.url, el.imgs.imgs[0].url)
Beispiel #9
0
 def get_content_size(self):
     in_memory_file = in_memory_file_manager.get(self.absolute_path)
     return in_memory_file.content_size