<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jason on Medium]]></title>
        <description><![CDATA[Stories by Jason on Medium]]></description>
        <link>https://medium.com/@xuzhusheng?source=rss-41bd992616fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WvSeAJwGVusKLkQSyDG6qw.jpeg</url>
            <title>Stories by Jason on Medium</title>
            <link>https://medium.com/@xuzhusheng?source=rss-41bd992616fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:10:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xuzhusheng/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Watermark Image with Python Pillow]]></title>
            <link>https://python.plainenglish.io/watermark-image-with-python-pillow-9d3433b19f43?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3433b19f43</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pillow]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 04:16:40 GMT</pubDate>
            <atom:updated>2024-09-03T02:40:28.309Z</atom:updated>
            <content:encoded><![CDATA[<h4>Image Processing</h4><h4>A Step-by-Step Guide</h4><p>In this article, we are going to discover how to watermark an image with a Python pillow. At the end of this article, we will create a rotated, translucent text watermark as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CefWIhTvG1yXVwRzhrP4pA.png" /><figcaption>Image Watermarked with Transparent Text</figcaption></figure><p>Before we start, let’s review Python Pillow first.</p><h3>Python Pillow</h3><p>The Python Imaging Library adds image processing capabilities to your Python interpreter.</p><p>This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities.</p><p>Python Pillow is a Python Image Library(PIL) for manipulating images. It supports different formats of images(e.g. ‘jpeg’, ‘png’, ‘gif’, ‘tiff’ etc.). We could use pillow for resizing, rotating, merging images, creating watermarks etc.</p><h4>Installation</h4><p>We could install pillow by following comand:</p><pre>pip install pillow</pre><h3>Watermark Image with Pillow</h3><p>In this section, we are going to crate a watermark for an image. We needs modules: Image, ImageDraw, ImageFont in pillow to create watermark .</p><p><strong>Import libaries:</strong></p><pre>from PIL import Image, ImageDraw, ImageFont</pre><h4>Creating Text Watermark</h4><p>We are going to creat image in 3 step: load image, load font, and draw text on image.</p><p><strong>Step 1</strong>: Loading image.</p><pre>img = Image.open(&quot;image.jpg&quot;)<br>img</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZPH36m-m3h_9g9VtHxFmQ.png" /><figcaption>Origin Image</figcaption></figure><p><strong>Step 2</strong>: Loading fonts. We use system default font. The script as below:</p><pre>font = ImageFont.load_default(font_size)  #font_size is the caculated font size</pre><p><strong>Step 3</strong>: Drawing text.</p><pre>drawing = ImageDraw.Draw(img)  # retrieve the drawing context<br>drawing.text(<br>    xy=(x, y),<br>    text=watermark_text,<br>    fill=(255, 255, 255, 100),<br>    anchor=&quot;mm&quot;,<br>    align=&quot;middle&quot;,<br>    font=font,<br>)</pre><p><strong>Parameters for ImageDraw.text():</strong></p><ul><li><em>xy — The anchor coordinates of the text.</em></li><li><em>text — Text to be drawn.</em></li><li><em>fill — Text color.</em></li><li><em>anchor — The text anchor alignment. Determines the relative location of the anchor to the text. “mm” is both horizontally and vertically centered with the text.</em></li><li><em>font — Text Font.</em></li></ul><h4>The completed codes for creating a text wartermark</h4><pre>from PIL import Image, ImageDraw, ImageFont<br><br>img = Image.open(&quot;image.jpg&quot;)<br>width, height = img.size<br>x, y = width / 2, height / 2<br>watermark_text = &quot;XUZHUSHENG.MEDIUM.COM&quot;<br>font_size = width / len(watermark_text) #calulate the font size<br>font = ImageFont.load_default(font_size)<br>drawing = ImageDraw.Draw(img)<br>drawing.text(<br>    (x, y),<br>    text=watermark_text,<br>    fill=(255, 255, 255, 100),<br>    anchor=&quot;mm&quot;,<br>    align=&quot;middle&quot;,<br>    font=font,<br>)<br>img</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIbavcrtXpTsrPfC6PmnjA.png" /><figcaption>Watermarked Image</figcaption></figure><h3>Rotating Text</h3><p>We can not rotate text or draw text with any angle directly by ImageDraw.text() function. To rotate text, we need to draw it on another image and then rotate the text image and merge with the original image. Let’s see how to create new image and draw rotated text on it:</p><pre>txt = Image.new(&quot;L&quot;, img.size)  # create new image with the same size as the original image<br>drawing = ImageDraw.Draw(txt)<br>drawing.text(<br>    xy=(x, y),<br>    text=watermark_text,<br>    fill=255,<br>    anchor=&quot;mm&quot;,<br>    font=font,<br>)<br>rotated = txt.rotate(-45)  # rotate image</pre><p>And the merge with Image.paste():</p><pre>img.paste(im=(255, 255, 255), mask=rotated)</pre><p><strong>Parameters for Image.paste():</strong></p><ul><li><em>im — Pixel value.</em></li><li><em>mask — Mask image, make sure it paste only the text area of the source image.</em></li></ul><h4>Completed codes</h4><pre>from PIL import Image, ImageDraw, ImageFont, ImageOps<br><br>img = Image.open(&quot;image.jpg&quot;)<br>width, height = img.size<br>x, y = width / 2, height / 2<br>watermark_text = &quot;XUZHUSHENG.MEDIUM.COM&quot;<br>font_size = width / len(watermark_text)<br>font = ImageFont.load_default(font_size)<br>txt = Image.new(&quot;L&quot;, img.size)<br>drawing = ImageDraw.Draw(txt)<br>drawing.text(<br>    xy=(x, y),<br>    text=watermark_text,<br>    fill=255,<br>    anchor=&quot;mm&quot;,<br>    font=font,<br>)<br>rotated = txt.rotate(-45)<br>img.paste(im=(255, 255, 255), mask=rotated)<br>img</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i16QNbnc5MzJqdXAGNc5LA.png" /><figcaption>Image Watermarked with Rotated Text</figcaption></figure><h3>Making Text Transparent</h3><p>Making text transparent is easy. SinceImage.paste() function support alpha mask, we just need to change the fill value of the mask image to the alpha value. Here is the changes from above codes:</p><pre>alpha = 100 # value in range 0 - 255, 100 means 100/255 transparency<br>drawing.text(<br>    xy=(x, y),<br>    text=watermark_text,<br>    fill_color=alpha,<br>    anchor=&quot;mm&quot;,<br>    font=font,<br>)<br>rotated = txt.rotate(-45)<br>img.paste(im=(255, 255, 255), mask=rotated)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CefWIhTvG1yXVwRzhrP4pA.png" /><figcaption>Image Watermarked with Transparent Text</figcaption></figure><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p><em>👏 Please </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> me.</em></p><p><em>📬 </em><a href="https://medium.com/@xuzhusheng/subscribe"><em>Subscribe</em></a><em> to my Medium newsletter for email updates!</em></p><p><em>☕ or just </em><a href="https://www.buymeacoffee.com/jason.xu"><em>buy me a coffee</em></a><em>.</em></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3433b19f43" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/watermark-image-with-python-pillow-9d3433b19f43">Watermark Image with Python Pillow</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constructs Bounding Volume Hierarchy(BVH) with Surface Area Heuristic(SAH) in Python]]></title>
            <link>https://python.plainenglish.io/constructs-bounding-volume-hierarchy-bvh-with-surface-area-heuristic-sah-in-python-89c14afb2f03?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c14afb2f03</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 11:01:47 GMT</pubDate>
            <atom:updated>2024-03-22T02:52:20.213Z</atom:updated>
            <content:encoded><![CDATA[<h4>algorithm</h4><h4>A step by step guide go build Bounding Volume Hierarchy(BVH) with Surface Area Heuristic(SAH) in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t76pREm7YKp9PbBg" /><figcaption>Photo by <a href="https://unsplash.com/@dkoi?utm_source=medium&amp;utm_medium=referral">D koi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Bounding volume hierarchy</strong> (<strong>BVH</strong>) is an advanced data structure widely used in computer graphics, especially in ray tracing algorithms. It is uesed to effectively organize geometric data, such as polygons or triangles that compose a 3D model, such as 3d-tiles. All geometric objects, which form the leaf nodes of the tree, are wrapped in bounding volumes.</p><p>In this article, we are going to explore how to construct bounding volume hierarchy (BVH) with Surface Area Heuristic(SAH).</p><h3><strong>Bounding Volume Hierarchy</strong> Data Structure</h3><p>Bounding volume hierarchy (BVH) is a tree structure on a set of geometric objects.</p><ul><li>All geometric objects, which form the leaf nodes of the tree, are wrapped in bounding volumes.</li><li>These nodes are then grouped as small sets and enclosed within larger bounding volumes. These, in turn, are also grouped and enclosed within other larger bounding volumes in a recursive fashion, forming the hierarchy of the tree.</li><li>A bounding volume can take various forms, such as a sphere, a box (AABB — Axis Aligned Bounding Box), or an oriented bounding box (OBB), depending on the application’s specific requirements.</li></ul><p>Here is a example of a bounding volume hierarchy using rectangles as bounding volumes from <a href="https://en.wikipedia.org/">wikipedia</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*oFx736LEYo1tuK4gji3fCg.png" /></figure><h3>Surface Area Heuristic</h3><p>A common method for constructing a high-quality BVH is using the Surface Area Heuristic. The idea of using SAH is based on two main principles:</p><ol><li>Minimize the probability of intersection for BHV nodes</li><li>The probability of intersection of a node is proportional to its surface area, under certain conditions.</li></ol><h4>SAH Formula</h4><p>Here is the SAH formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*9xrJTx8W-9owWJWh" /></figure><ul><li><em>C(A, B) — the cost for splitting a node into volumes A and B</em></li><li><em>t_traversal — the time to traverse an interior node</em></li><li><em>P(A) and P(B) — the probabilities that the ray passes through the volumes A and B</em></li><li><em>N_A and N_B — are the number of triangles in volumes A and B</em></li><li><em>a_i and b_i — are the ith triangle in volumes A and B</em></li><li><em>t_intersect - is the cost for one ray-triangle intersection.</em></li></ul><p>We can compute P(A) and P(B) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/0*l1SaElXNgQ_y6jw_" /></figure><ul><li><em>C — the parent node of A and B</em></li><li><em>S_A, S_B, and S_C — the surface areas of volumes A, B and C (We can simply compute the surface area of a node by summing all faces of a node)</em></li><li><em>P(A|C) and P(B|C) — the conditional probability that a random ray passing through C will also pass through A or B, given that A or B is a convex volume in another convex volume C.</em></li></ul><p>Replace P(A) and P(B) at the SAH formula, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*2I9CU-aGMMgXfAQX" /></figure><p>Since our goal is find the minimal cost, the actual cost value does not matter. Assume t_traversal as the constant 0, and t_intersect as the constant 1, we get a simplify form of SAH formula：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*7oJo7Vz07tPs3If-" /></figure><p>Here is the scripts to calculate SAH cost:</p><pre>def sah_cost(surface_area, count):<br>    return surface_area * count</pre><h3>Constructing BVH with SAH</h3><h4>Preparing Data</h4><p>we generates 10 triangles as testing data for construction BVH as followed figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*qfKAzgmjDCCFpS7LvpadHQ.png" /></figure><p>Here is the generation scripts:</p><pre>import numpy as np<br><br>np.random.seed(202403)<br><br>MIN_ANGLE = np.pi / 6<br>MAX_ANGLE = np.pi / 2<br><br>def make_triangle(max_length, max_translation):<br>    edge_a, edge_b = np.random.uniform(1, max_length, size = 2)<br>    alpha = np.random.uniform(0, np.pi * 2)<br>    beta = alpha + np.random.uniform(MIN_ANGLE, MAX_ANGLE)<br>    point_a = edge_a * np.cos(alpha), edge_a * np.sin(alpha)<br>    point_b = edge_b * np.cos(beta), edge_a * np.sin(beta)<br>    points = np.array([(0, 0), point_a, point_b])<br>    translation = np.random.uniform(max_length, max_translation, size=(1, 2))<br>    return points + translation<br><br>TRINGLES_NUM = 10<br>triangles = [make_triangle(3, 27) for _ in range(TRINGLES_NUM)]</pre><h4>Bounding Volume — AABB</h4><p>We use AABB(Axis Aligned Bounding Box) to wrap geometries. An minimal AABB class must have below fields and methods:</p><p><strong>Fields:</strong></p><ul><li><em>centroid — used to sort nodes before spliting nodes to two groups</em></li><li><em>surface_area — calculated surface area, used to calculate SAH cost</em></li></ul><p><strong>Methods:</strong></p><ul><li><em>union — calcualte the new bounding volume when merging boxes</em></li></ul><p>Here is the scripts for box class:</p><pre>class Box2:<br>    def __init__(self, min=[np.inf] * 2, max = [-np.inf] * 2) -&gt; None:<br>        self.__min = np.array(min)<br>        self.__max = np.array(max)<br>        <br>    @classmethod<br>    def from_geometries(cls, geometries):<br>        return cls(geometries.min(0), geometries.max(0))<br>    <br>    @property<br>    def anchor(self):<br>        return self.__min<br>    <br>    @property<br>    def size(self):<br>        return self.__max - self.__min<br>    <br>    @property<br>    def centroid(self):<br>        return ((self.__max + self.__min) / 2).tolist()<br>    <br>    @property<br>    def min(self):<br>        return self.__min<br><br>    @property<br>    def max(self):<br>        return self.__max<br>    <br>    def union(self, box):<br>        self.__max = np.maximum(self.__max, box.max)<br>        self.__min = np.minimum(self.__min, box.min)<br>        return self<br>    <br>    @property<br>    def surface_area(self):<br>        width, height = self.size<br>        return width * height</pre><h4>BVH Node</h4><p>A BVH node is tree node with geometries data and bounding volume. Here is the scrpts:</p><pre>class Node:<br>    def __init__(self, geometries = None) -&gt; None:<br>        self.geometries = geometries<br>        self.left = None<br>        self.right = None<br>    <br>    def add_children(self, left = None, right = None):<br>        self.left = left<br>        self.right = right<br>        <br>        return self<br>        <br>    @property    <br>    def box(self):<br>        if self.geometries is not None:<br>            return Box2.from_geometries(self.geometries)<br>        <br>        box = Box2()<br>        if self.left:<br>            box.union(self.left.box)<br>            <br>        if self.right:<br>            box.union(self.right.box)<br>            <br>        return box<br>        </pre><h4>Splitting Nodes at Minimal Cost on One Axis</h4><p>We find the split with minimal cost in 3 steps:</p><ol><li><em>Sorts nodes by the controid of bounding box</em></li><li><em>Calculates SAH cost for every possible split</em></li><li><em>Finds the split with minimal cost</em></li></ol><p>Here is the scripts:</p><pre>def calculate_split_costs(nodes):<br>    box = Box2()<br>    costs = []<br>    for i, node in enumerate(nodes, 1):<br>        box = box.union(node.box)<br>        costs.append(sah_cost(box.surface_area, i))<br><br>    return costs[:-1]<br><br>def find_min_cost_split(nodes, axis):    <br>    sorted_nodes = sorted(nodes, key=lambda node: node.box.centroid[axis])<br>    left_costs = calculate_split_costs(sorted_nodes)<br>    <br>    right_costs = reversed(calculate_split_costs(list(reversed(sorted_nodes))))<br>    costs = list(<br>        map(lambda l, r: l + r, left_costs, right_costs))<br>    min_cost = min(costs)<br>    split_index = np.argmin(costs) + 1<br>    return min_cost, split_index</pre><h4>Building BVH Tree</h4><p>The last is actually build the tree. The building can be done in steps:</p><ol><li><em>Return the node if there is only one node left; Return an interior with two nodes as children if there are two nodes left</em></li><li><em>Finds the axis and split index with minimal cost</em></li><li><em>Sorts the nodes by centroid of bounding box on the axis</em></li><li><em>Splits the nodes to two group</em></li><li><em>Repeats steps 1–4 recursively for both splited group until there are less then 3 nodes</em></li></ol><p>Let’s show an animation of splitting process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*B1uyiDUZoF2ubtXdrJuEDg.gif" /></figure><p>Here is the scripts:</p><pre>DIMENSIONS = 2<br><br>def build_bvh(nodes):<br>    if len(nodes) == 1:<br>        return nodes[0]<br>    <br>    if len(nodes) == 2:<br>        return Node().add_children(*nodes)<br>    <br>    min_costs_splits = [find_min_cost_split(nodes, axis) for axis in range(DIMENSIONS)]<br>    axis, _ = np.argmin(min_splits, 0, keepdims=False)<br>    _ , split_index = min_splits[axis]<br>    sorted_nodes = sorted(nodes, key=lambda node: node.box.centroid[axis])<br>    return Node().add_children(left = build_bvh(sorted_nodes[:split_index]), right = build_bvh(sorted_nodes[split_index:]))<br><br>nodes = list(map(Node, triangles))<br>tree = build_bvh(nodes)</pre><h3>What About 3 Dimensions?</h3><p>We’ve covered building BVH for 2 dimensions. For 3 dimensions, we need only little changes for calculating the surface area. We create a class Box3 for this.</p><pre>class Box3(Box2):<br>    <br>    @property<br>    def surface_area(self):<br>        a, b, c = self.size<br>        return a * b + b * c + c * a</pre><p>The last thing to do is update the constant DIMENSIONS to 3 and replace Box2 with Box3.</p><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c14afb2f03" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/constructs-bounding-volume-hierarchy-bvh-with-surface-area-heuristic-sah-in-python-89c14afb2f03">Constructs Bounding Volume Hierarchy(BVH) with Surface Area Heuristic(SAH) in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D Affine Transformation Matrices Implementation with NumPy]]></title>
            <link>https://python.plainenglish.io/3d-affine-transformation-matrices-implementation-with-numpy-57f92058403c?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/57f92058403c</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 04:01:07 GMT</pubDate>
            <atom:updated>2024-03-22T02:53:10.004Z</atom:updated>
            <content:encoded><![CDATA[<h4>3D Affine Transformation</h4><h4>Explores 3D affine transformation matrices and implements it with NumPy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YhbgLSfLA9RgoDNE" /><figcaption>Photo by <a href="https://unsplash.com/@mariolagr?utm_source=medium&amp;utm_medium=referral">MARIOLA GROBELSKA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In computer graphics, afﬁne transformation is the most general transformations model. Any combination of translation, rotations, scalings/reﬂections and shears can be combined in a single 4 by 4 afﬁne transformation matrix.</p><p>In this article, we are going to explore common 3d affine transformation matrices and implement it with NumPy.</p><h3><strong>3D Affine Transformation Matrices</strong></h3><p>Here is a afﬁne transformation matrix that transforms point (or vector) x to point (or vector) y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/0*RcVfjT1NLncBvUDl" /></figure><p>The upper-left 3 × 3 sub-matrix of the matrix represents a rotation transform (include scales and shears). The last column of the matrix represents a translation. When used as a coordinate system, the upper-left 3 x 3 sub-matrix represents an orientation in space while the last column vector represents a position in space. The transformation of point x to point y is obtained by performing the matrix-vector multiplication Mx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/61/0*BOHJ7Z2VcigfKx9I" /></figure><p>The transformation matrix uses homogeneous coordinates, which allow to distinguish between points and vectors. Vectors have a direction and magnitude whereas points are positions. Points and vectors are both represented as mathematical column vectors in homogeneous coordinates. The only difference is points have a 1 in the fourth position whereas vectors have a zero at this position, which removes translation operations (4th column) for vectors.</p><p>The transformation of point x to point y using homogeneous matrix is written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/0*5GRNCeZyUUCvgjum" /></figure><p><strong>Implements matrix with NumPy</strong></p><p>Matrix is easy to be Implemented with NumPy. Let’s see how to construct a matrix with NumPy:</p><pre>import numpy as np<br><br>elements = [<br>    [1,2,3,4],<br>    [4,6,7,8],<br>    [9,10,11,12],<br>    [13,14,15,16]<br>]<br>matrix = np.array(elements)<br>print(matrix)<br># [[ 1  2  3  4]<br>#  [ 4  6  7  8]<br>#  [ 9 10 11 12]<br>#  [13 14 15 16]]</pre><p>Since affine transformation matrix is used to represent object’s rotaion and translation in 3D models, serialization and deserialization is common scenario. Here is code snippets for constructing matrix from list and converting it to a list:</p><pre>import numpy as np<br><br># constructs from list<br>elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]<br>matrix = np.array(elements)<br>matrix = matrix.reshape(4,4)<br>print(matrix)<br># [[ 1  2  3  4]<br>#  [ 5  6  7  8]<br>#  [ 9 10 11 12]<br>#  [13 14 15 16]]<br><br># converts to list<br>print(matrix.reshape(-1).tolist())<br># [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]</pre><h3>Translation</h3><p>A translation operation will translate a point(or an object) from an initial position to a new position based on a linear shift. Here equation of translate a point (x, y, z) to point (x&#39;, y&#39;, z&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/83/0*v6bX_KcpXD19QEsW" /></figure><p>And the transformation matrix form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*9vAyfWIAClT_y9yn" /></figure><p><strong>Implements translation matrix with NumPy</strong></p><pre>def translation_matrix(tx, ty, tz):<br>    matrix = [<br>        [1,0,0,tx],<br>        [0,1,0,ty],<br>        [0,0,1,tz],<br>        [0,0,0,1]<br>    ]<br>    return np.array(matrix)<br><br>np.random.seed(202403)<br><br>tx, ty, tz = np.random.randint(10, size=3)<br>print(tx, ty, tz)   #5 5 2<br><br>matrix = translation_matrix(tx, ty, tz)<br>print(matrix)<br># [[1 0 0 5]<br>#  [0 1 0 5]<br>#  [0 0 1 2]<br>#  [0 0 0 1]]<br><br># translates a point x, y, z<br>x, y, z = np.random.randint(10, size = 3)<br>print(x, y, z)  #3 6 8<br>translated_point = matrix @ [x,y,z,1]<br>print(translated_point[:3]) #[ 8 11 10]<br><br>#decompose translation from translation_matrix<br>tx, ty, tz = matrix[:3,3]<br>print(tx, ty, tz)   #5 5 2</pre><h3>Scaling</h3><p>A scale operation will shift a point(or an object) from an initial position to a new position based on a scaling. Here is the equation of scaling point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/0*-fXUxB6sHg76_ye3" /></figure><p>And the transformation matrix form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*LGM6KAFwo6l-9a3Z" /></figure><p><strong>Implements scaling matrix with NumPy</strong></p><pre>def scaling_matrix(sx, sy, sz):<br>    matrix = [<br>        [sx,0,0,0],<br>        [0,sy,0,0],<br>        [0,0,sz,0],<br>        [0,0,0,1]<br>    ]<br>    <br>    return np.array(matrix)<br><br>np.random.seed(202403)<br><br>sx, sy, sz = np.random.rand(3)<br>print(sx, sy, sz)   #0.5243255319030659 0.4804928539608385 0.07838680854264224<br><br>matrix = scaling_matrix(sx, sy, sz)<br>print(matrix)<br># [[0.52432553 0.         0.         0.        ]<br>#  [0.         0.48049285 0.         0.        ]<br>#  [0.         0.         0.07838681 0.        ]<br>#  [0.         0.         0.         1.        ]]<br><br># scales a point x, y, z<br>x, y, z = np.random.randint(10, size = 3)<br>print(x, y, z)  #6 8 8<br>scaled_point = matrix @ [x,y,z,1]<br>print(scaled_point[:3]) #[3.14595319 3.84394283 0.62709447]</pre><h3>Rotation</h3><p>A rotation operation will shift a point(or an object) from an initial position to a new position based on a rotation about a given axis or any arbitrary vector.</p><p>The rotation matrix is more complex than the scaling and translation matrix since the whole 3x3 upper-left matrix is needed to express complex rotations. It is common to specify arbitrary rotations with a sequence of simpler ones each along one of the three axes. In each case, the rotation is through an angle, about the given axis. Let’s explore rotation matrix around single axis one by one. Notice that the signs of rotation angles are defined using a right-hand rule convention in the following sections.</p><h4><strong>Rotation around the x-axis</strong></h4><p>Here is the matrix for rotating a point through the angle alpha around the x-axis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*f7mNutLhtBwhaV-5" /></figure><p><strong>Implements x-axis rotation matrix with NumPy</strong></p><pre>def rotation_matrix_x(alpha_degree):<br>    alpha_radian = np.deg2rad(alpha_degree)<br>    <br>    rotation_alpha = [<br>        [1, 0, 0, 0],<br>        [0, np.cos(alpha_radian), -np.sin(alpha_radian), 0],<br>        [0, np.sin(alpha_radian), np.cos(alpha_radian), 0],<br>        [0, 0, 0, 1]<br>    ]<br>    <br>    return np.array(rotation_alpha)<br><br>rotated_point = rotation_matrix_x(90) @ [0, 1, 0, 1]<br>print(rotated_point[:3])    #[0.000000e+00 6.123234e-17 1.000000e+00]</pre><h4><strong>Rotation around the y-axis</strong></h4><p>Here is the matrix for rotating a point through the angle beta around the y-axis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*S-iwiCWThje9iEH7" /></figure><p><strong>Implements y-axis rotation matrix with NumPy</strong></p><pre>def rotation_matrix_y(beta_degree):<br>    beta_radian = np.deg2rad(beta_degree)<br><br>    rotation_beta = [<br>        [np.cos(beta_radian), 0, np.sin(beta_radian), 0],<br>        [0, 1, 0, 0],<br>        [-np.sin(beta_radian), 0, np.cos(beta_radian), 0],<br>        [0, 0, 0, 1]<br>    ]<br><br>    return np.array(rotation_beta)<br><br>rotated_point = rotation_matrix_y(90) @ [1, 0, 0, 1]<br>print(rotated_point[:3])    #[ 6.123234e-17  0.000000e+00 -1.000000e+00]</pre><h4><strong>Rotation around the z-axis</strong></h4><p>Here is the matrix for rotating a point through the angle gamma around the z-axis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/0*kYV9Lk6bofzHe5FW" /></figure><p><strong>Implements z-axis rotation matrix with NumPy</strong></p><pre>def rotation_matrix_z(gamma_degree):<br>    gamma_radian = np.deg2rad(gamma_degree)<br><br>    rotation_gamma = [<br>        [np.cos(gamma_radian), -np.sin(gamma_radian), 0, 0],<br>        [np.sin(gamma_radian), np.cos(gamma_radian), 0, 0],<br>        [0, 0, 1, 0],<br>        [0, 0, 0, 1]<br>    ]<br>    <br>    return np.array(rotation_gamma)<br><br>rotated_point = rotation_matrix_z(90) @ [1, 0, 0, 1]<br>print(rotated_point[:3])    #[6.123234e-17 1.000000e+00 0.000000e+00]</pre><h4>General rotation</h4><p>General rotation matrix around 3 axes can be composed by concatenating matrices around each axis using matrix multiplication. Here is a general rotation matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*506QFJ0Nj_SowMTp" /></figure><p><strong>Compose general rotaton matrix with NumPy</strong></p><pre>def rotation_matrix(alpha, beta, gamma):<br>    return rotation_matrix_x(alpha) @ rotation_matrix_y(beta) @ rotation_matrix_z(gamma)<br><br>np.random.seed(202403)<br><br>alpha, beta, gamma = np.random.randint(0, 360, size = 3)<br>print(alpha, beta, gamma)   #165 77 117<br><br>x, y, z = np.random.randint(10, size = 3)<br>print(x, y, z)  #2 3 6<br>rotated_point = rotation_matrix(alpha, beta, gamma) @ [x,y,z,1]<br><br>print(rotated_point[:3]) #[ 5.04067053 -1.65813521 -4.56532892]</pre><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57f92058403c" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/3d-affine-transformation-matrices-implementation-with-numpy-57f92058403c">3D Affine Transformation Matrices Implementation with NumPy</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manipulate JSON with Python Dynamic Object]]></title>
            <link>https://python.plainenglish.io/manipulate-json-with-python-dynamic-object-fe885394d17f?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe885394d17f</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 02:12:37 GMT</pubDate>
            <atom:updated>2024-03-22T02:54:08.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>Code Snippets</h4><h4>Avoid code duplication with python dynamic object</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tmSiQ9rxkxOG1cJX" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JSON (JavaScript Object Notation) is a lightweight, text-based data format used for storing and exchanging data. It’s a simple and flexible way of representing data that can be easily understood and parsed by both humans and machines. JSON has become one of the most popular in standard.</p><p>Python provides variou tools for parsing and manipulating JSON data. JSON string can be parsed into corresponding dictionary or custom python object. It is a commom pratice parse JSON string to custom object. However, we have to define corresponding class in advance. It can be a bunch of codes, especially for complex class.</p><p>In this article, I am going to share my code snippets for mapping JSON to python object without predefined attribtute at my project:</p><p><a href="https://github.com/xuzhusheng/gltf-to-3d-tiles">GitHub - xuzhusheng/gltf-to-3d-tiles: glTF to 3d Tiles Converter. Convert glTF model to Glb, b3dm or 3d tiles format.</a></p><p>Let’s get start we a briefing about JSON data structure we are going to deal with - glTF file.</p><h3>Briefing about The JSON Data Structure</h3><p>The JSON data we are going to manipulate is <strong>glTF</strong> (Graphics Library Transmission Format), a <a href="https://en.wikipedia.org/wiki/List_of_file_formats#3D_graphics">standard file format</a> for <a href="https://en.wikipedia.org/wiki/3D_modeling">three-dimensional scenes and models</a>. Here is a minimal glTF file:</p><pre>{<br>  &quot;scene&quot;: 0,<br>  &quot;scenes&quot; : [<br>    {<br>      &quot;nodes&quot; : [ 0 ]<br>    }<br>  ],<br>  <br>  &quot;nodes&quot; : [<br>    {<br>      &quot;mesh&quot; : 0<br>    }<br>  ],<br>  <br>  &quot;meshes&quot; : [<br>    {<br>      &quot;primitives&quot; : [ {<br>        &quot;attributes&quot; : {<br>          &quot;POSITION&quot; : 1<br>        },<br>        &quot;indices&quot; : 0<br>      } ]<br>    }<br>  ],<br><br>  &quot;buffers&quot; : [<br>    {<br>      &quot;uri&quot; : &quot;data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=&quot;,<br>      &quot;byteLength&quot; : 44<br>    }<br>  ],<br>  &quot;bufferViews&quot; : [<br>    {<br>      &quot;buffer&quot; : 0,<br>      &quot;byteOffset&quot; : 0,<br>      &quot;byteLength&quot; : 6,<br>      &quot;target&quot; : 34963<br>    },<br>    {<br>      &quot;buffer&quot; : 0,<br>      &quot;byteOffset&quot; : 8,<br>      &quot;byteLength&quot; : 36,<br>      &quot;target&quot; : 34962<br>    }<br>  ],<br>  &quot;accessors&quot; : [<br>    {<br>      &quot;bufferView&quot; : 0,<br>      &quot;byteOffset&quot; : 0,<br>      &quot;componentType&quot; : 5123,<br>      &quot;count&quot; : 3,<br>      &quot;type&quot; : &quot;SCALAR&quot;,<br>      &quot;max&quot; : [ 2 ],<br>      &quot;min&quot; : [ 0 ]<br>    },<br>    {<br>      &quot;bufferView&quot; : 1,<br>      &quot;byteOffset&quot; : 0,<br>      &quot;componentType&quot; : 5126,<br>      &quot;count&quot; : 3,<br>      &quot;type&quot; : &quot;VEC3&quot;,<br>      &quot;max&quot; : [ 1.0, 1.0, 0.0 ],<br>      &quot;min&quot; : [ 0.0, 0.0, 0.0 ]<br>    }<br>  ],<br>  <br>  &quot;asset&quot; : {<br>    &quot;version&quot; : &quot;2.0&quot;<br>  }<br>}</pre><p>Let’s save this file as minimal.gltf. We are going to load and convert this file to a dynamic object in next section.</p><h3>Converting JSON to Python Dynamic Object</h3><p>JSON could converted to python object in two steps:</p><ol><li>converts JSON data to a dictionary object by json.load()</li><li>converts dictionary object to dynamic object.</li></ol><p>The second step could be done with the function setattr(). Let’s get into the codes.</p><pre>class GltfModel:<br>    <br>    def __init__(self) -&gt; None:<br>        ...<br><br>    @classmethod<br>    def from_kwargs(cls, **kwargs):<br>        <br>        obj = cls()<br>        <br>        for key, value in kwargs.items():<br>            if type(value) == dict:<br>                setattr(obj, key, cls.from_kwargs(**value))<br>            elif type(value) == list:<br>                setattr(obj, key, [cls.from_kwargs(**item) if type(item) == dict else item for item in value])<br>            elif value is not None:<br>                setattr(obj, key, value)<br>                <br>        return obj</pre><p><strong>Codes walk throuth:</strong></p><ol><li>Defines a class funcion from_kwargs() accepts keyword arguments to create and initialize dynamic object - @classmethod def from_kwargs(cls, **kwargs)</li><li>Creates object from class cls - obj = cls()</li><li>Parses keyword arguments in a loop - for key, value in kwargs.items()</li><li>Creates a nested object attribute by calling cls.from_kwargs() recursively for dict value - if type(value) == dict: setattr(obj, key, cls.from_kwargs(**value))</li><li>Creates an array attribute with primary data type value or nested object for list value - elif type(value) == list: setattr(obj, key, [cls.from_kwargs(**item) if type(item) == dict else item for item in value])</li><li>Creates an attribute with primary data type for other not none value - elif value is not None: setattr(obj, key, value)</li></ol><h3>Access and Manipulate Attributes</h3><p>Afte converted the minial.gltf to a dynamic object, we can access and manipulate attributes with dot notation like model.scene. It is much nicer and cleaner than model[&quot;scene&quot;] or model.get(&quot;scene&quot;). However, there are some optional node in gltf data structure. Correspondingly, there are some optional attributes. If we access any optioanl attribute that does not exist with dot notation model.not_exist_attribute, we will get a AttributeError. To avoid this, we need to override the __getattr__() magic function of class GltfModel:</p><pre>def __getattr__(self, name):<br>        return None</pre><p>Than, if we access any none exist attribute with mode.not_exist_attribute, it return None</p><h3>Naming convention</h3><p>The JSON in minimal.gltf using camal case naming convention violates python PEP 8 standard. I using the code snippets to convert camel case to snake case:</p><pre>import re<br><br>CAMEL_PATTERN = r&#39;(?&lt;!^)(?=[A-Z])&#39;<br>camel_to_snake = lambda name : re.sub(CAMEL_PATTERN, &#39;_&#39;, name).lower()</pre><p>For converting between snake case and camel case, please read my article:</p><p><a href="https://xuzhusheng.medium.com/converting-between-naming-convention-with-python-2d91032bd0dc">Converting between Snake Case and Camel Case</a></p><h3>Conclusion</h3><p>The completed code snippets as below:</p><pre>import re<br><br>CAMEL_PATTERN = r&#39;(?&lt;!^)(?=[A-Z])&#39;<br>camel_to_snake = lambda name : re.sub(CAMEL_PATTERN, &#39;_&#39;, name).lower()<br><br>class GltfModel:<br>    <br>    def __init__(self) -&gt; None:<br>        ...<br><br>    @classmethod<br>    def from_kwargs(cls, **kwargs):<br>        <br>        obj = cls()<br>        <br>        for key, value in kwargs.items():<br>            key = camel_to_snake(key)<br>            if type(value) == dict:<br>                setattr(obj, key, cls.from_kwargs(**value))<br>            elif type(value) == list:<br>                setattr(obj, key, [cls.from_kwargs(**item) if type(item) == dict else item for item in value])<br>            elif value is not None:<br>                setattr(obj, key, value)<br>                <br>        return obj<br><br>    def __getattr__(self, name):<br>        return None<br><br>with open(&quot;minimal.gltf&quot;, encoding=&#39;utf-8&#39;) as f:<br>    data = json.load(f)<br>    <br>gltf = GltfModel.from_kwargs(**data)<br><br>print(gltf.scene) # 0<br>print(gltf.not_exist_attribute) # None</pre><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe885394d17f" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/manipulate-json-with-python-dynamic-object-fe885394d17f">Manipulate JSON with Python Dynamic Object</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting between Snake Case and Camel Case]]></title>
            <link>https://python.plainenglish.io/converting-between-naming-convention-with-python-2d91032bd0dc?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d91032bd0dc</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 14:29:50 GMT</pubDate>
            <atom:updated>2024-03-24T09:47:42.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>code snippets</h4><h4>Elegant Python code snippets for converting between snake case and camel case</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rz_NQ08qJUTzulHH" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I shared my code snippets about manipulate JSON with python dynamic object in my article:</p><p><a href="https://xuzhusheng.medium.com/manipulate-json-with-python-dynamic-object-fe885394d17f">Manipulate JSON with Python Dynamic Object</a></p><p>But the JSON data using camel case, it’s naming convention violates python PEP 8 standard. we need to convert the camel case to snake case.</p><p>In this articl, we are intruduces some elegant code snippets to converting between and camel case. Before we start, let’s review the relative name conventions first.</p><h3>Naming Conventions</h3><p>Here listed the snake case, camel case and pascal case naming conventions:</p><ul><li>Snake Case - Separates the words with underscore, e.g. snake_case</li><li>Camel Case - All words start with a capital letter except the first one, e.g. camelCase</li><li>Pascal Case - All words start with a capital letter, e.g. PascalCase</li></ul><p>Pascal Case is also mentioned above, because pascal case acted as a median naing convention between snake case and camel case. We are converts snake case to pascal case, and then converts pascal case to camel case in coming sesction.</p><p>The only different between camel case and the pascal case is whether the first letter is capital. Let’s warm up with the easiest one, converting between pascal case and camel case.</p><h3>Converting between Pascal Case and Camel Case</h3><p>The only thing we need to do is convert the first letters to upper case or otherwise. The scripts as below:</p><pre>def pascal_to_camel(name):<br>    return name[0].lower() + name[1:]<br><br>print(pascal_to_camel(&quot;CamelCase&quot;)) #camelCase<br><br>def camel_to_pascal(name):<br>    return name[0].upper() + name[1:]<br><br>print(camel_to_pascal(&quot;PascalCase&quot;)) #PascalCase</pre><h3>Snake Case to Pascal Case</h3><p>Converts from snake case to pascal case, we need to convert the first letter of each word to upper case and remove the underscore seperator. Here is the script:</p><pre>def snake_to_pascal(name):<br>    return &#39;&#39;.join(name.title().split(&#39;_&#39;))<br><br>print(snake_to_pascal(&quot;pascal_case&quot;)) # PascalCase</pre><h3>Snake Case to Camel Case</h3><p>Combines snake_to_pascal and pascal_to_camel, we could converts the snake case to camel case:</p><pre>def snake_to_camel(name):<br>    return pascal_to_camel(camel_to_pascal(name))<br><br>print(snake_to_camel(&quot;camel_case&quot;)) # camelCase</pre><h3>Converting to Snake Case</h3><p>Converting camel case or pascal case to snake case is the same. It could be done by 2 steps:</p><ol><li>Inserts a underscore seperator before each upper case letter.</li><li>converts string to lower case.</li></ol><p>It can be done by re.sub() function:</p><pre>import re<br><br>CAMEL_PATTERN = r&#39;(?&lt;!^)(?=[A-Z])&#39;<br><br>def camel_to_snake(name):<br>    return re.sub(CAMEL_PATTERN, &#39;_&#39;, name).lower()<br><br>print(camel_to_snake(&quot;cnakeCase&quot;)) # snake_case</pre><p>Since compile the regex can take times, we could do it beforehand to improve performance:</p><pre>import re<br>CAMEL_PATTERN = re.compile(r&#39;(?&lt;!^)(?=[A-Z])&#39;)<br>def camel_to_snake(name):<br>    return CAMEL_PATTERN.sub(&#39;_&#39;, name).lower()<br><br>print(camel_to_snake(&quot;SnakeCase&quot;)) # snake_case<br>print(camel_to_snake(&quot;HTTPStatus&quot;)) # h_t_t_p_status</pre><p>It was suppose to convert HTTPStatus to http_status. To handle this case, we need a different approach.</p><h4>Advanced Cases (Not Reversible)</h4><p>These cases is <strong>not reversible</strong>, once we convert HTTPStatus to http_status, There is no way we can convert back to HTTPStatus. Also two steps to get it done:</p><ol><li>Looks for every upper case letter that following lower case letter ( letter C in snakeCase ) or followed by lower case letter (letter S in HTTPStatus ), then insert a underscore seperator before each.</li><li>Converts string to lower case.</li></ol><p>Here is the script:</p><pre>ADVANCED_CAMEL_PATTERN = re.compile(r&#39;(?&lt;=[a-z])[A-Z]|(?&lt;!^)[A-Z](?=[a-z])&#39;)<br>def advanced_camel_to_snake(name):<br>    return re.sub(ADVANCED_CAMEL_PATTERN, r&quot;_\g&lt;0&gt;&quot;, name).lower()<br><br>print(advanced_camel_to_snake(&quot;snakeCase&quot;)) # snake_case<br>print(advanced_camel_to_snake(&quot;SnakeCase&quot;))  # snake_case<br>print(advanced_camel_to_snake(&quot;HTTPStatus&quot;)) # http_status<br>print(advanced_camel_to_snake(&quot;HTTPStatusXYZ&quot;)) # http_status_xyz<br>print(advanced_camel_to_snake(&quot;getHTTPStatus&quot;)) # get_http_status<br>print(advanced_camel_to_snake(&quot;GetHTTPStatus&quot;)) # get_http_status</pre><h3>Conclusion</h3><p>We’ve covered code snippets for converting between snake case, camel case and pascal case. I put all of the converting functions together as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0ae932bbd2bffeb19a2c7a0a42b07d1/href">https://medium.com/media/c0ae932bbd2bffeb19a2c7a0a42b07d1/href</a></iframe><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d91032bd0dc" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/converting-between-naming-convention-with-python-2d91032bd0dc">Converting between Snake Case and Camel Case</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loads millions of Rows into MySQL in Seconds]]></title>
            <link>https://python.plainenglish.io/how-to-load-millions-of-rows-csv-data-into-mysql-in-seconds-05805e5c1e39?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/05805e5c1e39</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 11:32:39 GMT</pubDate>
            <atom:updated>2024-03-22T02:57:39.492Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Manipulation</h4><h4>Two efficient methods to load millions of rows CSV data into MySQL in several seconds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8OY5u8tQOpR10Jep" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we are doing data migrations or data cleaning, we might need to load millions of rows CSV data in to database. MySQL is one of the most popular database management system in the world.</p><p>In this article, we will cover two efficient methods to load CSV data to MySQL.</p><h3>Requirement</h3><h4>Preparing Data</h4><p>Suppose we need to load a person.csv file with millions of rows records to MySQL database table. Here is a sample file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d36a65ec9a2e13c8c8db5cce4457ebb9/href">https://medium.com/media/d36a65ec9a2e13c8c8db5cce4457ebb9/href</a></iframe><p>In real practic, our data might exported from another database system or scraped from web. For scraping data from web pages, please read:</p><p><a href="https://xuzhusheng.medium.com/playwright-web-scrapping-in-python-2024-def04f46a129">Scrapes Interactive Pages with Playwright in Python</a></p><p>In this article, we generages csv file with Faker. The generation scripts as below:</p><pre>from aiofile import async_open<br>from faker import Faker<br><br>Faker.seed(2024)    <br>faker = Faker()<br>async with async_open(&quot;person.csv&quot;, &quot;w&quot;, encoding=&quot;UTF-8&quot;) as af:<br>    await af.write(&quot;name, age, birthday, phone_number, email\n&quot;)<br>    for _ in range(1000000):<br>        name = faker.name()<br>        age = faker.pyint(1, 115)<br>        birthday = faker.date_of_birth(minimum_age=1, maximum_age=115)<br>        phone_number = faker.phone_number()<br>        email = faker.ascii_free_email()<br>        line = f&#39;{name}, {age}, {birthday}, {phone_number}, {email}\n&#39;<br>        await af.write(line)</pre><h4>Creating Table</h4><p>We need a table with corresponding columns and a id as primary key as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050a105f26c1afa71a3f11fcbadd20a3/href">https://medium.com/media/050a105f26c1afa71a3f11fcbadd20a3/href</a></iframe><p>Here is the SQL scripts:</p><pre>CREATE TABLE person (<br>    `id` INT auto_increment primary key,<br>    `name` VARCHAR(255) NOT NULL,<br>    `age` TINYINT,<br>    `birthday` DATE NOT NULL,<br>    `phone_number` VARCHAR(30),<br>    `email` VARCHAR(255)<br>);</pre><h3>Loading Data into MySQL</h3><p>Using the LOAD DATA statement is one of the most efficient methods to load data into MySQL. Let’s cover this method first.</p><h4>Using LOAD DATA statement</h4><p>Here is the LOAD DATA scripts:</p><pre>LOAD DATA LOCAL<br>    INFILE &#39;person.csv&#39;<br>    INTO TABLE `person`<br>    FIELDS TERMINATED by &#39;,&#39;<br>    LINES TERMINATED by &#39;\n&#39;<br>    IGNORE 1 LINES<br>    (name, age, birthday, phone_number, email);</pre><p><strong>Codes walk through:</strong></p><ul><li>LOCAL specifies load data from client machine - LOAD DATA LOCAL</li><li>CSV file path - INFILE &#39;person.csv&#39;</li><li>Destination table - INTO TABLE person</li><li>CSV Delimiter - FIELDS TERMINATED by &#39;,&#39;</li><li>Line breaker - LINES TERMINATED by &#39;\n&#39;</li><li>Ignore header - IGNORE 1 LINES</li><li>Column mapping - (name, age, birthday, phone_number, email)</li></ul><p>The local data loading is disabled by default. We can enable it by set the global variable local_infile = &#39;ON&#39;</p><pre>set global local_infile = &#39;ON&#39;</pre><p>Run the script, all of the data in csv file will be loaded into mysql table. The loading take<strong> 6 - 7 seconds</strong> on my computer.</p><p>Using LOAD DATA statement is alway my first option to load huge data into mysql. But what if we are not allowed to enable the local data loading setting? Is there other options?</p><h4>Using pandas</h4><p>pandas is a fast and easy to use open source data analysis and manipulation python library. With pandas, it need just serval line of codes to get our task done.</p><p>Before getting start, we need to install libraries: spandas, sqlalchemy and mysqlclient. Pandas need sqlalchemy and mysqlclient to connect to MySQL database. The installation command as below.</p><pre>pip install pandas<br>pip install sqlalchemy<br>pip install mysqlclient</pre><p>The load data scripts with pandas is very simple. Let’s get into it.</p><pre>import pandas as pd<br>from sqlalchemy import create_engine<br><br>df = pd.read_csv(&quot;person.csv&quot;, skipinitialspace=True)<br>engine = create_engine(&#39;mysql://root@127.0.0.1/db&#39;)<br>df.to_sql(name=&#39;person&#39;, con=engine, if_exists=&#39;append&#39;, index=False)</pre><p><strong>Codes walk through:</strong></p><ul><li>Import the necessary libraries - the first two lines</li><li>Read csv file by pd.read_csv(file) - df = pd.read_csv(“person.csv”, skipinitialspace=True)</li><li>Create engine for database connection by create_engine(url) - engine = create_engine(‘mysql://root@127.0.0.1/db’)</li><li>Load data into MySQL database - df.to_sql(name=’person’, con=engine, if_exists=’append’, index=False)</li></ul><p>This loading take <strong>22–24 seconds</strong> on my computer. It is slower, but it is simple and generic, easy to adapt to other source file format or database.</p><p>We covered two methods for loading data with one million rows. What if there are much more data, hundres of millions rows data?</p><h3>Loading Hundreds of Millions Rows CSV data</h3><p>It is not feasible to load a file with hundres of millions row. In this case, we can split it into many files with one million rows, then load file with above methods. This can be done by the split command.</p><pre> split -d -l 1000000 person.csv person_ --additional-suffix .csv</pre><h3>Conclusion</h3><p>We’ve covered two efficient methods to load huge csv data into mysql database.</p><p>Using LOAD DATA statement is much more faster, but need permission to configurate database server, so that we can enable local data load. When we permission and the loading time is really crucial, using LOAD DATA statement is our choice.</p><p>When we are dealing with varied source file format or varied database, using pandas is more simple and adaptable.</p><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05805e5c1e39" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-load-millions-of-rows-csv-data-into-mysql-in-seconds-05805e5c1e39">Loads millions of Rows into MySQL in Seconds</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Interactive Pages with Playwright in Python]]></title>
            <link>https://python.plainenglish.io/playwright-web-scrapping-in-python-2024-def04f46a129?source=rss-41bd992616fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/def04f46a129</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-automation]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 10:29:51 GMT</pubDate>
            <atom:updated>2024-03-22T02:55:18.424Z</atom:updated>
            <content:encoded><![CDATA[<h4>Web Scraping</h4><h4>Explore how to scrape dynamic interactive pages with scrolling and infinite pagination with a practical example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KI3ciuhZYqQ-NwU7" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we are going to explore how to scrape dynamic page with scrolling and infinite pagination. We scrape pages with Playwright in Python.</p><p>We are going to build a scraper to scrape the historical Snapshot of 21 January 2024 from <a href="https://coinmarketcap.com/historical/20240121/">CoinMarketCap</a>. At the end of this article, we will get a CSV file as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smq1wbAWf4QJu-yGHoq7Pg.png" /><figcaption>CSV File Snapshot</figcaption></figure><h3>What is Playwright</h3><p>Playwright is an open-source cross-platform library built on Node.js. But it is compatible with most popular programming languages, such as Node.js, Python, Java, and .NET. You can use playwright with any of these languages you like.</p><p>Playwright was created for end-to-end testing, it is perfectly capable of browser automation and web scraping. Playwright web scraping has become one of the most popular searched topics recently.</p><h3><strong>Installing Playwright</strong></h3><p>Install playwright is very simple. All we need is install the playwright library by pipcommand and the install the necessary browsers byplaywright install command: pip</p><pre>pip install playwright<br>playwright install</pre><h3>First Playwright script.</h3><p>Playwright supports both synchronous api and asynchronous api. Let’s using asynchronous api to create a basic script to open a dynamic page as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/504f6982c229c3f3a8471f4585e388d3/href">https://medium.com/media/504f6982c229c3f3a8471f4585e388d3/href</a></iframe><p><strong>Codes walk through:</strong></p><ol><li>Imports playwright asynchronous API. (line 1)</li><li>Launches a chromium browser and open a new page. (line 5 — line 7).</li><li>Navigates to the target page by page.goto() function. (line 8)</li><li>Captures the screenshot and saves into “screenshot.png”. (line 9)</li><li>Close the browser at the end. （line 10）</li></ol><p>Run the script, we will get a screenshot as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtU6gpe0zu8AgcNC_htPqg.png" /><figcaption>Screenshot</figcaption></figure><p>Data in the table is what we are going to scrap in next section.</p><h3><strong>Locating elements and Extracting data</strong></h3><p>The first step to extract data from any element is locate the element. Playwright use locators to locate elements on the page.</p><p>Locators are the central piece of Playwright’s ability to locate elements and perform actions automated. Some built in locators of playwright sumarized below.</p><p><strong>Built in locators of playwright summary</strong></p><ul><li>page.get_by_role() to locate by explicit and implicit accessibility attributes.</li><li>page.get_by_text() to locate by text content.</li><li>page.get_by_label() to locate a form control by associated label’s text.</li><li>page.get_by_placeholder() to locate an input by placeholder.</li><li>page.get_by_alt_text()to locate an element, usually image, by its text alternative.</li><li>page.get_by_title() to locate an element by its title attribute.</li><li>page.get_by_test_id() to locate an element based on its data-testid attribute (other attributes can be configured).</li></ul><p>We are going to locate table header element by page.locator() and retireve the header text by locator.inner_text():</p><pre>header = await page.locator(&quot;thead tr&quot;).inner_text()<br>print(header)</pre><p>If we run the script to check result, we will get an error:</p><pre>Error: strict mode violation: locator(“thead tr”) resolved to 3 elements</pre><p>There are three table header elements in the page, we need only the visible one. We filter the rest by locator.locator(&quot;visible=true). The completed codes as below:</p><pre>header = await page.locator(&quot;thead tr&quot;).locator(&quot;visible=true&quot;).inner_text()<br>print(header)</pre><p>Rerun the script, we could see the header text printed as below:</p><pre>Rank Name Symbol Market Cap Price Circulating Supply volume (24h) % 1h % 24h % 7d</pre><p>Let’s get into the whole scripts than locates table elements and retrieves corresponding text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb42a068b6ca298a3292822233b745ff/href">https://medium.com/media/eb42a068b6ca298a3292822233b745ff/href</a></iframe><p><strong>Codes walk through:</strong></p><ol><li>Navigates to the target page. This is the same as first script above. (line 1 - line 10 )</li><li>Locates the table header and extracts the header text by locator.inner_text() function. (line 11)</li><li>Locates all rows of the table body. (line 13)</li><li>Extracts row text and reformat it to print on the screen in a loop. (line 14–18)</li></ol><p>It seems quite simple. Let’s run this example and check the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvYaK4Ie3ep-IcUJvN2mTQ.png" /></figure><p>We got only 20 rows. The rest data is missing. The page load rows visible on screen only. We need to scroll down, so that it could load the rest data.</p><h3><strong>Scrolling and Infinite Pagination</strong></h3><p>Scrolling could be done easy by add row.scroll_into_view_if_needed() before inner_text = await row.inner_text().</p><p>The trick part is pagination. At the bottom of the page, there is a “Load More” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wx1OrTPpP2ywHJESunmLGg.png" /></figure><p>What we need to do is keep clicking the “Load More” button while is clickable. The “Load More” scripts as below:</p><pre>async def has_next_page():<br>    try:<br>        await page.get_by_role(&quot;button&quot;, name=&quot;Load More&quot;).click(trial = True)<br>        return True<br>    except:<br>        return False<br>                        <br>async def load_next_page():<br>    current_page = 1<br>    while await has_next_page():<br>        try:<br>            yield current_page<br>            await page.get_by_role(&quot;button&quot;, name=&quot;Load More&quot;).click(force=True)<br>            current_page += 1<br>        except:<br>            ...<br>    yield current_page</pre><p><strong>Codes walk through</strong></p><ol><li>Function has_next_page() waits for the “Load More” button to be clickable then return Ture. Or return False if any exception. By setting (trial = True), the click() fucntion perform only actionable checks and skips the click action.</li><li>While the “Load More” button is clickable, each time function load_next_page() is called, it clicks the “Load More” button to load next page data.</li></ol><p>Let’s do some refactoring, extracts locates elements and extracts data codes to a data() function. And put the pagnitions codes together.</p><pre>async def data():  <br>    <br>    yield await page.locator(&quot;thead tr&quot;).locator(&quot;visible=true&quot;).inner_text()<br>    <br>    current_row = 0<br>    async for _ in load_next_page():<br>        rows = await page.locator(&quot;tbody tr&quot;).all()<br>        rows = rows[current_row:]<br>        <br>        for row in rows:<br>            await row.wait_for(timeout=0)<br>            await row.scroll_into_view_if_needed(timeout=0)<br>            yield await row.inner_text()<br>            current_row += 1 </pre><p>The current_row index indicates the next row to be parsed. After the “Load More” button is clicked, it parses rows start from current_row to the end.</p><p>The final thing, we save the extracted data in a csv file instead of print it on screen and add a progress bar by tqdm. The completed codes as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86b8cf1e7087305f5408b6b320c61a7/href">https://medium.com/media/c86b8cf1e7087305f5408b6b320c61a7/href</a></iframe><h3>What’s Next</h3><p>In this article, we store scraped data into a CSV file. But in real scraping practic, we deal with thounds of millions of pages, instead of storing data in CSV files, we usually store data into database. One of the most popular database management system MySQL. For loading CSV data into MySQL efficiently, read my article:</p><p><a href="https://xuzhusheng.medium.com/how-to-load-millions-of-rows-csv-data-into-mysql-in-seconds-05805e5c1e39">Loads millions of Records into MySQL in Seconds</a></p><h3>Jason 🚀</h3><p><em>Thank you for reading until the end. Before you go:</em></p><p>👏 Please <strong><em>Clap</em></strong> and <strong><em>follow</em></strong> me</p><p>📬 <a href="https://medium.com/@xuzhusheng/subscribe">Subscribe</a> to my Medium newsletter for email updates!</p><p>☕ or just <a href="https://www.buymeacoffee.com/jason.xu">buy me a coffee</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def04f46a129" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/playwright-web-scrapping-in-python-2024-def04f46a129">Scraping Interactive Pages with Playwright in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>