awacke1's picture
Update app.py
841a32c
raw
history blame
3.06 kB
import streamlit as st
import svgwrite
st.set_page_config(page_title="SVG Optical Illusions", page_icon=":eyeglasses:")
# Define the card suits and values
suits = ["clubs", "diamonds", "hearts", "spades"]
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
# Define the size of the cards
CARD_WIDTH = 75
CARD_HEIGHT = 100
# Define the size of the SVG canvas
CANVAS_WIDTH = CARD_WIDTH * 13
CANVAS_HEIGHT = CARD_HEIGHT * 4
# Create a new SVG drawing
dwg = svgwrite.Drawing(size=(f"{CANVAS_WIDTH}px", f"{CANVAS_HEIGHT}px"))
# Draw each card in the SVG canvas
for suit_idx, suit in enumerate(suits):
for value_idx, value in enumerate(values):
# Calculate the position of the card on the canvas
x = CARD_WIDTH * value_idx
y = CARD_HEIGHT * suit_idx
# Draw the card border
dwg.add(dwg.rect((x, y), (CARD_WIDTH, CARD_HEIGHT), rx=10, ry=10, fill="white", stroke="black", stroke_width=2))
# Draw the card suit symbol
symbol = svgwrite.text.Text(suit.upper(), insert=(x + 5, y + 15), fill="black", font_size="16px", font_weight="bold")
dwg.add(symbol)
# Draw the card value
value = svgwrite.text.Text(value, insert=(x + 5, y + CARD_HEIGHT - 10), fill="black", font_size="16px", font_weight="bold")
dwg.add(value)
# Convert the SVG drawing to a string
svg_string = dwg.tostring()
# Display the SVG canvas in the Streamlit app
st.write(f'<svg viewBox="0 0 {CANVAS_WIDTH} {CANVAS_HEIGHT}">{svg_string}</svg>', unsafe_allow_html=True)
import streamlit as st
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
from io import BytesIO
# Define the SVG images as strings
svg_images = {
'Fraser spiral': """
<svg viewBox="-40 -40 80 80" xmlns="http://www.w3.org/2000/svg">
<g stroke-width="0.4" stroke="black" fill="none">
<path d="M40 0 Q 40 40 0 40 Q -40 40 -40 0 Q -40 -40 0 -40 Q 40 -40 40 0" />
<path d="M-39 1 Q -39 -39 0 -39 Q 38 -39 39 -1" />
<path d="M0 -39 Q 0 1 38 1" />
</g>
</svg>
""",
'Penrose triangle': """
<svg viewBox="-100 -100 200 200" xmlns="http://www.w3.org/2000/svg">
<g fill="none" stroke="black" stroke-width="4">
<path d="M -60 60 L 60 60 L 0 -60 Z" />
<path d="M -60 -60 L 60 -60 L 0 60 Z" />
<path d="M -60 60 L -60 -60 L 60 0 Z" />
<path d="M 60 60 L 60 -60 L -60 0 Z" />
</g>
</svg>
"""
}
# Define the functions to convert SVG to PNG
def svg_to_image(svg_string):
drawing = svg2rlg(BytesIO(svg_string.encode()))
img_data = BytesIO()
renderPM.drawToFile(drawing, img_data, fmt="PNG")
return img_data.getvalue()
# Define the app layout
st.title("SVG Optical Illusions")
# Display the SVG images and convert them to PNG
for name, svg_string in svg_images.items():
st.subheader(name)
svg = st.markdown(svg_string, unsafe_allow_html=True)
png = svg_to_image(svg_string)
st.image(png, use_column_width=True)