<?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 Anuja Shukla on Medium]]></title>
        <description><![CDATA[Stories by Anuja Shukla on Medium]]></description>
        <link>https://medium.com/@anuja-shukla?source=rss-152b45c46c7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ECxfoYTBAEC-gdi1_Nf5_A.jpeg</url>
            <title>Stories by Anuja Shukla on Medium</title>
            <link>https://medium.com/@anuja-shukla?source=rss-152b45c46c7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:15:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anuja-shukla/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[How to Write PySpark DataFrames to S3 Like a Pro (With AWS Glue!) ]]></title>
            <link>https://anuja-shukla.medium.com/how-to-write-pyspark-dataframes-to-s3-like-a-pro-with-aws-glue-c675eb99bd75?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c675eb99bd75</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[techniques]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 15:09:26 GMT</pubDate>
            <atom:updated>2025-02-18T15:09:26.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’ve ever tried to write <strong>millions of records</strong> from a PySpark DataFrame to <strong>Amazon S3</strong>, you probably know the struggle. <strong>Slow writes, too many small files, or just outright failures?</strong> We’ve all been there. 😅</p><p>But fear not! In this guide, we’ll explore <strong>multiple ways to write PySpark DataFrames to S3 using AWS Glue</strong>, compare their speeds, and determine which approach is the best for <strong>speed, efficiency, and sanity</strong>! 🎯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*-4RDr4eH4yX7MsMetIYVTA.png" /></figure><h3>1️⃣ The Default Approach: Just Write It! (But Beware 👀)</h3><h3>Code:</h3><pre>df.write.format(&quot;parquet&quot;).mode(&quot;overwrite&quot;).save(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 2–5 minutes for 10M records</h3><p>✅ Simple to use<br>✅ Supports multiple formats (Parquet, ORC, JSON, CSV)<br>❌ May create <strong>too many small files</strong></p><p>👉 <em>Best for small datasets or quick testing!</em></p><h3>2️⃣ The Parquet Way: Because We Like Speed! ⚡</h3><h3>Code:</h3><pre>df.write.mode(&quot;overwrite&quot;).parquet(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 1–4 minutes for 10M records</h3><p>✅ <strong>Parquet is columnar = Faster analytics!</strong><br>✅ Smaller file size compared to CSV<br>❌ Not human-readable</p><p>👉 <em>Best for structured, analytical workloads!</em></p><h3>3️⃣ Partitioning: Read Faster, But Write Smartly! 🧩</h3><h3>Code:</h3><pre>df.write.mode(&quot;overwrite&quot;).partitionBy(&quot;year&quot;, &quot;month&quot;).parquet(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 1–3 minutes for 10M records</h3><p>✅ <strong>Speeds up querying in Athena &amp; Redshift</strong><br>✅ <strong>Efficient data pruning</strong> (scan only needed partitions)<br>❌ <strong>Too many partitions = Slow writes &amp; S3 listing overhead</strong></p><p>👉 <em>Great for time-based filtering (logs, events, etc.)!</em></p><h3>4️⃣ Bucketing: Supercharged Joins! ⚙️</h3><h3>Code:</h3><pre>df.write.mode(&quot;overwrite&quot;).bucketBy(10, &quot;customer_id&quot;).parquet(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 2–4 minutes for 10M records</h3><p>✅ <strong>Optimized for joins (less shuffle in Spark)</strong><br>✅ Better than partitioning for <strong>unique identifiers</strong><br>❌ <strong>Only works with Hive tables</strong></p><p>👉 <em>Best when joining large datasets with the same bucket column!</em></p><h3>5️⃣ Coalesce: Stop the “Small File Nightmare” 🔥</h3><h3>Code:</h3><pre>df.coalesce(1).write.mode(&quot;overwrite&quot;).parquet(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 3–6 minutes for 10M records</h3><p>✅ <strong>Reduces the number of small files</strong><br>❌ <strong>Single-threaded write = Slower for large datasets</strong></p><p>👉 <em>Great when you need a single output file for small to medium datasets!</em></p><h3>6️⃣ The (Not So Great) CSV Method: Please Don’t 🚫</h3><h3>Code:</h3><pre>df.write.option(&quot;header&quot;, &quot;true&quot;).csv(&quot;s3://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 5–10 minutes for 10M records</h3><p>✅ Human-readable ❌ <strong>Slower than Parquet</strong><br>❌ <strong>Larger file size = More expensive storage</strong></p><p>👉 <em>Use only if absolutely necessary (or if you hate your data engineers 😆).</em></p><h3>7️⃣ The Ultimate Trick: Modulo Partitioning + Snappy! 🏆</h3><h3>Code:</h3><pre>from pyspark.sql import functions as F</pre><pre>df = df.withColumn(&quot;zip_mod&quot;, F.col(&quot;zip_code&quot;).cast(&quot;int&quot;) % 5)</pre><pre>df.write \<br>  .option(&quot;useS3ListImplementation&quot;, &quot;true&quot;) \<br>  .option(&quot;compression&quot;, &quot;snappy&quot;) \<br>  .partitionBy(&quot;zip_mod&quot;) \<br>  .mode(&quot;overwrite&quot;) \<br>  .parquet(&quot;s3a://your-bucket/path/&quot;)</pre><h3>⏳ Time Estimate: 1–3 minutes for 10M records</h3><p>✅ <strong>Balanced partitions (avoids data skew!)</strong><br>✅ <strong>Fastest performance with S3 optimizations</strong><br>✅ <strong>Snappy compression = Speed &amp; efficiency</strong></p><p>👉 <em>Best for large-scale writes! Perfect for Athena, Redshift, and Glue-based ETL!</em></p><h3>Performance Summary 📊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*truhyWGQT5x2eXlOTXp9zQ.png" /></figure><h3>Final Thoughts 💡</h3><p>Writing data efficiently to S3 using AWS Glue can <strong>make or break</strong> your ETL pipeline. By using the right method (especially <strong>partitioning &amp; compression</strong>), you can significantly <strong>boost performance and reduce costs</strong>. 💰</p><p>So, the next time someone says, <em>“Why is my Glue job so slow?”</em> just send them this article. 😉🚀</p><p><strong>Which method do you prefer? Drop a comment and let’s discuss!</strong> 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c675eb99bd75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guidance for AWS Certifications]]></title>
            <link>https://anuja-shukla.medium.com/guidance-for-aws-certifications-f4b8941fe4aa?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4b8941fe4aa</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[guidance]]></category>
            <category><![CDATA[aws-certification]]></category>
            <category><![CDATA[awscertificationtraining]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 18:28:12 GMT</pubDate>
            <atom:updated>2023-03-08T18:28:12.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rT1XRLxGoSIei-JoD154iA.png" /></figure><p><strong>What is AWS?</strong></p><p>It is a comprehensive cloud computing platform provided by Amazon to large enterprises and businesses to scale up their businesses.</p><p><strong>What is Cloud Computing?</strong></p><p>To process, manage, and store data through remote services on any computer in the world rather than your local machine. Let us suppose an enterprise company has a huge amount of data to process but does not have a structure for the same. So, AWS can make the required infrastructure available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*F_HdMTS8RSxpXkI65hve2A.jpeg" /></figure><p><strong>What does AWS offers?</strong></p><ol><li>IaaS (Infrastructure As A Service) —</li></ol><p>If you have developed an application or website and need an infrastructure to deploy it, then IaaS is provided by AWS. This infrastructure is powerful, secure, and reliable.</p><p>2. PaaS (Platform As A Service) -</p><p>To host 3rd party applications and make them available to the customers by providing a platform.</p><p>3. SaaS (Software As A Service) -</p><p>It is a software distribution model. The third-party software is made available to the customer over the internet.</p><p><strong>Let us understand some Use Cases of AWS…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*daK0NzzAvEciwwCh_tEO-Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*Wb0_vGjDbq2GdvN2bf-vBQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*SChf6LjhQcqe6ek5gn_pSg.jpeg" /></figure><p>Right from the manufacturing company, where lots of automation is taking place, AWS has been widely used. Not only this! The entertainment industry has lots of video data that needs to be stored and backed up; AWS is used for the same.</p><p>Most of the enterprise industries are looking for new and upcoming skills, such as big data, which requires AWS.</p><p><strong>Why AWS?</strong></p><ol><li>Easy SignUp Process</li><li>No Agreement</li><li>High-capacity Servers (6 times more than competitors)</li><li>Handle more traffic</li><li>Trusted vendor(Already used by Netflix)</li><li>Flexible pricing/ Cost reduction/ Pay as per the usage</li></ol><p><strong>Services Offered by AWS:</strong></p><p><strong><em>$ Amazon Elastic Compute Cloud</em></strong><em> </em>— This provides virtual servers depending upon the load and the application.</p><p><strong><em>$ Amazon Simple Storage S3</em> </strong>— This is used to store and back up data. Also, you can perform analysis on the data.</p><p><strong><em>$ Amazon Relational Database Service</em></strong>— This is used to manage your databases.</p><p><strong><em>$ Amazon Migration Hub</em></strong> — To migrate applications, databases, and servers on its public cloud.</p><p><strong><em>$ Amazon Virtual Private Cloud</em> </strong>— An isolated private cloud provided to you with admin control.</p><p><strong><em>$ Amazon AI</em> </strong>— This provides, voice, chat, and text/chatbot technology.</p><p><strong>AWS Certifications:</strong></p><ol><li><strong>Foundational Course</strong> → <em>6 months experience → </em><strong>Cloud Practitioner</strong></li><li><strong>Associate</strong> →<em>1.5 yrs experience</em> →<strong> Solution Architect / SysOps Admin / Developer</strong></li><li><strong>Professional</strong> → 2 yrs experience → <strong>Solution Architect / DevOps Engineer</strong></li><li><strong>Specialty</strong> → 3 yrs experience → <strong>Advance Networking / Bigdata / ML field</strong></li></ol><p>I hope you enjoyed the blog!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Also, new ideas are welcomed.</p><p>Thank You! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4b8941fe4aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Travel Tastes & Flavours Of Seattle]]></title>
            <link>https://anuja-shukla.medium.com/travel-tastes-flavours-of-seattle-9f08a4817483?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f08a4817483</guid>
            <category><![CDATA[seattle]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[photography]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 14:24:29 GMT</pubDate>
            <atom:updated>2023-02-16T13:04:53.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*qaS56MOQ-5tKPtgQvFp8wQ.jpeg" /></figure><p>It takes a lot of courage to move away from the comfort zone of a cushioned corporate job and venture out on uncertain roads to fulfill one’s passion for traveling and photography.</p><p>However, wanderlust is a beautiful thing. The more you try to ignore it, the more it claws at you!!!!</p><p>Writing my frst blog on travel and photography :)</p><p>Now, let’s begin...</p><p><strong><em>Seattle is a seaport city on the West Coast of the United States. It is the seat of King County, Washington. It is the largest city in both the state of Washington and the Pacific Northwest region of North America.</em></strong></p><p>Here comes some flavors of Seattle….</p><h3><strong>Shades Of Green</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFNBsCOZgfxrPbpzTaohag.jpeg" /></figure><p>Those towering evergreens that surround the city sparked the lumber boom of the late 19th century and continue to draw lovers of the great outdoors today.</p><p>But while the pines, spruces and firs that earned the Emerald City its nickname, the diversity of Seattle’s trees — both native and non-native species — add more than verdancy to the palette of our local landscape. Think of the delicate pink of the cherry trees’ blooms, the warm ocher of peeling madrone bark, and the blazing crimson of Japanese maple leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g49DbjWbc2_OleTloHtSOQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMS0_nhMpdQuMJ8VqcrRjg.jpeg" /></figure><p>Twenty years ago, the City of Seattle, in cooperation with nonprofit Plant Amnesty, established T<strong>he Heritage Tree Program,</strong> with a mission to recognise and protect trees notable for their size, age or association with a community or historic event.</p><p>In the celebration of that program’s anniversary and Washington state’s Arbor Day on April 13 and Earth Day on April 22, sharing the names of some of the city’s most celebrated trees — <strong><em>Yoshino Cherry, Southern Magnolia, Western Red Cedar, Madrona</em></strong><em>.</em></p><h3>Angels On Earth</h3><p>The Arboretum is a welcome oasis on the shores of Lake Washington. Jointly managed by the University of Washington Botanic Gardens and the City of Seattle, its 230 acres contain a dynamic assortment of plants, some found nowhere else in the Northwest.</p><p>Take a walk through the Arboretum and discover this beautiful living collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*GRTKpxS9g9n8g8pHFFC8rA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lcIdkztGCe2op5wGlU2oNg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*q_oySLQlH0Vy2zpxgJRGqg.jpeg" /></figure><p>Skagit Valley Tulip Festival is the second-largest tulip festival in the USA and features fields of tulips, display gardens, experiences and events. Skagit Valley Tulip Festival features four farms: RoozenGaarden, Tulip Town, Tulip Valley Farms, and Garden Rosalyn. Millions of tulips burst into bloom in April during the 41st Annual Skagit Valley Tulip Festival!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*efe42BQiim7GtgGGg7pCZw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*hk3Iy0XE062B00rCVgC2yA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*oaSPEErWCX723jJ5sqUHYg.jpeg" /></figure><p>It includes the Salish Sea shorelines, bays, islands, mountains, the Skagit River, and one of the largest and most diverse agricultural communities west of the Cascade mountain range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*R4hppkzQ-Zi4YaO20JREYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*MtStUKNqfnxmvngWhWBkRA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ZrTrBf0fMKNrGqbY4dKKPQ.jpeg" /></figure><p><strong>Did you know that agriculture is theNo.1 industry in Skagit County? </strong>More tulip and daffodil bulbs are produced here than in any other county in the U.S., and local farmers produce about $261 million worth of 90 different crops, livestock, and dairy products on 93,000 acres of land. In addition to food and fiber products, agriculture in the Skagit Valley provides habitat for thousands of swans, snow geese, and dabbling ducks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*5-we8Z8DAg7OuVW0ch_-Pw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*cUvGMmyXkkB_oR71dOYJFQ.jpeg" /></figure><h3>Heritage</h3><p>The city of Seattle is a thriving hub of commercialization and the IT industry, but it is also a place where you can find some of the most beautiful, spiritual places of worship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*A1O9PYUz7KVJwNif7XGEsw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*UC6oq4PjE0sfBOkfuPGqnA.jpeg" /></figure><p>Following the foundation of VEDA in August, 2007 to let the Hindu community of Redmond celebrate their religious festivals and observe spiritual ceremonies, VEDA Sri Venkateswara Temple was established in October, 2009. Over and above regular puja and religious services, the temple also conducts community observation of auspicious occasions like Navratri, Ganesh Puja, Rudrabhishekam, to name a few. Sri Venkateswara Temple of Seattle is a center of learning Indian culture as well. Classes for language, yoga, and Hindustani music are conducted regularly on temple premises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-mwzWoN-P4bSgxTGtT7Ldw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ltyZFcI5Ghael8VFGtxNsw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*s7pGdUyOSB8GS7G7QTytbg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lc-52o9uYASL5KcvsJYN7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*O4EQBWVIlYOBQ0492Lu2AA.jpeg" /></figure><h3>University Of Washington</h3><p>The <strong>University of Washington</strong> (<strong>UW</strong>, simply <strong>Washington</strong>, or informally <strong>U-Dub</strong>) is a public research university in Seattle, Washington.</p><p>Founded in 1861, Washington is one of the oldest universities on the <a href="https://en.wikipedia.org/wiki/West_Coast_of_the_United_States">West Coast</a>; it was established in <a href="https://en.wikipedia.org/wiki/Seattle">Seattle</a> approximately a decade after the city’s founding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*sIUd3t1imj6FRk9LbKhV5Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*JIqfIWFnPTlIwQ7c2JoJYg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*VIP16zt67JXKwg_A1vSiFA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*wYOTPRzL77xOwXBv6zPVYg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*F0dr-Ay9K9iRh4Lste2hlw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*cChTWdnjlCs15UbZabQgDg.jpeg" /></figure><h3><strong>Beautiful Sunset</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VuaknFnQx-GQXqBpbUNBRw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*zk4b4eyKkaLwvuhTXk0Hlg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*x2z-u2boqQ-O9zUetxQ6WQ.jpeg" /><figcaption><strong>Pic credit goes to my friend!!! 👏👏</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f08a4817483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[your Python code to the users who expect to simply click on an executable file]]></title>
            <link>https://anuja-shukla.medium.com/your-python-code-to-the-users-who-expect-to-simply-click-on-an-executable-file-d1d4ce4347e8?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1d4ce4347e8</guid>
            <category><![CDATA[application]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[pyinstaller]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[executable]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 18:08:25 GMT</pubDate>
            <atom:updated>2022-09-07T18:14:18.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distribute your Python code to the users who expect to simply click on an executable file</h3><figure><img alt="How to Convert python script to an executable file" src="https://cdn-images-1.medium.com/max/293/1*HzObG7LhLZMEz5Y11fkYKg.jpeg" /><figcaption><strong>.py -&gt; .exe</strong></figcaption></figure><p>Few days back, I developed an automation script for my brother. This script was counting the number of pages for all the pdf available in the input folder and give the total count of all the files along with the excel sheet with page count in the individual file. When he asked me to do the required setup in his machine, and I didn&#39;t want to share the code along with the folder structure.</p><p>Am I sounding selfish here???</p><p>Lolzzz!!! Not at all…..</p><p>I am just trying to implement data abstraction here. :)</p><p>He is least interested in the code and more into the functionality, so why to make an application and simply share that.</p><p>Let us begin…</p><p>Fortunately, there are many Python utilities that help convert files from .py to .exe. They will “freeze” your code and build an executable file for you. Here we’ll consider two of the most popular options: <strong>cx_freeze</strong> and <strong>PyInstaller</strong>. Both of these tools are versatile and easy to use, but depending on your use case, you may prefer one over the other.</p><p><strong>Using PyInstaller:</strong></p><p><strong>Step 1:</strong> Install Python</p><blockquote>1: Download the Python Installer binaries. Open the official Python website (<a href="https://www.python.org/downloads/"><strong>https://www.python.org/downloads/</strong></a>)in your web browser. …</blockquote><blockquote>2: Run the Executable Installer. Once the installer is downloaded, run the Python installer. …</blockquote><blockquote>3: Add Python to environmental variables. …</blockquote><blockquote>4: Verify the Python Installation.</blockquote><p><strong>Step 2:</strong> Open up the command line. Navigate to the folder that contains the &lt; your_file.py &gt; program.</p><p><strong>Step 3:</strong> Install pyinstaller</p><blockquote>pip install pyinstaller</blockquote><p>PyInstaller supports lots of popular packages like NumPy, PyQt, and Matplotlib without any additional work from you. You can see more about the list of packages that PyInstaller officially supports by referring to the <a href="https://github.com/pyinstaller/pyinstaller/wiki/Supported-Packages"><em>PyInstaller documentation</em></a><em>.</em></p><p>Don’t worry if some of your dependencies aren’t listed in the official docs. Many Python packages work fine. In fact, PyInstaller is popular enough that many projects have explanations on how to get things working with PyInstaller. In short, the chances of your project working out of the box are high.</p><p><strong>Step 4: </strong>Run your python file with pyinstaller</p><blockquote>pyinstaller [option1] [option2] &lt; your_file.py &gt;</blockquote><p>PyInstaller is complicated under the hood and will create a lot of output. So, it’s important to know what to focus on first. Namely, the executable you can distribute to your users and potential debugging information. By default, the pyinstaller command will create a few things of interest:</p><ul><li>A <strong>*.spec file</strong> — This file can be modified and re-used to create executables later. You can make future builds a bit faster by providing this spec file instead of the entry-point script to the pyinstallercommand.</li><li>A <strong>build/ folder </strong>— This folder is where PyInstaller puts most of the metadata and internal bookkeeping for building your executable.</li><li>A <strong>dist/ folder </strong>— This folder contains the final artifact you’ll want to ship to your users. Inside this folder, there is a folder named after your file that contains all the dependencies and executable for our application. The executable to run is dist/your_file/your_file or dist/your_file/your_file.exe if you’re on Windows.</li></ul><p>You can find the full list the <a href="https://pythonhosted.org/PyInstaller/#options"><strong>options</strong></a> in the documentation.</p><p>An example could be</p><blockquote>pyinstaller.exe — onefile — windowed — icon=app.icon &lt; your_file.py &gt;</blockquote><p>— is double hyphen</p><ul><li>— onefile: Create a one-file bundled executable.</li><li>— windowed: Parameter to choose if you are compiling in Mac OS X or Windows</li><li>— icon : Choose the file to use as icon for file.</li></ul><p>Under macOS, PyInstaller always builds a UNIX executable in dist . If you specify — onedir , the output is a folder named myscript containing supporting files and an executable named myscript . If you specify — onefile , the output is a single UNIX executable named myscript .</p><p><strong>Step 5:</strong> Testing your new executable file</p><p>The best way to test your new executable is on a new machine. The new machine should have the same OS as your build machine. Ideally, this machine should be as similar as possible to what your users use. That may not always be possible, so the next best thing is testing on your own machine.</p><p>The key is to run the resulting executable <em>without</em> your development environment activated. This means run without <em>virtualenv</em>, <em>conda</em>, or any other environment that can access your Python installation. Remember, one of the main goals of a PyInstaller-created executable is for users to not need anything installed on their machine.</p><p><strong>Note:</strong></p><p><strong>The output of PyInstaller is specific to the active operating system and the active version of Python. This means that to prepare a distribution for:</strong></p><ul><li><strong>a different OS</strong></li><li><strong>a different version of Python</strong></li><li><strong>a 32-bit or 64-bit OS</strong></li></ul><p><strong>You run PyInstaller on that OS, under that version of Python. The Python interpreter that executes PyInstaller is part of the bundle, and it is specific to the OS and the word size.</strong></p><p>Converting files from .py to .exe is a task more common than you’d imagine.</p><p>I hope you enjoyed the blog!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Also, new ideas are welcomed.</p><p>Thank You! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d4ce4347e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Alexa using Python]]></title>
            <link>https://anuja-shukla.medium.com/build-your-own-alexa-using-python-febc71eda4c7?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/febc71eda4c7</guid>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[virtual-assistant]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[gtt]]></category>
            <category><![CDATA[wikipedia]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 17:44:15 GMT</pubDate>
            <atom:updated>2021-06-19T17:44:15.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever thought of having your personal assistant just like Alexa and YOU can build it on your own!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*Gx1SdbKQiMzRB7KF2Stitw.jpeg" /></figure><p>Yes, you read it right!</p><p>Build Your Own Alexa…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3O7DyTSJV3CkvPddRcPGyA.jpeg" /></figure><p>And now, let’s begin with the construction of Alexa :)</p><p>In this article, we will develop a virtual assistant program that will get a date, time and do random greetings and provides information of a person. To get person’s data, we will be using wikipedia package.</p><p>Few packages need to be installed before starting with the code. And the list is as follows:</p><blockquote>pip install pyaudio<br>pip install SpeechRecognition<br>pip install gTTS<br>pip install wikipedia</blockquote><p>Once above packages are successfully installed, then let us start with the code.</p><pre>import speech_recognition as sr<br>import speech_recognition as sr<br>import os<br>from gtts import gTTS<br>import datetime<br>import warnings<br>import calendar<br>import random<br>import wikipedia</pre><p>In case of any warnings, let us supress/ignore them for now,</p><pre># ignore any warnings messages<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p>Firstly, we need to activate our microphone to record audio. Then we will convert the audio to text (String) followed by converting into a command. Later, we will be receiving a response and then convert it into a text followed by an audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*EBMRd86DZSqo6vnAZJITWQ.jpeg" /></figure><p>In short, Alexa will be responding us by speaking to us.</p><pre>def recordAudioAsString():<br>    # Record the audio<br>    r = sr.Recognizer()<br>    # Open microphone&amp; start recording<br>    with sr.Microphone() as source:<br>        print(&#39;Say Something&#39;)<br>        audio = r.listen(source)<br><br>    # Use google speech recognition</pre><pre>    data = &#39;&#39;<br>    try:<br>        data = r.recognize_google(audio)<br>        print(&#39;You said: &#39;+data)<br>    except sr.UnknownValueError:<br>        print(&#39;We cannot understand the audio, unknown error&#39;)<br>    # In case if service is disconnected<br>    except sr.RequestError as e:<br>        print(&#39;Service Error &#39;+e)<br><br>    return data</pre><p>This function will simply ask permission to allow microphone to record audio and then convert our audio into text and display it.</p><p>As mentioned earlier, we will ask for today’s date and the function will be as follows:</p><pre>def getDate():<br><br>    now = datetime.datetime.now()<br>    current_date = datetime.datetime.today()<br>    current_day = calendar.day_name[current_date.weekday()]<br>    month = now.month<br>    day = now.day<br><br>    month_list = [&#39;January&#39;, &#39;February&#39;, &#39;March&#39;, &#39;April&#39;, &#39;May&#39;, &#39;June&#39;, &#39;July&#39;,&#39;August&#39;, &#39;September&#39;, &#39;October&#39;, &#39;November&#39;, &#39;December&#39;]<br>    ordinal = lambda n: &quot;%d%s&quot; % (n, &quot;tsnrhtdd&quot;[(n // 10 % 10 != 1) * (n % 10 &lt; 4) * n % 10::4])<br>    ordinal_list = [ordinal(n) for n in range(1,32)]<br><br>    return &#39;Today is &#39;+current_day+&#39; &#39;+month_list[month-1]+&#39; &#39;+ordinal_list[day-1]</pre><p>The second skill of our virtual assistant (Alexa) would posses is to greet:</p><pre>def greet(text):<br><br>    inputGreetWords = [&#39;hi&#39;, &#39;hello&#39;]<br>    outputGreetWords = [&#39;Hello, how can I help you?&#39;, &#39;Hey, wassup&#39;]<br><br>    for word in text.split():<br>        if word in inputGreetWords:<br>            return random.choice(outputGreetWords)<br><br>    return &#39; &#39;</pre><p>And last but not the least skill is to get details of a person from wikipedia</p><p>Suppose, you ask Alexa… who is Bhagat Singh?</p><p>Alexa will return 2 liner details for ‘Bhagat Singh’.</p><pre>def getPersonData(text):<br><br>    text_list = text.split()<br>    # print(text_list)<br>    for i in range(0,len(text_list)):<br>        if i&lt;=len(text_list) and text_list[i].lower()==&#39;who&#39; and text_list[i+1].lower()==&#39;is&#39;:<br>            # print(text_list[2]+ &#39; &#39;+text_list[3])<br>            return text_list[2]+ &#39; &#39;+text_list[3]</pre><p>Once above function returns the output as the person name, then we will be searching it over wikipedia</p><pre>person = getPersonData(text)<br>wiki = wikipedia.summary(person, sentences=2)<br>response = response+&#39; &#39;+ wiki</pre><p>The ‘sentences=2’ in above lines represents that read 1st two sentences from wikipedia. So, you can mention the limit as per your choice.</p><p>And finally, you need to call it in main().</p><h4>You can get entire code on <a href="https://github.com/ShuklaAnuja/Virtual-Assistant-Using-Python">Github</a> !!!</h4><p>In the output, it generates an mp3 file of the recording.</p><p>Also, the conversation snippet might look like….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLZ_WtmVtkyNOrHQNT67mg.png" /></figure><p>I hope you enjoyed the blog!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Also, new ideas are welcomed.</p><p>Thank You! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=febc71eda4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline Your Images into Text with Python and OCR]]></title>
            <link>https://medium.com/analytics-vidhya/streamline-your-images-into-text-with-python-and-ocr-6c32c0f79d1e?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c32c0f79d1e</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[tesseract]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Tue, 25 May 2021 20:27:29 GMT</pubDate>
            <atom:updated>2021-07-15T12:30:34.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eyYEcLj8iCQJ_tHb3Bu6dg.jpeg" /></figure><p><strong>OCR stands for Object Character Recognition !!!!</strong></p><p>OCR<strong> </strong>is the electronic or mechanical conversion of images of typed, handwritten, or printed text into machine-encoded text, whether from a scanned document, a photo of a document, a scene-photo (for example the text on signs and billboards in a landscape photo), or from subtitle text superimposed on an image (for example: from a television broadcast). OCR has become a common Python tool. With the advent of libraries such as <em>Tesseract</em> and <em>Ocrad</em>, more and more developers are building libraries and bots that use OCR in novel, interesting ways.</p><p>A trivial example is a basic OCR tool used to extract text from IMAGES so you don’t have to re-type the text later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*Am-2yNU8cBC7k3vkR94H3w.png" /></figure><p>Let’s begin with the steps…</p><p><strong>Step 1</strong>: Install tesseract using <a href="https://tesseract-ocr.github.io/tessdoc/Installation.html"><em>tessdoc</em></a><em> </em>as per the OS availability.</p><p><strong>Step 2</strong>: Check and confirm the installation path for <strong><em>tesseract</em></strong><em> </em>package.</p><p>For windows, the default installation path will be: C:\Users\USER\AppData\Local\Tesseract-OCR.</p><p>For mac OS, the installation path will be: /usr/local/Cellartesseract/4.1.1.</p><p><strong>Step 3</strong>: Install <em>pytesseract</em> using <em>pip</em></p><p>pip install pytesseract</p><p><strong>Step 4</strong>: Set the tesseract path in the script (only for Windows)</p><p>Set the tesseract path in the script before calling image_to_string:</p><p>pytesseract.pytesseract.tesseract_cmd = r&#39;C:\Users\USER\AppData\Local\Tesseract-OCR\tesseract.exe&#39;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*uNXmnBdjK2rgPepadmZL0g.jpeg" /></figure><p>You are ready with the basic setup of the requirements, and now you can start with coding……</p><p>I have used Anaconda Navigator Jupyter notebook and mac OS for the below code. It might vary as per the OS specs.</p><p>Import required packages…</p><blockquote>import cv2 as cv<br>import pytesseract as tes</blockquote><p>Using openCV (here cv2 package), read the image that you wish to convert into text…</p><blockquote>img = cv.imread(“demo.jpeg”)</blockquote><p>If the image is in the same folder as the code script, then simply provide the name, else mention the entire path.</p><p>Get the size of the image and you can cut that image into the exact text to be converted. This is completely optional.</p><blockquote>height,width,_ = img.shape<br>roi = img[50:500, 200:600]</blockquote><p>Make use of <em>image_to_string</em>() function from <em>tesseract</em> package to print the image characters into string.</p><blockquote>print(tes.image_to_string(roi))</blockquote><p>Finally, we just display the resulting frame and also set a way to exit this infinite loop and close the video feed.</p><blockquote>cv.imshow(“roi”,roi)<br>cv.waitKey(0)<br>cv.destroyAllWindows()</blockquote><h4>Code output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*hDiqDNl73VrPwN7j2ZoH9Q.png" /></figure><p>I hope you enjoyed the blog!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c32c0f79d1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/streamline-your-images-into-text-with-python-and-ocr-6c32c0f79d1e">Streamline Your Images into Text with Python and OCR</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train ML Model and Build Android Application Using TensorFlow Lite & Keras]]></title>
            <link>https://medium.com/geekculture/train-ml-model-and-build-android-application-using-tensorflow-lite-keras-6bf23d07309a?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf23d07309a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ml-kit]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 05:59:22 GMT</pubDate>
            <atom:updated>2021-04-13T23:31:14.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*ghMaqZgVvIRzUmFRY91ZLA.jpeg" /><figcaption>ML + Android</figcaption></figure><p>In this blog, I will train a very basic Machine Learning model using TensorFlow and Keras then we will develop an android application for that trained model.</p><p>We will use Anaconda to train our machine learning model then we will convert this model into a <strong>tflite</strong> format. After that, we will develop an Android Application using Android studio in java. So at the end of this, you will have your very own machine learning-based Android Application.</p><p><em>Tensorflow lite use in Android is not clear for most of them but in this example, we will explain with a very simple example.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*VZiqUttzjBnIkONJyUaLqQ.jpeg" /></figure><p>Let us begin….</p><p><strong>Step 1</strong>: Import required libraries</p><blockquote><em>import tensorflow as tf<br>import numpy as np<br>from tensorflow import keras,lite</em></blockquote><p>Tensorflow will be used to train our model and numpy will be used to create a dataset. Keras will be used to generate a neural network model. Using lite, we will convert the model into tflite format for Android.</p><p><strong>Step 2:</strong> Create a dataset.</p><p>The basic dataset will have 2 variables x and y. The relationship pattern with the vars will be <strong>y=2x-1. </strong>Here y is the label and x is the feature.</p><blockquote>x = np.array([-1.0,0.0,1.0,2.0,3.0,4.0],dtype=float)<br>y = np.array([-3.0,-1.0,1.0,3.0,5.0,7.0],dtype=float)</blockquote><p><strong>Step 3:</strong> Train a model using Keras</p><p>This package has a similar behavior as of neural network package. The hidden layers are created using the Keras. layers.Dense(). This dense() will provide connectivity of current and previous neurons.</p><blockquote>model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1]),keras.layers.Dense(units=1,input_shape=[1])])<br>model.compile(optimizer=’sgd’,loss=’mean_squared_error’)</blockquote><p>units=1 will tell you that it will have 1 neuron and input_shape for the previous layer is 1 because we are using only 1 feature (i.e. <strong>x</strong>). then, we compile the model. The parameters optimizer and loss values. the loss defines the difference between predicted and actual value. As this is Supervised ML, we have labeled data and we are going to get predicted results which we will be compared with the actual values.</p><p><strong>Step 4:</strong> Performing training on the model</p><blockquote>model.fit(x,y,epochs=500)<br>print(model.predict([10]))</blockquote><p>The x and y values indicate the input and output values to train the model with 500 epochs which means we want to train this dataset 500 times.</p><p>Then, predict the value of x=10.</p><p>Ideally, the value of y should be 19. The predicted value after executing the code is 18.9999. Hence, the model is quite accurate.</p><p><strong>Step 5:</strong> Save the model and create h5 and tflite file format</p><blockquote>keras_file = “linear.h5”<br>tf.keras.models.save_model(model,keras_file)<br>converter = lite.TFLiteConverter.from_keras_model(model)<br>tfmodel = converter.convert()</blockquote><blockquote>open(“linear.tflite”,”wb”).write(tfmodel)</blockquote><p><strong>Step 6</strong>: Create Android Application</p><p>Goto Android Studio -&gt; Create New Project.</p><p>Initially, you need to add below dependencies in the code:</p><ol><li>Add following package inside dependencies of build.gradle file -</li></ol><blockquote>implementation &#39;org.tensorflow:tensorflow-lite:+&#39;</blockquote><p>Then, we need to add the below code just above dependencies</p><blockquote>aaptOptions<strong>{<br> </strong>noCompress &quot;tflite&quot;<br> noCompress &quot;lite&quot;<br><strong>}</strong></blockquote><p>This specifies that tflite files should not be compressed like other files.</p><p>Sync the project and gradle should compile successfully.</p><p>2. Add the tflite file inside the assets folder of the Android project.</p><p>3. Add the below function in the Java file</p><blockquote>private MappedByteBuffer loadModelFile() throws IOException<br>{<br> AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd(&quot;linear.tflite&quot;);<br> FileInputStream fileInputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());<br> FileChannel fileChannel = fileInputStream.getChannel();<br><br> long startOffset = assetFileDescriptor.getStartOffset();<br> long len = assetFileDescriptor.getLength();<br><br> return fileChannel.map(FileChannel.MapMode.<em>READ_ONLY</em>,startOffset,len);<br>}</blockquote><p>This will convert the tflite model file into MappedByteBuffer format. It is an optimized format that will help us to increase efficiency and speed.</p><p>4. Add an Interpreter which will interpret the input and output of data using the model.</p><blockquote>interpreter = new Interpreter(loadModelFile(),null);</blockquote><p>5. Add below doInference() function to evaluate the expression and get the output with the help of the model.</p><blockquote>public float doInference(String val)<br>{<br> float[] input = new float[1];<br> input[0] = Float.<em>parseFloat</em>(val);<br> float[][] output = new float[1][1];<br><br> interpreter.run(input,output);<br> return output[0][0];<br>}</blockquote><p>The parameter val is the input value given by the user.</p><p>As the model is developed on float values, we are converting the input string value to float value. Then, we have created a 2D output array (as it has only one row and one column). Later, the interpreter will produce output based on the input value and save it in the output variable of the 0th row and 0th column.</p><p>And the output is…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeJ2ArF86mMF9QigqJDD5w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErN5UCz3rdWBx1aiSP2VKQ.jpeg" /></figure><p>You can find the entire code snippet on <a href="https://github.com/ShuklaAnuja/Python-ML---Android-Kit"><strong><em>Github</em></strong></a><strong><em>.</em></strong></p><p>I hope you enjoyed the blog!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Also, new ideas are welcomed.</p><p>Thank You! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf23d07309a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/train-ml-model-and-build-android-application-using-tensorflow-lite-keras-6bf23d07309a">Train ML Model and Build Android Application Using TensorFlow Lite &amp; Keras</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Mask Detection using OpenCV]]></title>
            <link>https://anuja-shukla.medium.com/face-mask-detection-using-opencv-d9a2d75e4064?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a2d75e4064</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 20:42:10 GMT</pubDate>
            <atom:updated>2020-10-11T15:16:37.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Readers really enjoy learning from the timely, practical application, so today we are going to look at COVID-related application of computer vision, <strong>this one on detecting face masks with OpenCV and TensorFlow.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*K-hFxWdPIOeEbr1OrzjPiA.png" /></figure><p>Let us begin…..</p><p><strong>Prerequisites</strong>:</p><p>A. OpenCV package (import cv2 as cv)</p><p>B. Tensorflow/Keras (import tensorflow)</p><p>C. IDE (I used Anaconda Navigator — Jupyter Notebook) : To download opencv and tensorflow on Anaconda, you can simply install these 2 packages in case if it is not available.</p><p>Commands:</p><blockquote>conda <strong>install</strong> -c conda-forge <strong>opencv</strong></blockquote><blockquote>pip install tensorflow</blockquote><p>Here is the list of subtopics we are going to cover:</p><ol><li>How to do Real-time face detection</li><li>How to do Real-time Mask detection</li></ol><p><strong>How to do Real-time face detection</strong></p><p>In this section, we are going to use OpenCV to do real-time face detection from a live stream via our webcam.</p><p>As you know videos are basically made up of frames, which are still images. We perform the face detection for each frame in a video. So when it comes to detecting a face in still image and detecting a face in a real-time video stream, there is not much difference between them.</p><p>We will be using <strong>Haar Cascade algorithm </strong>to detect faces. It is basically a machine learning object detection algorithm which is used to identify objects in an image or video. In OpenCV, we have several trained Haar Cascade models which are saved as XML files. Instead of creating and training the model from scratch, we use this file. We are going to use “<strong>haarcascade_frontalface_alt2.xml</strong>” file in this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*6zLZHTecBub6-RCQh-jPhQ.png" /><figcaption>Haar Cascade Model</figcaption></figure><p>The first step is to find the path to the “haarcascade_frontalface_alt2.xml” file. We do this by using the os module of Python language.</p><pre>import os<br>cascadePath = os.path.dirname(<br>    cv.__file__) + &quot;/data/haarcascade_frontalface_alt2.xml&quot;</pre><p>The next step is to load our classifier. The path to the above XML file goes as an argument to CascadeClassifier() method of OpenCV.</p><pre>faceCascade = cv.CascadeClassifier(cascadePath)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6RfqQC3yiuzHVGp5DLupg.jpeg" /><figcaption>Haar Cascade classifier</figcaption></figure><p>After loading the classifier, let us open the webcam using this simple OpenCV one-liner code</p><pre>video_capture = cv.VideoCapture(0)</pre><p>Next, we need to get the frames from the webcam stream, we do this using the read() function. We use it in infinite loop to get all the frames until the time we want to close the stream.</p><pre>while True: #(or 1)<br>    # Capture frame-by-frame<br>    ret, frame = video_capture.read()</pre><p>For this specific classifier to work, we need to convert the frame into grayscale.</p><pre>gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)</pre><p>The faceCascade object has a method detectMultiScale(), which receives a frame(image) as an argument and runs the classifier cascade over the image. The term MultiScale indicates that the algorithm looks at subregions of the image in multiple scales, to detect faces of varying sizes.</p><pre>faces = faceCascade.detectMultiScale(gray,<br>                                         scaleFactor=1.1,<br>                                         minNeighbors=5,<br>                                         minSize=(80, 80),<br>                                         flags=cv.CASCADE_SCALE_IMAGE)</pre><ul><li>scaleFactor — the image size that can be reduced at each image scale. By rescaling the input image, you can resize a larger face to a smaller one, making it detectable by the algorithm. 1.05 is a good possible value for this, which means you use a small step for resizing, i.e. reduce the size by 5%, you increase the chance of a matching size with the model for detection is found.</li><li>minNeighbors — specifying how many neighbours each candidate rectangle should have to retain it. This parameter will affect the quality of the detected faces. Higher value results in fewer detections but with higher quality. 3~6 is a good value for it.</li><li>flags –Mode of operation</li><li>minSize — Minimum possible object size. Objects smaller than that are ignored.</li></ul><p>The coordinates indicate the row and column of pixels in the image. We can easily get these coordinates from the variable face</p><pre>for (x,y,w,h) in faces:<br>        face_frame = frame[y:y+h,x:x+w]<br>        face_frame = cv.cvtColor(face_frame, cv.COLOR_BGR2RGB)<br>   <br>cv.rectangle(frame, (x, y), (x + w, y + h),(0,255,0), 2)</pre><p>rectangle() accepts the following arguments:</p><ul><li>The original image</li><li>The coordinates of the top-left point of the detection</li><li>The coordinates of the bottom-right point of the detection</li><li>The colour of the rectangle (a tuple that defines the amount of red, green, and blue (0–255)).In our case, we set as green just keeping the green component as 255 and rest as zero.</li><li>The thickness of the rectangle lines</li></ul><p>Next, we just display the resulting frame and also set a way to exit this infinite loop and close the video feed. By pressing the ‘q’ key, we can exit the script here</p><pre>cv2.imshow(&#39;Video&#39;, frame)<br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>        break</pre><p>Code output:</p><p>A&gt; With Mask</p><figure><img alt="With Mask" src="https://cdn-images-1.medium.com/max/1024/1*xehrNgu9zApsLx5B1MzBsA.png" /></figure><p>B&gt; Without Mask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtFPJB6FV6hFo4LkIqVC9g.png" /></figure><p>The next two lines are just to clean up and release the picture.</p><pre>video_capture.release()<br>cv2.destroyAllWindows()</pre><p>I hope you enjoyed the tutorial!!!</p><p>Please feel free to post your comments and feedback….</p><p><strong><em>Don’t forget to hit claps if you liked it :)</em></strong></p><p>Also, new ideas are welcomed.</p><p>Thank You! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a2d75e4064" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Games in Python….]]></title>
            <link>https://anuja-shukla.medium.com/making-games-in-python-6b831da97f7?source=rss-152b45c46c7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b831da97f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Anuja Shukla]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 18:01:02 GMT</pubDate>
            <atom:updated>2020-09-15T18:01:02.656Z</atom:updated>
            <content:encoded><![CDATA[<p>This one is for those of you who like to have fun!</p><p>Python can be used to code a variety of arcade games, adventure games, and puzzle games that you can deploy within a few days. Classics like hangman, tic-tac-toe, ping-pong, and more are all doable with your newly acquired programming skills.</p><p>The <a href="https://www.pygame.org/docs/">Pygame</a> library makes it even easier to build your own games. It contains almost anything you could need when starting to develop a game.</p><p>Pygame is free and open source. It includes computer graphics and sound libraries that you can use to add interactive functionality to your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*UGH5rdss9RXKn3ho88jNqg.jpeg" /><figcaption>PyGame library for Python</figcaption></figure><p>You will find many documentations/ tutorials for how to use this library and make a game!</p><p>This blog will help you to know facts related to gaming in Python…..</p><p><strong>Q. What is pygame written in?</strong></p><p>Assembly language….<strong>Cython!</strong></p><p><strong>Q. Is pygame a good way to learn Python?</strong></p><p>I think PyGame is one of the best ways to learn Python. … because you can visually see your logic at work, which is pretty much not possible in many other places. It’s not a great way to learn game development, since it uses paradigms that are not present in the game world today.</p><p><strong>Q. Is Python fast enough for games?</strong></p><p>Python is an excellent choice for rapid prototyping of games. But it has limits with performance. Therefore for more resource-intensive games, you should consider the industry standard which is C# with Unity or C++ with Unreal. Some popular games like <strong>EVE Online</strong> and <strong>Pirates of the Caribbean</strong> were created using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*F7CmzE4RF72DSUF2T-MSmQ.jpeg" /><figcaption>Pirates of Caribbean game created using Python</figcaption></figure><p><strong>Q. Is Python good for graphics?</strong></p><p>Python is a great language, but Computer Graphics are heavy and need performance. Because of this, commonly people use C or C++ in games. … But you CAN make basic Computer Graphics with Python, if it’s for learning purposes. There is a Python binding to OpenGL.</p><p><strong>Q. Can Python make 3d games?</strong></p><p>If you’re interested in learning how to use Pygame to create 3D games, two sites that are dedicated to 3D Python are Python 3D(<em>py3d.org</em>) and Python 3D Software. You can find several 3D game projects available here. PyWeek is a bi-annual programming challenge site that produces several great games.</p><p><strong>Q. Is pygame worth learning?</strong></p><p>No definitely not! Before starting pygame you definitely need to have basic python knowledge, such as loops, lists, etc. But pygame is a great module which can be used to easily create a fantastic game for free. … As a beginner you can learn pygame just knowing the python basics.</p><blockquote>Python Humor</blockquote><p><em>Beautiful is better than ugly.</em></p><p><em>Explicit is better than implicit.</em></p><p><em>Simple is better than complex.</em></p><p><em>Complex is better than complicated.</em></p><p><em>Flat is better than nested.</em></p><p><em>Sparse is better than dense.</em></p><p><em>Readability counts.</em></p><p><em>Special cases aren’t special enough to break the rules.</em></p><p><em>Although practicality beats purity.</em></p><p><em>Errors should never pass silently.</em></p><p><em>Unless explicitly silenced.</em></p><p><em>In the face of ambiguity, refuse the temptation to guess.</em></p><p><em>There should be one — and preferably only one — obvious way to do it.</em></p><p><em>Although that way may not be obvious at first unless you’re Dutch.</em></p><p><em>Now is better than never.</em></p><p><em>Although never is often better than </em>right<em> now.</em></p><p><em>If the implementation is hard to explain, it’s a bad idea.</em></p><p><em>If the implementation is easy to explain, it may be a good idea.</em></p><p><em>Namespaces are one honking great idea — let’s do more of those!</em></p><p><em>— Tim Peters</em></p><p>Please share your thoughts and feedback for this blog….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b831da97f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>