<?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 Jasmine Plows on Medium]]></title>
        <description><![CDATA[Stories by Jasmine Plows on Medium]]></description>
        <link>https://medium.com/@jasmineplows?source=rss-1e0650579559------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rJDMMA5n2aUp1dtvNuogKA.jpeg</url>
            <title>Stories by Jasmine Plows on Medium</title>
            <link>https://medium.com/@jasmineplows?source=rss-1e0650579559------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:31:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasmineplows/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[Can we predict the Top 10 movies of the US box office in 2026?]]></title>
            <link>https://medium.com/@jasmineplows/can-we-predict-the-top-10-movies-of-the-us-box-office-in-2026-8f015569d42e?source=rss-1e0650579559------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f015569d42e</guid>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Jasmine Plows]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 18:07:25 GMT</pubDate>
            <atom:updated>2026-02-05T18:07:25.034Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a cross-post from me and <a href="https://www.linkedin.com/in/justinkiehl/">Justin Kiehl</a>’s blog/newsletter <a href="https://medium.com/@unpromptedblog">Unprompted — A Data Science Blog</a>. Check it out and subscribe!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZcOkuNNfNDNV53oV.png" /></figure><p>One thing about me (Jasmine) — I am a <em>huge</em> movie buff. My favorite thing to do is to go to the movies. As <a href="https://www.amctheatres.com/amcstubs/alist">AMC A-Lister</a>s, my wife and I spend our weekends seeing all the latest releases in one of the many historic theaters around Los Angeles. On the drive home from each one, we listen to NPR’s <a href="https://www.npr.org/podcasts/510282/pop-culture-happy-hour">Pop Culture Happy Hour</a> and The Ringer’s <a href="https://www.theringer.com/podcasts/the-big-picture">The Big Picture</a> podcast recaps, and we diligently log every movie we watch on the movie logging app, <a href="https://letterboxd.com/">Letterboxd</a>.</p><p>I am also a data scientist, which means I am prone to thinking about everything in terms of data. For the last few years, I have been passively following US box office trends, and have been wondering how easy it would be to accurately predict box office numbers. Box office prediction has become its own art form, with the rise in popularity of things like <a href="https://www.fantasyboxofficegame.com/">Box Office Movie Drafts</a> and <a href="https://www.theverge.com/film/659517/moviepass-mogul-nfts-mysten-sui-blockchain">Box Office gambling odds</a>.</p><p>To explore this question more, fellow data scientist Justin Kiehl and I sought to answer the question: How accurately can we predict the top 10 movies of 2026?</p><p>Since the pandemic, there have been clear trends in the US box office. Children’s movies — especially when they’re sequels — do particularly well. Superhero films (particularly Marvel movies) always do well. As do general Intellectual Property (“IP”) movies, where there is already a built-in audience (e.g. <em>Barbie</em>, <em>Super Mario Bros.</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MUc1HrcyVF4MDTM5.png" /><figcaption>The Top 10 films of the last 10 years at the US box office.</figcaption></figure><p>We decided to focus only on the US box office, as the worldwide box office is notoriously more variable (a good example is the Chinese animated film <em>Ne Zha 2</em>, which <a href="https://variety.com/2026/film/box-office/ne-zha-2-zootopia-2-2025-china-box-office-7-4-billion-1236621734/">grossed over two billion dollars worldwide in 2025</a>, but barely had a release in the US). Given that, we combined two datasets with data from 2010 onwards: a web-scrape of <a href="https://www.boxofficemojo.com/">BoxOfficeMojo</a> (BOM) and <a href="https://www.themoviedb.org/?language=en-US">The Movie Database</a> (TMDB) API. We merged the two datasets and ended up with a clean dataset of movie metadata (from TMDB) and box office results (from BOM).</p><h3>Feature Engineering</h3><p>Next came feature engineering. We had a bunch of features we could think of to start with. For example, a film’s genre; studio; whether the film is a sequel or IP; season of release; month of release; proximity to major holidays; etc. We also felt that a director’s prior films’ revenue and each of the top-five billed actors’ prior film revenues could be important, so added these as well.</p><p>Here are the features we ultimately landed on:</p><h3>Studio Features</h3><ul><li><strong>is_disney</strong> — Disney / Walt Disney Studios movies</li><li><strong>is_warner_bros</strong> — Warner Bros. movies</li><li><strong>is_universal</strong> — Universal Pictures movies</li><li><strong>is_sony</strong> — Sony / Columbia / Screen Gems / TriStar movies</li><li><strong>is_paramount</strong> — Paramount Pictures movies</li><li><strong>is_fox</strong> — 20th Century Fox movies</li><li><strong>is_mgm</strong> — MGM / United Artists movies</li><li><strong>is_lionsgate</strong> — Lionsgate movies</li><li><strong>is_major_studio</strong> — Any of the 8 major studios above</li></ul><h3>Genre Features</h3><ul><li><strong>Genre (one-hot encoded into 17 distinct genres): </strong>genre_action, genre_adventure, genre_animation, genre_comedy, genre_crime, genre_drama, genre_family, genre_fantasy, genre_history, genre_horror, genre_music, genre_mystery, genre_romance, genre_science_fiction, genre_thriller, genre_war, genre_western</li><li><strong>genre_count</strong> — Number of genres per movie</li><li><strong>is_action_adventure</strong> — Action + Adventure combination</li><li><strong>is_action_sci_fi</strong> — Action + Sci-Fi combination</li><li><strong>is_comedy_romance</strong> — Comedy + Romance combination</li><li><strong>is_family_animation</strong> — Family + Animation combination</li></ul><h3>IP &amp; Franchise Features</h3><ul><li><strong>is_marvel</strong> — Marvel MCU films</li><li><strong>is_dc</strong> — DC Extended Universe films</li><li><strong>is_star_wars</strong> — Star Wars franchise films</li><li><strong>is_fast_furious</strong> — Fast &amp; Furious franchise films</li><li><strong>is_harry_potter</strong> — Harry Potter / Wizarding World films</li><li><strong>is_pixar</strong> — Pixar films</li><li><strong>is_disney_animation</strong> — Disney animated films</li><li><strong>is_sequel</strong> — Film is a sequel (validated manually and via an LLM)</li><li><strong>has_remake_indicator</strong> — Title contains remake indicators</li><li><strong>is_franchise_sequel</strong> — Sequels to established franchises</li><li><strong>is_live_action_remake</strong> — Disney / DreamWorks live-action remakes</li><li><strong>is_adaptation</strong> — Adaptations from other media (games, TV, toys)</li><li><strong>is_superhero</strong> — All superhero movies</li><li><strong>is_remake_adaptation</strong> — Combined remake/adaptation flag</li><li><strong>is_ip_movie</strong> — Any intellectual property movie</li></ul><h3>Release Timing Features</h3><ul><li><strong>release_month</strong> — Month of release (1–12)</li><li><strong>is_summer_blockbuster</strong> — Released May–August</li><li><strong>is_holiday_release</strong> — Released November–December</li><li><strong>is_oscar_season</strong> — Released October–December</li><li><strong>is_holiday_proximity</strong> — Within 10 days of major holidays</li><li><strong>is_christmas_proximity</strong> — Near Christmas / New Year’s</li><li><strong>is_thanksgiving_proximity</strong> — Near Thanksgiving</li><li><strong>is_independence_day_proximity</strong> — Near July 4th</li><li><strong>is_memorial_labor_day_proximity</strong> — Near Memorial / Labor Day</li><li><strong>days_to_holiday</strong> — Days to nearest major holiday</li></ul><h3>Competition Features</h3><ul><li><strong>has_nearby_major_release</strong> — Other $50M+ movies within ±14 days</li><li><strong>nearby_major_releases_count</strong> — Count of nearby major releases</li><li><strong>has_blockbuster_competition</strong> — Nearby $200M+ movies</li><li><strong>has_immediate_competition</strong> — Major releases within 7 days</li></ul><h3>Origin &amp; Language Features</h3><ul><li><strong>is_english</strong> — English language movies</li><li><strong>is_origin_usa</strong> — US production origin</li><li><strong>is_origin_uk_ie</strong> — UK / Ireland production origin</li><li><strong>is_origin_canada</strong> — Canadian production origin</li><li><strong>is_origin_us_uk_ca</strong> — US / UK / Canada production origin</li></ul><h3>Time &amp; Era Features</h3><ul><li><strong>years_since_baseline</strong> — Years since 2010 (linear time progression)</li><li><strong>is_pre_streaming_era</strong> — Released ≤2018 (traditional theatrical era)</li><li><strong>is_streaming_transition</strong> — Released 2019 or 2021 (market transition)</li><li><strong>is_pandemic_year</strong> — Released 2020–2021 (pandemic disruption)</li><li><strong>is_post_pandemic_era</strong> — Released ≥2022 (recovery / hybrid era)</li></ul><h3>Director and Cast Success Features</h3><ul><li><strong>director_avg_domestic_prior_films </strong>— the director’s average domestic revenue on their previous films</li><li><strong>director_max_domestic_prior_films </strong>— the director’s maximum domestic revenue across their previous films</li><li><strong>avg_prior_revenue_cast_member_1 (and 2, 3, 4, 5) </strong>— cast member’s average domestic revenue on their previous films</li><li><strong>max_prior_revenue_cast_member_1 (and 2, 3, 4, 5)</strong> — cast member’s maximum domestic revenue across their previous films</li></ul><h3>Data Exploration and Visualization</h3><p>After engineering the features, we did some exploratory analysis/data visualization. Here are some of our observations:</p><h3>Studio/Distributors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*japw9fdhW-BWyiTv.png" /><figcaption>Revenue per studio</figcaption></figure><p>These plots show how much Disney has over-performed as a studio over the last 10 years. Of the top eight major studios, it released the second-fewest films, but had the highest average return by far. This makes sense — we know Disney owns Star Wars, Marvel, Pixar, and all its animated classics (including its hugely popular live-action remakes such as <em>The Lion King</em> and <em>Lilo &amp; Stitch</em>) — but it’s still surprising to see just <em>how much</em> being a Disney film impacts revenue.</p><h3>Genre</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ndwWl2-kA5uQiKqH.png" /><figcaption>Revenue per genre</figcaption></figure><p>In terms of genre, “Adventure” had the highest average revenue and outperformed other genres, which is somewhat surprising until you dig into some examples (basically all Star Wars and Marvel films were classified as Adventure). Less surprising was Family and Animation, which reflects the Disney outperformance we saw above. In fact, all of the outperforming genres appear to have been driven by Disney (either superhero, Star Wars, or animated films)</p><h3>Release Month and Season</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZ7eP3WwUKaCnZDx.png" /><figcaption>Revenue per release month and season</figcaption></figure><p>For release month, results were mostly as expected, with July pulling in the highest average revenue of the months, and summer being the best season, followed by winter. We were surprised to see that August was the lowest-performing month (widely believed to be January, which came in second-worst). August was still a big movie month, but it seems this was primarily driven by films that were released earlier in July.</p><h3>Holidays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*opNJsjzfEeCw00Al.png" /><figcaption>Revenue per US holiday</figcaption></figure><p>Holidays were also big drivers of box office revenue. Unsurprisingly, Christmas had the highest revenue, followed by July 4th and Memorial Day, which are big movie release dates in the summer. We were surprised to see that the holiday with the most movies with nearby releases was Veteran’s Day, however, which falls in November. This may be related to movies releasing in time for awards’ season.</p><h3>Competition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QStebN6up8MdjmaQ.png" /><figcaption>Revenue as a function of box office competition</figcaption></figure><p>Another feature we thought might be important was nearby releases. It is commonly believed to be detrimental to release two big movies on the same weekend, as they pull audiences away from one another. However, in recent years, this has been seen more as an advantage (for example the famous <a href="https://en.wikipedia.org/wiki/Barbenheimer">Barbenheimer</a> weekend in July 2023). It also reflects the time of year — more major releases happen in certain months and holidays, which we already established is associated with revenue.</p><h3>Intellectual Property (IP) and Sequel Movies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g-tJwMG_1wtaPKnV.png" /><figcaption>IP and sequel movie performance vs original movie performance</figcaption></figure><p>As expected, average revenue for IP movies was higher than for non-IP movies. In fact, IP movies had a 490% advantage over non-IP movies. A sequel film’s revenue was also unsurprisingly strongly correlated with the previous films in the series’ revenue. This reflects a somewhat-depressing trend — the surest way to make money as a studio is to tap into existing content, which disincentivizes producing original films. Having said that, there will always be some exceptions, which are typically hard to predict. For example, we don’t think any machine learning model (or human) would have ever predicted Warner Bros.’ <em>Sinners</em> as being a top-10 film of 2025. It is an original horror movie that had terrific word-of-mouth and an extended IMAX run, and ended up being a delightful critical and box office success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpb7Jd66kxH0gVKb.png" /><figcaption>There was a strong correlation between performance of sequel movies vs their previous iterations</figcaption></figure><h3>Era (Streaming and Pandemic effects)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o05Y9vZWH8FX5zY6.png" /><figcaption>Associations between film release era and domestic revenue</figcaption></figure><p>Both the rise of streaming and the pandemic had significant effects on the US population’s tendency to go to the movies, as visualized above. The pre-streaming era had the most films released, and the highest mean and median domestic revenue. The effect of the pandemic can be clearly seen with the crash of the blue line in the bottom-right plot in 2020 and the slow recovery (films released in the post-pandemic era have yet to fully recover, although they are close, especially with the effect of inflation in recent years).</p><h3>Director success</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*qVd8Hf7GzCY9Fu0u.png" /><figcaption>A film’s revenue is correlated with the director’s average revenue across previous films</figcaption></figure><p>James Cameron recently made headlines for something truly remarkable — with the success of <em>Avatar: Fire and Ash</em>, he is likely to have soon directed <a href="https://www.hollywoodreporter.com/movies/movie-news/box-office-avatar-3-billion-the-housemaid-win-1236463156/">four of the top 10 highest grossest films of all time</a>. This speaks to something important for prediction purposes — a director’s revenue on previous films is likely to be correlated with future revenue. Indeed, this is what our data showed, above.</p><h3>Cast success</h3><p>Intuitively, we know that the popularity of a film’s cast also likely predicts its success. Think 2025’s <em>F1</em> and <em>Marty Supreme</em> — both films that likely wouldn’t have done as well as they did without the star power of Brad Pitt and Timothée Chalamet, respectively. Indeed, we found a correlation between a film’s box office success and the box office performance of the cast’s previous films, although it wasn’t particularly strong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vqBZV4hZrw9NXR8Z.png" /><figcaption>There was a correlation between a film’s revenue and the top-billed actors’ prior average film revenue</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*FSRk3124Y3VFBRfo.png" /><figcaption>TMDb cast popularity score correlates with domestic revenue</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*mSuaIH7U-hN9QMLZ.png" /></figure><h3>Modeling</h3><p>To prevent data leakage, we used temporal validation — training on years 2015–2023, validating on 2024 data, and testing on 2025 data (note — some December 2025 releases will still be making money into 2026, so these numbers are subject to change).</p><p>We tested five approaches of varying complexity — Ridge Linear Regression, Decision Tree, Random Forest, XgBoost, and LightGBM.</p><p>We knew from our data exploration work that the pandemic would potentially affect the model, so tried a few different approaches for handling it (ignoring the pandemic, removing the pandemic years, or de-weighting the pandemic years by weighting 2020 and 2021 at 30% importance).</p><h3>2024 Results</h3><p>After trying all the models, the best model was the XgBoost model, without removal of the pandemic years from the training dataset. This model had a root mean squared error (RMSE) of $85,048,262, mean absolute error (MAE) of $35,713,062, and R² of 37%. But most importantly, it correctly predicted 7 out of 10 of the top 10 films of 2024:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fSjoHiNCTMtf9ZUq.png" /><figcaption>Our model’s 2024 predictions were 70% correct</figcaption></figure><p>The films it got incorrect were <em>Venom: The Last Dance, Transformers One</em>, and <em>Joker: Folie a Deux</em>, which are not entirely surprising. These are all sequel/IP films whose predecessors did extremely well at the box office, but themselves were critically panned so did not do as well. Of course, the model has no way to predict critical reception in advance, so we can’t penalize it for this. Humans suffer from the same issue. The films it missed were <em>Beetlejuice Beetlejuice, Dune: Part Two, </em>and<em> Inside Out 2</em>, which were harder to predict (with the exception of <em>Inside Out 2</em> — which we were surprised it missed. This may have been partly due to the fact that it was director Kelsey Mann’s directorial debut).</p><h3>2025 Results</h3><p>So how did the model perform on predicting 2025 results? Actually better than its 2024 performance, with an RMSE of $52,568,922, MAE of $23,032,570, R² of 60%, and <strong>8 out of 10</strong> correct (note: 2025 box office results are still subject to change as we enter 2026):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXqnxtUSwXdJnwEp.png" /><figcaption>Our model got 8 of the top 10 2025 films correct</figcaption></figure><p>Again, these misses are not entirely surprising. Both <em>Mission Impossible: The Final Reckoning</em> and <em>Thunderbolts*</em> <a href="https://www.boxofficemojo.com/year/2025/">just missed the top 10</a> (12 and 13, respectively), while Ryan Coogler’s <em>Sinners</em> was a surprise hit. However, it is a little disappointing that the model missed Disney’s <em>Zootopia 2</em>, which should have been a slam-dunk. It seems our model underestimates some Disney animated films, despite including a number of features to capture their popularity.</p><h3>2026 Predictions</h3><p>The only thing left to do was to use the model to predict 2026 box office performance. Here are the predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*DDNYBX04d2OiV3pt.png" /><figcaption>Our model’s predictions for 2026</figcaption></figure><p>Overall, these are pretty good predictions — our guess is that at least 8 out of 10 of these end up being correct. The two questions marks here are <em>The Devil Wears Prada 2</em> and <em>The Cat in the Hat (</em>and maybe<em> Scream 7)</em>, but all of these are within the realm of possibility.</p><h3>LLM Predictions</h3><p>We also asked both <em>ChatGPT 5.2</em> and <em>Claude Sonnet 4.5</em> to make their predictions, out of curiosity. Nowadays as the field of data science moves more towards LLMs, it will be interesting if our 60+ hours of work training a model will perform as well as a two-second LLM query. Only time will tell:</p><h3>GPT-5.2’s predictions as of 12/23/2025:</h3><ol><li>Avengers: Doomsday</li><li>The Super Mario Galaxy Movie</li><li>Spider-Man: Brand New Day</li><li>Moana (Live-Action)</li><li>Toy Story 5</li><li>Minions 3</li><li>The Odyssey</li><li>Michael</li><li>Masters of the Universe</li><li>Greenland 2: Migration</li></ol><h3>Claude Sonnet 4.5’s predictions as of 12/23/2025:</h3><ol><li>Avengers: Doomsday</li><li>Spider-Man: Brand New Day</li><li>The Super Mario Galaxy Movie</li><li>Toy Story 5</li><li>The Mandalorian &amp; Grogu</li><li>The Odyssey</li><li>Moana (Live-Action)</li><li>Minions 3</li><li>The Hunger Games: Sunrise on the Reaping</li><li>Dune: Part Three</li></ol><p>Our model’s predictions and Claude’s predictions are pretty similar, although Claude favored Christopher Nolan’s <em>The Odyssey </em>and <em>Dune: Part Three</em>. We agree with Claude on the <em>Dune</em> sequel, although <em>The Odyssey</em> will have a runtime of over three hours, so may be a tough-sell for some and not quite make the top 10. We were a little perplexed by ChatGPT’s inclusion of <em>Greenland 2</em> and <em>Masters of the Universe</em>, but hey, you never know.</p><p>Code can be found here (<a href="https://github.com/jasmineplows/box_office">GitHub</a>) and comments and suggestions are always welcome! We will continue to publish articles like this here (<a href="https://medium.com/@unpromptedblog">Unprompted — A Data Science Blog</a>), and you can find each of us on LinkedIn for further discussion (<a href="https://www.linkedin.com/in/jasmine-plows-ph-d-41a4894a/">Jasmine</a> and <a href="https://www.linkedin.com/in/justinkiehl/">Justin</a>).</p><p>Thanks for reading, and we wish you a healthy and happy 2026!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f015569d42e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a web app for tracking your recreational sports team’s stats ]]></title>
            <link>https://medium.com/@jasmineplows/how-to-build-a-web-app-for-tracking-your-recreational-sports-teams-stats-8df888f71015?source=rss-1e0650579559------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df888f71015</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jasmine Plows]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 23:18:35 GMT</pubDate>
            <atom:updated>2023-11-02T23:18:35.646Z</atom:updated>
            <content:encoded><![CDATA[<p>In March of this year, I challenged myself by doing something totally new and outside my comfort zone — I joined a <a href="https://en.wikipedia.org/wiki/Flag_football">Flag Football</a> team. The team plays as part of the <a href="https://outloudsports.com/losangeles">OutLoud Sports</a> league in West Hollywood, CA — a queer sports league open to everyone that includes kickball, dodgeball, soccer, and more. OutLoud Sports has had All-Gender Flag Football for several years now, but this year they added an additional She/They league. For those who don’t know, Flag Football is a non-tackle version of American Football, where instead of tackling, you must grab one of three flags that are connected by velcro to a belt around each player’s hips.</p><p>The season started with a “skills night”, where captains watched players do drills, and drafted players to their teams. I was drafted into a team called the “LA Clams”, along with 14 other amazing people. We play 8 week seasons — 5 weeks of regular season games, and 3 weeks of playoffs. So far, we have completed two seasons (Spring and Summer 2023), and are currently in the middle of the Fall 2023 season.</p><p>As both a sports fan and data nerd, I have always been interested in sports analytics, and dabbled with it for fun during my PhD, at the height of my NBA obsession. When the 2023/24 NFL season started a few months back — along with the accompanying <a href="https://en.wikipedia.org/wiki/Fantasy_football_(gridiron)">fantasy football</a> craze— I started wondering what my own football team’s stats look like, and thought it would be a cool project.</p><p><strong>The goal: </strong>to track my Flag Football team’s stats, and display them on a web app so my team can view them after each game.</p><p>My first challenge was identifying a way to collect the data for tracking. Of course, in professional leagues, there are people whose entire job it is to track stats during games. In rec leagues, this is more difficult, and because I’m playing on the field, I obviously can’t track stats myself. Lucky for me, my wife agreed to film every play of each game from the sideline — both defense and offense — using my phone. This allowed me to play back the recordings after each game.</p><p>My next challenge was finding a way to translate the recordings into actual data. I’m fairly certain that in the not-so-distant future, ChatGPT will be able to do this for me (i.e. ingest videos along with labels pertaining to each player, and output what happened in the video, along with each player’s stats). But for now, this requires human input. I played around with several approaches, until I settled on what seemed most straightforward: an app with one page to display stats and another page for entering new data. I am a big fan of <a href="https://streamlit.io/">Streamlit </a>— a Python library that allows you to create a web app in just a few minutes, and I knew it would be perfect for this use case.</p><p>I started with the data collection page, by creating a Python script named Admin.py . Admin.py needed to be access-controlled, so that only the admin (in my case, me), could enter new stats. To do this, I used the excellent streamlit-authenticator package. Read more <a href="https://blog.streamlit.io/streamlit-authenticator-part-1-adding-an-authentication-component-to-your-app/">here</a>. Then I wrote a simple script where the admin can enter the stats play-by-play. This play-by-play entry structure is preferable over, say, player-by-player because it allows the admin to simply watch the recorded videos one-by-one in order, and enter the stats as they go. Any other structure would require additional steps to keep track of player stats while watching the videos. Here is the finished Admin.py script (NOTE: also check out the <a href="https://github.com/jasmineplows/laclams/tree/master">GitHub repo</a>, which may be more up-to-date than what is written here):</p><pre>import streamlit as st<br>import pandas as pd<br>import streamlit_authenticator as stauth #add abilty to authenticate<br>import os<br>import yaml<br>from src.setup import get_players<br><br>def calculate_points(action, conversion_type=None, conversion_outcome=None):<br>    points = 0<br>    if action in [&#39;Touchdown&#39;, &#39;Pick-Six&#39;]:  # Correctly check if the action is one of these types<br>        points = 6  # standard points for a touchdown or pick-six<br><br>    # Check if there was an attempted conversion and whether it was successful<br>    if action == &#39;Conversion&#39; and conversion_outcome == &#39;Complete&#39;:<br>        if conversion_type == &#39;1-point&#39;:<br>            points = 1  # points for a successful 1-point conversion<br>        elif conversion_type == &#39;2-point&#39;:<br>            points = 2  # points for a successful 2-point conversion<br><br>    return points<br><br># get credentials for dashboard<br>with open(&#39;credentials.yaml&#39;) as file:<br>    config = yaml.safe_load(file)<br><br>authenticator = stauth.Authenticate(<br>    config[&#39;credentials&#39;],<br>    config[&#39;cookie&#39;][&#39;name&#39;],<br>    config[&#39;cookie&#39;][&#39;key&#39;],<br>    config[&#39;cookie&#39;][&#39;expiry_days&#39;],<br>    config[&#39;preauthorized&#39;]<br>)<br><br>name, authentication_status, username = authenticator.login(&#39;Login&#39;, &#39;main&#39;)<br><br># only if log-in was successful, continue<br>if authentication_status:<br><br>    st.header(&quot;LA Clams Statistics Entry Page&quot;)<br><br>    # Check if the stats CSV exists, if not, create an empty one<br>    if not os.path.exists(&#39;team_stats.csv&#39;):<br>        columns = [<br>            &#39;Week&#39;, &#39;Opponent&#39;, &#39;Half&#39;, &#39;Down&#39;, &#39;Yards to Go&#39;,<br>            &#39;Play&#39;, &#39;Offense/Defense&#39;, &#39;Players on Field&#39;, &#39;Player Positions&#39;, &#39;Action&#39;, <br>            &#39;Player Involved&#39;, &#39;Touchdown Type&#39;, &#39;Pass Outcome&#39;, &#39;Yards&#39;, &#39;Points&#39;, &#39;Notes&#39;<br>        ]<br>        pd.DataFrame(columns=columns).to_csv(&#39;team_stats.csv&#39;, index=False)<br><br>    # Initialize or update session state variables<br>    if &#39;play_count&#39; not in st.session_state:<br>        st.session_state.play_count = 0<br>    if &#39;week&#39; not in st.session_state:<br>        st.session_state.week = 1<br>    if &#39;opponent&#39; not in st.session_state:<br>        st.session_state.opponent = &quot;&quot;<br><br>    # Set Week number<br>    new_week = st.number_input(&#39;Week:&#39;, min_value=1, value=st.session_state.week)<br>    if new_week != st.session_state.week:<br>        # When moving to a new week, reset all weekly information<br>        st.session_state.week = new_week<br>        st.session_state.play_count = 0<br>        st.session_state.opponent = &quot;&quot;<br><br>    # Information about the game<br>    if st.session_state.opponent == &quot;&quot;:<br>        st.session_state.opponent = st.text_input(&#39;Opponent:&#39;, value=st.session_state.opponent)<br><br>    # default values<br>    td_type = None<br>    conversion_type = None<br>    conversion_outcome = None<br><br>    # Display the play count<br>    st.write(f&quot;Inputting data for Play: {st.session_state.play_count + 1}&quot;)<br><br>    # Selecting offense or defense<br>    offense_or_defense = st.selectbox(&#39;Offense or defense?&#39;, [&#39;Offense&#39;, &#39;Defense&#39;], key=&quot;offense_defense_select&quot;)<br><br>    # Based on the selection above, present relevant positions<br>    if offense_or_defense == &#39;Offense&#39;:<br>        positions = [&#39;Quarterback&#39;, &#39;Wide Receiver&#39;, &#39;Running Back&#39;, &#39;Tight End&#39;, &#39;Center&#39;]  # Offense positions<br>    else:<br>        positions = [&#39;Pass Rusher&#39;, &#39;Corner Back&#39;, &#39;Safety&#39;]  # Defense positions<br><br>    # Play info<br>    half = st.selectbox(&#39;Half:&#39;, [&#39;1st&#39;, &#39;2nd&#39;], key=&quot;half_select&quot;)<br>    down = st.number_input(&#39;Down (1-4):&#39;, min_value=1, max_value=4, value=1, key=&quot;down_input&quot;)<br>    yards_to_go = st.number_input(&#39;Yards to Go:&#39;, min_value=0, value=10, key=&quot;yards_to_go_input&quot;)<br><br>    players = get_players()<br><br>    # Multi-select for players on the field<br>    selected_players = st.multiselect(&#39;Select players on the field:&#39;, players, key=&quot;players_field_multiselect&quot;)<br><br>    # Check if exactly 7 players are selected<br>    if len(selected_players) != 7:<br>        st.warning(&#39;Please select exactly 7 players before proceeding.&#39;)<br>        st.stop()<br><br>    # Assign positions to selected players, now using the relevant positions list<br>    player_positions = {player: st.selectbox(f&quot;Position for {player}:&quot;, positions, key=f&quot;position_for_{player}&quot;) for player in selected_players}<br>    player_involved_options = [&#39;No specific player&#39;, *players]<br><br>    # Action info<br>    action = st.selectbox(&#39;Action:&#39;, [&#39;Pass&#39;, &#39;Run&#39;, &#39;Flag Pull&#39;, &#39;Touchdown&#39;, &#39;Conversion&#39;, &#39;Interception&#39;, &#39;Forced Fumble&#39;, &#39;Sack&#39;, &#39;Pick-Six&#39;, &#39;Penalty&#39;], key=&quot;action_select&quot;)<br><br>    # Player involved in the action<br>    player_involved = None<br>    if action in (&#39;Pass&#39;, &#39;Run&#39;, &#39;Flag Pull&#39;, &#39;Touchdown&#39;, &#39;Conversion&#39;, &#39;Forced Fumble&#39;, &#39;Interception&#39;, &#39;Sack&#39;):<br>        player_involved = st.selectbox(&#39;Who was the player involved (if any)?&#39;, player_involved_options, key=&#39;player_involved&#39;)<br><br>    # Additional information based on the type of action<br>    td_type = pass_outcome = None<br>    if action == &#39;Touchdown&#39;:<br>        td_type = st.selectbox(&#39;Type of touchdown:&#39;, [&#39;Passing Touchdown&#39;, &#39;Rushing Touchdown&#39;], key=&quot;td_type_select&quot;)<br>    elif action == &#39;Pass&#39;:<br>        pass_outcome = st.selectbox(&#39;Was the pass complete?&#39;, [&#39;Complete&#39;, &#39;Incomplete&#39;], key=&quot;pass_outcome_general&quot;)<br>    elif action == &#39;Conversion&#39;:<br>        conversion_type = st.selectbox(&#39;1-point or 2-point conversion?&#39;, [&#39;1-point&#39;, &#39;2-point&#39;], key=&quot;conversion_type_select&quot;)<br>        conversion_outcome = st.selectbox(&#39;Was the conversion complete?&#39;, [&#39;Complete&#39;, &#39;Incomplete&#39;], key=&quot;conversion_outcome_select&quot;)<br><br>    # Yards info<br>    yards = st.number_input(&#39;Yards gained/lost:&#39;, min_value=-100, max_value=100, value=0, key=&quot;yards_input&quot;)<br><br>    # Additional notes<br>    notes = st.text_area(&#39;Any additional notes or details about the play:&#39;, key=&quot;notes_text_area&quot;)<br><br>    # Submit the play info<br>    if st.button(&#39;Submit Play Info&#39;, key=&quot;submit_play_info_button&quot;):<br>        # Increase the play count for each submission<br>        st.session_state.play_count += 1<br><br>        # Read the current CSV<br>        df = pd.read_csv(&#39;team_stats.csv&#39;)<br><br>        # Calculate points based on the action<br>        points = calculate_points(action, conversion_type, conversion_outcome)<br><br>        # Append the new data<br>        new_data = {<br>            &#39;Week&#39;: st.session_state.week,<br>            &#39;Opponent&#39;: st.session_state.opponent,<br>            &#39;Half&#39;: half,<br>            &#39;Down&#39;: down,<br>            &#39;Yards to Go&#39;: yards_to_go,<br>            &#39;Play&#39;: st.session_state.play_count,<br>            &#39;Offense/Defense&#39;: offense_or_defense,<br>            &#39;Players on Field&#39;: &#39;, &#39;.join(selected_players),<br>            &#39;Player Positions&#39;: &#39;, &#39;.join(f&quot;{player} as {position}&quot; for player, position in player_positions.items()),<br>            &#39;Action&#39;: action,<br>            &#39;Player Involved&#39;: player_involved,<br>            &#39;Touchdown Type&#39;: td_type,<br>            &#39;Pass Outcome&#39;: pass_outcome,<br>            &#39;Conversion Outcome&#39;: conversion_outcome,<br>            &#39;Yards&#39;: yards,<br>            &#39;Points&#39;: points,<br>            &#39;Notes&#39;: notes,<br>        }<br><br>        df = pd.concat([df, pd.DataFrame([new_data])], ignore_index=True)<br><br>        # Save the updated CSV<br>        df.to_csv(&#39;team_stats.csv&#39;, index=False)<br>        st.success(&#39;Play info saved successfully!&#39;)<br><br>    # Option to delete a play if a mistake was made<br>    if st.button(&#39;Delete Last Play&#39;):<br>        if st.session_state.play_count &gt; 0:<br>            df = pd.read_csv(&#39;team_stats.csv&#39;)<br>            # Make sure we&#39;re deleting the right play (the most recent for the current week)<br>            recent_play = df[(df[&#39;Week&#39;] == st.session_state.week) &amp; (df[&#39;Play&#39;] == st.session_state.play_count)]<br>            if not recent_play.empty:<br>                # Correctly update the play_count before deleting the entry from the DataFrame<br>                st.session_state.play_count -= 1<br>                # Deleting the row with the most recent play<br>                df = df.drop(recent_play.index)<br>                # Save the updated CSV<br>                df.to_csv(&#39;team_stats.csv&#39;, index=False)<br>                st.success(&#39;Last play deleted successfully.&#39;)<br>            else:<br>                st.error(&#39;No play available to delete for the current week.&#39;)<br>        else:<br>            st.error(&#39;No plays have been inputted yet for deletion.&#39;)<br><br>    # Display the current data<br>    st.subheader(&#39;Current Team Stats&#39;)<br>    current_df = pd.read_csv(&#39;team_stats.csv&#39;)  # This df is loaded after any possible deletion operation above<br>    st.data_editor(current_df)<br><br>    if st.button(&#39;Save&#39;, key=&quot;save&quot;):<br>        current_df.to_csv(&#39;team_stats.csv&#39;, index=False)<br>        st.success(&#39;Updated data saved successfully!&#39;)<br><br># don&#39;t let someone in without the password<br>elif authentication_status is False:<br>    st.error(&#39;Username/password is incorrect&#39;)</pre><p>The resulting Streamlit page (generated by running streamlit run Admin.py in the terminal) looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q91CC-VVLoS_h6lsE-ZTQQ.png" /><figcaption>Login page for the admin</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*666Th3y-ioPYvh8owRTvCw.png" /><figcaption>Once logged in, the admin user can enter stats play-by-play</figcaption></figure><p>To demonstrate how this works, here is a play from our league (with me catching the ball — a rarity!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*478zR-DpkDxU6Rm6jlI1Hg.gif" /></figure><p>To log this play, I would simply enter the week of the game and the opponent team’s name, and then I would select that we were on offense and that it was the first half and so on. I would also select all the players on the field for the play, along with their positions. Finally, I would enter the events that occurred during the play, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeQE5R3INzFcXyKHY9mPlg.png" /><figcaption>How to enter the events for each play</figcaption></figure><p>Once done, I would click “Submit”, and then repeat for each play, until done. The whole process takes approximately 15 minutes per game.</p><p>Once I finished creating the data entry page, it was time to create the page that actually displays that stats. For this, I created another Python file called Home.py :</p><pre>import streamlit as st<br>import pandas as pd<br>from src.setup import get_players<br>from src.metrics import *<br><br># Function to load data<br>@st.cache_data<br>def load_data():<br>    return pd.read_csv(&#39;team_stats.csv&#39;)<br><br>def main():<br>    # Page configuration<br>    st.set_page_config(page_title=&quot;LA Clams Stats&quot;, page_icon=&quot;🏈&quot;)<br>    hide_menu_style = &quot;&quot;&quot;<br>    &lt;style&gt;<br>    #MainMenu {visibility: hidden;}<br>    footer {visibility: hidden;}<br>    &lt;/style&gt;<br>    &quot;&quot;&quot;<br>    st.markdown(hide_menu_style, unsafe_allow_html=True)<br><br>    # Display the header and logo<br>    display_header()<br><br>    # Load the data<br>    data = load_data()  # Make sure to define this function to load your data<br><br>    # Display the season title<br>    st.subheader(&quot;🍁 Fall 2023 Season 🍁&quot;)<br><br>    # Get weeks with data and calculate total stats and season averages<br>    weeks_with_data = data[&#39;Week&#39;].unique()<br>    calculate_season_statistics(data)<br><br>    # Individual game statistics section<br>    st.subheader(&quot;Individual Game Statistics&quot;)<br><br>    # Week selection dropdown<br>    week_selection = st.selectbox(&#39;Select a Week&#39;, [&#39;Week &#39; + str(i) for i in range(1, 11)])<br>    week_number = int(week_selection.split(&#39; &#39;)[1])<br><br>    # Check if data for the selected week exists<br>    if week_number in weeks_with_data:<br>        week_data = data[data[&#39;Week&#39;] == week_number]<br>        weekly_stats = calculate_weekly_statistics(week_data, week_number)<br>    else:<br>        # Display error message if no data for the selected week<br>        st.error(f&quot;No stats available for {week_selection}. Please select another week.&quot;)<br><br>    #####################################################<br>    <br>    # Sort player names in alphabetical order<br>    sorted_player_names = sorted(get_players())<br><br>    st.subheader(&quot;Individual Player Stats&quot;)<br>    <br>    # Dropdown to select a player<br>    selected_player = st.selectbox(&#39;Select a player&#39;, sorted_player_names)<br>    <br>    # Display the stats<br>    st.subheader(f&#39;Season stats for {selected_player}&#39;)<br><br>    # Get the average statistics for the selected player<br>    calculate_average_stats(data, selected_player)<br><br>    st.subheader(&quot;Per-game player stats&quot;)<br><br>    # Dropdown to select the week<br>    week = st.selectbox(&#39;Select Week&#39;, options=data[&#39;Week&#39;].unique())<br><br>    # Dropdown to select the player<br>    selected_player = st.selectbox(&#39;Select Player&#39;, options=sorted_player_names)<br><br>    # Display the stats in the app<br>    st.write(f&quot;Stats for {selected_player} in week {week}:&quot;)<br><br>    # Calculate stats for the selected player and week<br>    calculate_individual_player_stats(data, week, selected_player)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>You can see that, in order to keep Home.py from becoming too long and convoluted, I put the metric calculations in a separate file called metrics.py , which is located in the src subfolder. The script is quite long, so I encourage you to check it out on the GitHub, <a href="https://github.com/jasmineplows/laclams/blob/master/src/metrics.py">here</a>. metrics.py also references another file, called setup.py , which you can find <a href="https://github.com/jasmineplows/laclams/blob/master/src/setup.py">here</a>. The general purpose of these files is to collate the detailed play-by-play data in statistics per season, per game, per player per season, and per player per game. Football is a fairly complex sport, where each player has a different position and different positions have different stats to be tracked. I anticipate that the summary statistics for other sports such as basketball and soccer would be a lot easier to generate!</p><p>Here is what the resulting Streamlit app looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSKdkM34Hf6UEmd1pmEKeg.png" /><figcaption>Logo credit: Emily Horrocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0009Q8mfREgcfoevWxa4A.png" /><figcaption>Per-game statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0djH2NSxnnYh7z4_-OK3dw.png" /><figcaption>Per-player per-season statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRZAJxFvFgntQ_Ua24A_wA.png" /><figcaption>Per-player per-game statistics</figcaption></figure><p>Finally, I needed to organize the pages appropriately. Since Home.py is the main page, and admin is a subpage, I moved Admin.py to a subfolder called pages . This is a <a href="https://docs.streamlit.io/library/get-started/multipage-apps/create-a-multipage-app">Streamlit feature</a> that automatically sorts the files into the home page and subpages. The final structure looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*kf3fqaCQDcTzwx1Z9A1jhQ.png" /><figcaption>The folder structure</figcaption></figure><p>I then published my app to the <a href="https://streamlit.io/cloud">Streamlit community cloud</a>, simply by clicking the “Deploy” button on the local app. You can check out the finished app at <a href="https://laclams.streamlit.app/">laclams.streamlit.app</a></p><p>And that’s it! I hope this was a helpful tutorial for those of you who are interested in creating a stats tracking app for your recreational sports team. Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df888f71015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build your own version of Iron Man’s voice-activated assistant J.A.R.V.I.S., using ChatGPT]]></title>
            <link>https://medium.com/@jasmineplows/how-to-build-your-own-version-of-iron-mans-voice-activated-assistant-j-a-r-v-i-s-using-chatgpt-4b738bbe8147?source=rss-1e0650579559------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b738bbe8147</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[chatgpt3]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Jasmine Plows]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 02:24:33 GMT</pubDate>
            <atom:updated>2023-01-18T01:50:38.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZ1DPQf1cIohTe8W3RHJVA.png" /><figcaption>J.A.R.V.I.S., as depicted in Age of Ultron (2015)</figcaption></figure><blockquote>Note: I used a Raspberry Pi for this, so this tutorial is tailored for Raspberry Pi OS systems. However, instructions should be similar/the same for macOS and Linux and should require only minor changes for Windows.</blockquote><p>Recently, I was re-watching <a href="https://en.wikipedia.org/wiki/Iron_Man_(2008_film)"><em>Iron Man</em></a> and the excellent new <em>Star Wars</em> series <a href="https://en.wikipedia.org/wiki/Andor_(TV_series)"><em>Andor</em></a>, and was struck by how helpful the voice-activated assistants are in these universes. Both <a href="https://marvelcinematicuniverse.fandom.com/wiki/J.A.R.V.I.S.">J.A.R.V.I.S.</a>, from <em>Iron Man</em>, and <a href="https://starwars.fandom.com/wiki/Third-degree_droid">Class 3 droids</a> in <em>Star Wars</em> act as fully intelligent robotic assistants. They understand language, provide a useful function, and then perfectly articulate a response. Of course, we’ve had voice-activated virtual assistants such as <a href="https://en.wikipedia.org/wiki/Amazon_Alexa">Amazon’s Alexa</a> and <a href="https://en.wikipedia.org/wiki/Siri">Apple’s Siri</a> for about a decade now, but they each leave something to be desired. For one, they never seem to understand when you’re talking to them (I find myself yelling “ALEXA” over and over again until I get a response), and when they do, they often interpret your question incorrectly. However, their biggest limitation, in my opinion, is how infrequently they are able to <em>actually answer questions</em>. I’ll often have a question I want answered but Alexa will be unable to meaningfully help me answer it. Instead, she’ll bring up a google search on my phone, requiring me to pull out my phone and manually scroll through the Google search page. To me, this isn’t all that useful, and it is a far cry from what J.A.R.V.I.S. and the droids of the <em>Star Wars</em> universe offer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZg_nD_x0bgM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZg_nD_x0bgM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZg_nD_x0bgM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/45cc45cb0dc02eb781ae5dee213032bb/href">https://medium.com/media/45cc45cb0dc02eb781ae5dee213032bb/href</a></iframe><p>A.I.’s are getting more advanced though. Last November, <a href="https://openai.com/">OpenAI</a> launched <a href="https://openai.com/blog/chatgpt/">ChatGPT</a>. ChatGPT stands for Generative Pre-Trained Transformer, and it is an A.I.-powered chatbot that can do all sorts of things. For starters, it can act as a search engine that answers your question in full sentences rather than requiring you to click on links, find the relevant information, and interpret it yourself. But it can also be creative, and can write its own poems, essays, and screenplays, all within seconds. Since its launch, I’ve been amazed at its functionality, and I have almost completely replaced Google Searches with it (something that <a href="https://www.cnet.com/tech/services-and-software/chatgpt-caused-code-red-at-google-report-says/">Google itself </a>has been afraid of). Any question I have, even coding questions, it answers effortlessly and within seconds. Try it for yourself, <a href="http://chat.openai.com/">here</a>.</p><p>The limitation, however, is that you must log in to the OpenAI website and type your question each time you want to use it. What if you could have your own personal ChatGPT that could understand you, answer your question, and then read aloud your answer, so you would never have to pull out your phone? You would essentially have your own J.A.R.V.I.S.! A virtual assistant that is highly intelligent and able to understand language and audibly relay information back to you. When I received a <a href="https://www.raspberrypi.com/products/raspberry-pi-4-model-b/">Raspberry Pi 4B</a> (an inexpensive single board computer that is great for <a href="https://itsfoss.com/raspberry-pi-projects/">projects like these</a>) for Christmas, I thought this would be a great first project.</p><p>I started in a very meta manner — I asked ChatGPT itself as to the best way to do my project, and here’s what it said:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ny60WVRoFf53qqxW416Ptg.jpeg" /><figcaption>I used ChatGPT to figure out how to make a ChatGPT virtual assistant</figcaption></figure><p>Amazed at its detailed answer, I decided to follow ChatGPT&#39;s advice, and I also asked it questions when I got stuck. Overall, the entire process took about 5 hours of trial-and-error before I had a fully working prototype, and the code is surprisingly simple. Here it is:</p><blockquote>UPDATE 2023/01/17: I have added “hey, Jarvis!” capability, and have also changed the text-to-speech library so it has a male (albeit, very robotic, unlike J.A.R.V.I.S.) voice. Feel free to check out previous commits of the code at the <a href="https://github.com/jasmineplows/jarvis">GitHub repo.</a></blockquote><pre>import time<br>import speech_recognition as sr<br>import os<br>import openai<br>import pyttsx3<br><br># Function to transcribe audio, send to ChatGPT, and read aloud<br>def listen_and_respond(after_prompt=True):<br> &quot;&quot;&quot;<br> Transcribes audio, sends to ChatGPT, and responds in speech<br> <br> Args:<br> after_prompt: bool, whether the response comes directly<br> after the user says &quot;Hey, Jarvis!&quot; or not<br> <br> &quot;&quot;&quot;<br> # Default is don&#39;t start listening, until I tell you to<br> start_listening = False<br><br> with microphone as source:<br><br>  if after_prompt:<br>   recognizer.adjust_for_ambient_noise(source)<br>   print(&quot;Say &#39;Hey, Jarvis!&#39; to start&quot;)<br>   audio = recognizer.listen(source, phrase_time_limit=5)<br>   try:<br>    transcription = recognizer.recognize_google(audio)<br>    if transcription.lower() == &quot;hey jarvis&quot;:<br>     start_listening = True<br>    else:<br>     start_listening = False<br>   except sr.UnknownValueError:<br>    start_listening = False<br>  else:<br>   start_listening = True<br>  <br>  if start_listening:<br>   try:<br>    print(&quot;Listening for question...&quot;)<br>    audio = recognizer.record(source, duration=5)<br>    transcription = recognizer.recognize_google(audio)<br>    print(f&quot;Input text: {transcription}&quot;)<br>     <br>    # Send the transcribed text to the ChatGPT3 API<br>    response = openai.Completion.create(<br>    engine=&quot;text-davinci-003&quot;,<br>    prompt=transcription,<br>    temperature=0.9,<br>    max_tokens=512,<br>    top_p=1,<br>    presence_penalty=0.6<br>    )<br><br>    # Get the response text from the ChatGPT3 API<br>    response_text = response.choices[0].text<br><br>    # Print the response from the ChatGPT3 API<br>    print(f&quot;Response text: {response_text}&quot;)<br><br>    #  Say the response<br>    engine.say(response_text)<br>    engine.runAndWait()<br> <br>   except sr.UnknownValueError:<br>    print(&quot;Unable to transcribe audio&quot;)<br><br><br># pyttsx3 engine paramaters<br>engine = pyttsx3.init()<br>engine.setProperty(&#39;rate&#39;, 150) <br>engine.setProperty(&#39;voice&#39;, &#39;english_north&#39;)<br><br># My OpenAI API Key<br>openai.api_key = os.environ[&quot;API_KEY&quot;]<br><br>recognizer = sr.Recognizer()<br>microphone = sr.Microphone()<br><br># First question<br>first_question = True<br><br># Initialize last_question_time to current time<br>last_question_time = time.time()<br><br># Set threshold for time elapsed before requiring &quot;Hey, Jarvis!&quot; again<br>threshold = 60 # 1 minute<br><br>while True:<br> if (first_question == True) | (time.time() - last_question_time &gt; threshold):<br>  listen_and_respond(after_prompt=True)<br>  first_question = False<br> else:<br>  listen_and_respond(after_prompt=False)<br><br># Can run in terminal with following command to suppress warnings:<br># python jarvis.py 2&gt;/dev/null</pre><p>I tried a few different speech-to-text libraries, but <a href="https://pypi.org/project/SpeechRecognition/">SpeechRecognition</a> was by far the simplest and most accurate (I found pocketsphinx was often unable to transcribe my New Zealand accent). I then used <a href="https://www.codingthesmartway.com/how-to-use-chatgpt-with-python/">this</a> tutorial to access ChatGPT via Python (there is <a href="https://community.openai.com/t/is-there-an-api-for-chatgpt3/23871">no official OpenAI ChatGPT API yet</a>) and the <a href="https://pypi.org/project/pyttsx3/">pyttsx3</a> library to read aloud the response (Note: I previously used <a href="https://pypi.org/project/gTTS/">gTTS</a> but it doesn’t allow you to change the voice, so I switched). Here are the step by step instructions if you want to get this working (all in about 10 mins!):</p><p>Step 1: Clone or fork my GitHub repository <a href="https://github.com/jasmineplows/jarvis">here</a>.</p><p>Step 2: Create a virtual environment (on a Raspberry Pi, here are the instructions):</p><pre>$ python3 -m venv jarvis </pre><p>Step 3: Activate your new virtual environment:</p><pre>$ source jarvis/bin/activate</pre><p>Step 4: Install requirements.txt into your virtual environment:</p><pre>$ cd &lt;path-to-jarvis-folder-where-requirements.txt-is&gt;<br><br>$ pip install -r requirements.txt</pre><p>Step 5: Plug in a USB or Bluetooth microphone (if you don’t already have one built-in to your machine) and make sure it is set as your default microphone.</p><p>Step 6: Plug in USB or Bluetooth speaker (if you don’t already have one built-in to your machine/monitor)</p><p>Step 7: Go to openai.com and <a href="https://openai.com/blog/chatgpt/">create an account</a> (it will prompt you to do this when you try to use ChatGPT on the web).</p><p>Step 8: Go to settings and click on API keys. You get $18 in free API credit that can be used during your first three months of having an account. After that, you will have to pay for API calls. But you don’t need to enter your credit card information to get started, which is great (Note: if you made an Open AI account a long time ago, your free credits may have expired. In this case, either pay or set up a new account).</p><p>Step 9: Copy your key. Create a new one if you can’t access it.</p><p>Step 10: Now you need to add your API key such that your script can access it. NOTE: DO NOT SHARE YOUR API KEY ANYWHERE ELSE AND BE CAREFUL NOT TO ACCIDENTALLY MAKE IT PUBLIC.</p><pre>$ nano ~/.bashrc</pre><p>Then add the following line at the end of the .bashrc file:</p><pre>export API_KEY=“your_key_here”</pre><p>Ctrl + X to exit, “Y” to save, then “Enter”.</p><p>Step 11: Now that you have everything set up, all you need to do is this:</p><pre>$ cd &lt;path-to-jarvis-folder&gt;/src<br><br>$ python jarvis.py</pre><p>If you get a bunch of annoying warnings, type this command instead to suppress them:</p><pre>$ python jarvis.py 2&gt;/dev/null</pre><p>Note, however, that doing this will suppress errors too, so you won’t know what broke if something breaks.</p><p>Step 12: The program will commence with the following prompt:</p><pre>Say &#39;Hey, Jarvis!&#39; to start</pre><p>All you need to do is say “Hey, Jarvis” aloud.</p><p>When the program picks up on that prompt, you will see the following text:</p><pre>Listening...</pre><p>Now ask your question, and wait for the answer! The terminal will also print your question as well as the response.</p><p>You can continue asking questions without saying “Hey, Jarvis” after that (unless you let more than a minute pass, in which case you’ll have to say “Hey, Jarvis” again).</p><p>Now you have a fully working J.A.R.V.I.S. prototype! Of course, all it can do at this point is answer questions that ChatGPT can answer, but personally I find it much more useful than Alexa or Siri for that purpose.</p><p>However, I have some ideas for ways to improve it which I will add as additional parts of this blog in the future:</p><ol><li>It’s a little annoying to have to wait after saying “Hey, Jarvis” before asking the first question. Alexa and Siri allow you to continue speaking immediately after the initial prompt. This shouldn’t be too hard to add, so I’ll update here when I can. I would also like to have this running using a <a href="https://www.amazon.com/stores/page/92B81F7A-D401-4CB1-9E7C-E5EC9FD42BE4?ingress=0&amp;visitId=b8e6fe77-548d-48df-9935-c69d6644223d">Jabra</a> system, which is a fully wireless microphone and speaker all-in-one. As long as the program is running, the Jabra is in Bluetooth range, and the wi-fi is working, I will be able to carry my Jabra around the house as my own portable wireless J.A.R.V.I.S.</li><li>I have a <a href="https://disneyland.disney.go.com/shops/disneyland/droid-depot/">customizable R2 unit droid</a> that I built at Disneyland’s Galaxy’s Edge in 2019. Currently, it can only move around (via remote control) and make noises/light up. I am thinking of opening it up, adding a <a href="https://www.raspberrypi.com/products/raspberry-pi-zero-w/">Raspberry Pi Zero W</a> with a small microphone and speaker (or re-wiring the existing speaker) and a battery pack, and then running the program from there. Then I won’t need the Raspberry Pi 4B at all, and I could have my own little intelligent droid!</li><li>I would, of course, like to add functionality to help me with things other than question-answering. Right now, it can only answer questions, but I could use it to turn on lights, adjust the thermostat, or tell me which of my plants need to be watered. The possibilities are endless!</li></ol><p>I’ll add to this blog as I complete these projects, but I hope this is helpful in the meantime!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b738bbe8147" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>