<?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 Vianney Mixtur on Medium]]></title>
        <description><![CDATA[Stories by Vianney Mixtur on Medium]]></description>
        <link>https://medium.com/@vianney.mixtur_39698?source=rss-a4e4eaffe65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fcY0ivYHCHJcpy1pI_bD7Q.jpeg</url>
            <title>Stories by Vianney Mixtur on Medium</title>
            <link>https://medium.com/@vianney.mixtur_39698?source=rss-a4e4eaffe65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:34:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vianney.mixtur_39698/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[AI Environmental Paradox]]></title>
            <link>https://medium.com/@vianney.mixtur_39698/ai-environmental-paradox-68ee89e64372?source=rss-a4e4eaffe65------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ee89e64372</guid>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[tech-for-good]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[climatetech]]></category>
            <dc:creator><![CDATA[Vianney Mixtur]]></dc:creator>
            <pubDate>Wed, 21 May 2025 09:20:39 GMT</pubDate>
            <atom:updated>2025-05-21T19:56:59.873Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can AI Save the Planet Without Destroying It?</h4><p><em>All my articles published on Medium are free. If you have trouble reading it here, you might try </em><a href="https://www.notion.so/vianmixt/AI-Environmental-Paradox-1f1af60d977880b7adf0d5bfa8b776f8"><em>this link</em></a><em>.</em></p><p>The World Economic Forum ranked climate action failure as the top global risk of the decade and environmental risks make half of the top 10 [1].</p><figure><img alt="Diagram showing the top 10 globak risk for the next decade by the World Economic Forum" src="https://cdn-images-1.medium.com/max/986/1*ErlOW7AsjFzUO2glbjuGUQ.png" /><figcaption>Source: World Economic Forum Global Risks Perception Survey 2024–2025</figcaption></figure><p>Mitigating those risks is really where most of our collective efforts should go right now. Unfortunately, we are racing to develop Artificial General Intelligence without taking the time to think about the <a href="https://en.wikipedia.org/wiki/AI_alignment">AI Alignment problem</a>. In other words, the incentives to develop AI as fast as possible are so high, that most actors rush to innovate in that space while we are not sure if AI will be an ally or an obstacle in our societies battles.</p><p>I believe the best way to achieve the best outcomes possible in today’s landscape is to put technology at work for the better to help us win. In a nutshell, let’s produce more <strong>renewable energy</strong> and less SUVs and more broadly.</p><p>Let’s make the best use of technology as it is a precious resource. On a technological point of view, one of the best tools that we currently have at hand is AI. In this article, I’m going to share my views on how AI can help in solving some of the major issues we face with the environment and question whether it is an ally or an aggravating risk factor.</p><h3>The Role AI Should Play</h3><p>From <strong>climate change</strong> to <strong>water scarcity</strong>, through <strong>loss of biodiversity</strong> and <strong>pollution</strong>, the world is facing several interconnected environmental challenges. Unlike previous crises like wars, economic downturns or pandemics, there are no clear adversaries, the issue cannot be solved by interest rate adjustments or by a miraculous vaccine. The <strong>systemic nature</strong> of those challenges require <strong>collective action</strong>, <strong>innovation</strong> and a systemic <strong>transformation</strong>.</p><p>Given the global environmental challenges ahead, artificial intelligence appears to be a timely response to our need for innovation and systemic transformation as it is anenabler of solutions across multiple domains. Indeed, AI technologies offer unprecedented capabilities to monitor, analyze, optimize, and transform our relationship with natural and complex systems. By processing vast amounts of environmental data at scales and speeds impossible for human analysts, AI can illuminate patterns and connections previously invisible, helping us understand ecosystem dynamics with new precision and foresight.</p><h3>Key Areas in which AI can make a difference</h3><p><strong>Energy Optimization</strong></p><p>AI is often described negatively by environmentalists, activists and policymakers because of the significant energy consumption of the latest <strong>Large Language Models</strong>. I’ll talk about this in greater detail in the next section of this article but first, let’s see the other side of the coin. AI can also be very positive in terms of energy optimization as it can intervene across the whole value chain. It can optimize energy production, distribution and consumption.</p><p>For example, in 2016, Google reduced by 40% the energy used for cooling its data centers by using AI [2][3]. They trained neural networks on historical sensor data to optimize for future <a href="https://en.wikipedia.org/wiki/Power_usage_effectiveness">Power Usage Effectiveness (PUE)</a> which is the ratio of total amount of energy used by a computer data center divided by the energy used by the computing equipment.</p><p><strong>Emissions Monitoring and Carbon Markets</strong></p><p>As with the previous domain, AI is already being implemented to enhance emissions monitoring, manage carbon markets and streamline carbon accounting across various industries.</p><p>Computer vision algorithms are being used to analyze satellite data to verify reforestation projects and detect fraudulent claims. Thus ensuring the legitimacy of credits or offsets bought by companies to achieve net-zero goals [4].</p><p>Similarly, computer vision could be used to analyze satellite imagery and detect methane emissions with precision. This AI-driven technique identifies methane plumes as small as 0.01 km² corresponding to sources emitting between 200–300 kg of methane per hour, offering significantly higher detection frequency and resolution than previous methods [5].</p><p>In carbon accounting, the key is to accurately collect the carbon data whether it is for reporting, decision making, or supply chain optimizations. AI automates and speeds up those processes. For instance, the carbon management platform Net0 reports that clients have achieved up to a 40% reduction in operational expenses related to decarbonization by automating data collection and validation processes [6].</p><blockquote>If you’re looking to enhance your environmental data collection and develop a more effective strategy, I’d love to connect. Let’s discuss how AI can drive your sustainability efforts.</blockquote><p><strong>Climate and Weather Forecasting</strong></p><p>The adoption of AI in weather forecasting is accelerating. As of 2023, 40% of weather forecasts are being refined using AI algorithms, and machine learning models have been adopted by 35 meteorological agencies worldwide [7]. Government agencies are gradually integrating AI technologies, while the private sector is rapidly capitalizing on these advancements. For example, the <a href="https://www.ecmwf.int/">European Centre for Medium-Range Weather Forecasts (ECMWF)</a> has integrated key components of AI approaches like GenCast (an advanced AI-powered weather forecasting model developed by Google DeepMind) [8] into their forecasting systems. This trend indicates a significant shift towards AI-enhanced forecasting methods across the industry.</p><p>Similarly AI is being used for flood and drought predictions, hurricane path tracing and in advanced climate models [9][10][11]. For the sake of brevity, I won’t elaborate on those use cases here.</p><p>AI is already playing a meaningful role in advancing sustainability — from optimizing energy usage to enhancing emissions monitoring and improving climate forecasting. It’s helping reduce power consumption in data centers, verify reforestation projects, and detect methane leaks with greater precision. AI is also streamlining carbon accounting and enabling more accurate, data-driven climate models — contributing to smarter, faster decisions on the path to net zero.</p><p>Given AI’s disruptive impact across nearly every industry, its growing influence in Environmental Tech is no surprise. What’s more important — and more complex — is evaluating that impact holistically. Can the benefits AI delivers in climate action outweigh the environmental cost of building and running these systems? That’s the balance we need to get right.</p><h3>Challenges and Opportunities of AI in Climate Tech</h3><p>After years of growth, the Climate Tech sector is now encountering some headwinds. According to PwC’s <em>State of Climate Tech 2024</em> report, there has been a notable decline in climate tech investment, with funding dropping by 29% to US$56 billion, now representing only 8.3% of total venture capital and private equity flows [12]. Despite the challenging market conditions, AI presents new opportunities for innovation. Energy-focused startups are gaining momentum, securing 35% of climate tech funding, while AI-driven climate ventures raised US$6 billion in the first three quarters of 2024, surpassing the US$5 billion raised throughout 2023.</p><p>As mentioned, in the previous section, a key challenge of using AI to solve environmental issues is the impact of AI usage itself on the environment. The recent developments in <strong>generative AI</strong> have exacerbated the environmental footprint of AI.</p><ul><li>AI might consume as much as six times more water than Denmark, a country of 6 million [13].</li><li>A request made through ChatGPT is assumed to consume 10 times the electricity of a Google Search [14].</li><li>The number of data centres — a critical infrastructure for AI — went from 500,000 in 2012 to 8 million in 2024 [15].</li><li>In 2022, data centers, cryptocurrencies, and AI collectively accounted for almost 2% of global electricity consumption, equating to 460 TWh [16].</li></ul><p>However, the numbers listed above have to be nuanced a bit. The first one is a predictive estimate, the second is from ongoing research and is debatable. As for the third and fourth, it’s unclear what part is attributable solely to AI. That said, it seems clear that we can have some concerns about AI resource usage.</p><p>The good news is that this challenge is already being tackled. Indeed, this topic was at the core of the AI Action Summit in Paris in February 2025 where several important initiatives were discussed. Notably, two initiatives focused on measuring AI’s environmental impact:</p><ul><li>The Coalition for Environmentally Sustainable AI that focuses on standardizing methods to measure AI’s environmental impacts [17].</li><li>The launch of the AI Energy Score that aims to address the lack of transparency about the environmental impact of AI models [18].</li></ul><p>While measuring AI’s environmental impact is the first step, it’s not enough. For that reason, tech companies are exploring solutions like nuclear power, renewable energy and hardware recycling to reduce AI’s environmental impact while governments are introducing regulations to ensure AI infrastructure aligns with sustainability goals.</p><h3>Wrapping Up</h3><p>The intersection of AI and environmental sustainability presents both profound opportunities and significant challenges. While AI holds the potential to drive transformative solutions in energy optimization, emissions monitoring, and climate forecasting, its own environmental impact cannot be overlooked. The rapid expansion of AI technologies, particularly in the realm of large-scale models, has raised concerns about resource consumption and its carbon footprint.</p><p>However, promising efforts are underway to address these concerns, with initiatives focused on measuring and reducing AI’s environmental impact. As we move forward, it is essential to balance the potential of AI with a conscious effort to ensure that its development aligns with <strong>sustainability goals</strong>. By leveraging AI responsibly and innovatively, we can accelerate climate action and build systems that serve people, businesses and the planet.</p><p>The convergence of <strong>climate urgency</strong> and <strong>technological maturity</strong> presents a unique window of opportunity for tech professionals to make a meaningful impact. McKinsey projects that Climate Tech investments could surpass $2 trillion by 2030, indicating long-term opportunity and career growth in this space [19].</p><p>For tech professionals seeking purpose-driven careers, working in Climate Tech offers the chance to see a tangible, positive impact on the world. Solving climate problems can be deeply fulfilling and motivating, providing a sense of purpose beyond user engagement or ad clicks. For hiring managers, attracting AI talent into Climate Tech can significantly boost a startup’s capabilities, enabling them to outpace others in efficiency and innovation.</p><h3>Sources</h3><ol><li><strong>World Economic Forum</strong> — <em>Global Risks Report 2025</em></li><li><strong>DeepMind Blog</strong> — <em>AI reduces Google data center cooling bill by 40%</em></li><li><strong>Google Research</strong> — <em>Data Center Cooling Optimization Using Machine Learning</em></li><li><strong>Pachama</strong> — <em>Carbon Credit Verification with AI</em></li><li><strong>Asian Scientist</strong> — <em>New AI Model Detects Methane Emissions from Space More Accurately</em></li><li><strong>Net0 Blog</strong> — <em>How AI Transforms Data Collection in Carbon Management</em></li><li><strong>IMARC Group</strong> — <em>Weather Forecasting Services Market Report</em></li><li><strong>DeepMind</strong> — <em>GenCast: AI Forecasts Weather and Extreme Conditions</em></li><li><strong>Google Blog</strong> — <em>Global Flood Forecasting with AI</em></li><li><strong>University of Miami</strong> — <em>AI in Hurricane Forecasting</em></li><li><strong>Stanford Sustainability</strong> — <em>AI Predicts Earth’s Peak Warming</em></li><li><strong>PwC</strong> — <em>State of Climate Tech 2024 Report</em></li><li><strong>arXiv</strong> — <em>Generative AI’s Water Consumption Estimates</em></li><li><strong>Polytechnique Insights</strong> — <em>Generative AI’s Energy Consumption Soars</em></li><li><strong>UNEP</strong> — <em>AI Has an Environmental Problem — Here’s What the World Can Do</em></li><li><strong>IEA (International Energy Agency)</strong> — <em>Electricity 2024: Analysis and Forecast to 2026</em></li><li><strong>Ministry of Ecological Transition</strong> — <em>Coalition for Environmentally Sustainable AI</em></li><li><strong>Salesforce</strong> — <em>AI Energy Score Launch Announcement</em></li><li><strong>McKinsey &amp; Company</strong> — <em>What Would It Take to Scale Critical Climate Technologies?</em></li></ol><blockquote>PS: If you want to consult the ressources referenced here. Checkout the uncensored version of the article <a href="https://www.notion.so/vianmixt/AI-Environmental-Paradox-1f1af60d977880b7adf0d5bfa8b776f8">here</a>.</blockquote><p><em>If you’ve made it this far, thank you — you’re exactly the kind of curious, thoughtful reader I write for</em>.<em><br>I am Vianney, a software engineer working in Tech. I share my thoughts, research and </em><a href="https://github.com/VianneyMI"><em>open-source projects</em></a><em> on </em><a href="https://medium.com/@vianney.mixtur_39698"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/vianney-mixtur-pro/"><em>LinkedIn</em></a><em>. Connect with me if you want curated, authentic and practical insights.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ee89e64372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[France in the AI Race: A Thriving Ecosystem Challenging the US and China]]></title>
            <link>https://aiadvances.org/france-in-the-ai-race-a-thriving-ecosystem-challenging-the-us-and-china-e4b6096b80ab?source=rss-a4e4eaffe65------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b6096b80ab</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[market-research-reports]]></category>
            <dc:creator><![CDATA[Vianney Mixtur]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 13:26:07 GMT</pubDate>
            <atom:updated>2025-02-27T13:26:07.499Z</atom:updated>
            <content:encoded><![CDATA[<p><em>All my articles published here are free.</em></p><p>As a French engineer, I’ve always felt a mix of admiration and disappointment watching the U.S. dominate the digital world with the Big Tech giants like Google, Facebook, Amazon, Apple, and Microsoft, while France had no equivalent Big Tech company.</p><p>Like the rest of Europe, France missed out on the technological revolutions that defined the past 50 years. The Internet, Mobile, and Cloud Computing revolutions did not spark in Europe. However, it looks different this time. A new wave of disruption and innovation is underway, and France isn’t lagging behind, <strong>it’s fully taking part of the AI race</strong> and is strategically positioned to lead.</p><h4>So what’s different this time ?</h4><p>In this article, I’ll explore <strong>why France is making waves in AI</strong>, <strong>the key players driving this momentum, and how the country is standing in the global tech landscape</strong>. From emerging startups to government initiatives, we’ll take a closer look at the factors that are fueling this shift and whether France can sustain its momentum and compete with the likes of the US and China.</p><figure><img alt="Knowledge worker making research on the AI market through multiples monitors. The Eiffel tower is visible through the office window." src="https://cdn-images-1.medium.com/max/1024/0*fKvYp1oHWBu03hgx" /><figcaption>Image generated with Dall-E by author</figcaption></figure><h3>French AI Ecosystem Overview</h3><p>There are three main reasons behind France’s current success in AI.<br>First, France has built a dynamic tech ecosystem over the last decade. Second, the AI revolution is deeply rooted in mathematics, a field where France has always excelled. Third, unlike in past technological revolutions, France was already well-positioned at the start of the AI boom and reacted quickly to the catalyst event that was the launch of ChatGPT in November 2022.</p><p>In this section, I will break down the key pillars of France’s AI ecosystem, its world class education system and research institutions, leading AI pioneers, groundbreaking companies, and rising startups, highlighting how they contribute to making France a leader in AI.</p><h4>World-Class Institutions</h4><p>One of France’s greatest advantages in AI stems from its world-class education and research institutions. Schools and institutions like École Polytechnique, ENS, CNRS, and INRIA have cultivated a generation of elite AI researchers, who have significantly contributed to global advancements.</p><ul><li><a href="https://www.polytechnique.edu/en/school/presentation-ecole-polytechnique"><strong>Ecole Polytechnique</strong></a><strong> : </strong>Founded in 1794, it is one of the most prestigious engineering school in France. It ranks 6th worldwide, with its proportion of Nobel laureate alumni related to its total number of graduates.</li><li><a href="https://www.ens.psl.eu/en/ens/ens-today"><strong>Ecole Normale Supérieure</strong></a><strong> </strong>: Also founded in 1794, its the representation of French mathematical excellence and is a very important institution in the AI landscape. Particularly through its <a href="https://www.master-mva.com/"><em>Mathématiques, Vision, Apprentissage</em> (MVA) master progam</a>.</li><li><a href="https://www.cnrs.fr/en"><strong>CNRS</strong></a><strong> : </strong>Established in 1939, CNRS is France’s largest governmental research organization. It regularly ranks in the top 5 research institutions worldwide.</li><li><a href="https://www.inria.fr/en"><strong>INRIA</strong></a><strong> : </strong>Created in 1967, INRIA is dedicated to computer science and applied mathematics. It helped developed the ocaml programming language, has strongly contributed to machine learning and regularly publishes high-impact papers in major AI conferences like NeurIPS, ICML and CVPR (19 in 2024).</li></ul><h4>World-Class AI Experts and Scientists</h4><p>The above institutions and many others have produced some of the most influential minds in AI.</p><ul><li><a href="https://www.linkedin.com/in/cournapeau-david-76782410/"><strong>David Cournapeau</strong></a> and <a href="https://gael-varoquaux.info/"><strong>Gael Varoquaux</strong></a> : Co-creators of <a href="https://github.com/scikit-learn/scikit-learn">Scikit-Learn</a>, one of the most used (80 million monthly download) open-source machine learning library and mandatory step for every data scientist in the world.</li><li><a href="https://en.wikipedia.org/wiki/Fran%C3%A7ois_Chollet"><strong>François Chollet</strong></a><strong> </strong>: Former Google engineer, he is known to be the creator of the Keras deep learning library. More recently, he launched the ARC-AGI prize, a $1,000,000+ public competition and a leading benchmark for assessing <strong>A</strong>I <strong>G</strong>eneral <strong>I</strong>ntelligence.</li><li><a href="https://en.wikipedia.org/wiki/Arthur_Mensch"><strong>Arthur Mensch</strong></a><strong>, </strong><a href="https://www.crunchbase.com/person/timothee-lacroix"><strong>Timothée Lacroix</strong></a><strong> </strong>and <a href="https://www.linkedin.com/in/guillaume-lample-7821095b/"><strong>Guillaume Lample</strong></a><strong> : </strong>Co-founders of Mistal AI, they previously help key research roles at DeepMind and Meta with Guillaume being among the researchers behind the original LLaMa models.</li><li><a href="http://yann.lecun.com/"><strong>Yann Lecun</strong></a><strong> </strong>: Chief AI Scientist at Meta, he is widely regarded as one of the father of modern AI with several foundational publications in the eighties and nineties.</li></ul><p>Also the broader pool of worldclass scientist further confirms French Academic Excellence. Thus, <a href="https://en.wikipedia.org/wiki/C%C3%A9dric_Villani"><strong>Cedric Villani</strong></a>, mathematician and 2010 Fields Medal has authored an influential report on France’s AI strategy, helping shape national policies on AI research and development. France is a a true powerhouse in mathematics, with the second-most Fields Medals (14 winners), just behind the US.<br>While not directly involved in AI, <a href="https://www.cnrs.fr/en/person/alain-aspect"><strong>Alain Aspect</strong></a>, 2022 Physics Nobel Prize has founded <a href="https://www.pasqal.com/fr/">Pasqal</a>, a quantum computing startup that could lead to significant improvements in AI algorithms in the future.</p><h4>Established Companies</h4><p>France’s strength isn’t just limited to academic excellence and pioneering scientists. Unlike in the previous technological shifts and where France struggled to translate research and development (R&amp;D) into valuable products and companies, this time the academic foundations have produced companies that are shaping the future of AI across enterprise solutions, digital analytics and deep learning platforms and AI infrastructure.</p><ul><li><a href="https://www.dataiku.com/company/"><strong>Dataiku</strong></a> : Founded by <a href="https://www.linkedin.com/in/fdouetteau/?originalSubdomain=uk">Florian Douetteau</a> in 2013, Dataiku develops a platform enabling enterprises to build and deploy AI models. It was recognized as a leader in Gartner’s 2024 Magic Quadrant for Data Science and Machine Learning Platforms. It has raised over <strong>$432 million</strong>, with a latest valuation of <strong>$3.7 billion </strong>in 2022.</li><li><a href="https://contentsquare.com/company/#who-we-are"><strong>Contentsquare</strong></a> : Founded by <a href="https://www.linkedin.com/in/jonathancherki/?locale=en_US">Jonathan Cherki</a> in 2012, ContentSquare’s platform provides AI-powered digital experience analytics, helping companies optimize user engagement, conversion rates, and accessibility. Backed by investors like SoftBank and BlackRock, ContentSquare has raised over <strong>$1.4 billion </strong>and was valued at $5.6 billion in 2022.</li><li><a href="https://huggingface.co/"><strong>HuggingFace</strong></a><strong> </strong>: Founded by <a href="https://www.linkedin.com/in/clementdelangue/">Clément Delangue</a>, <a href="https://www.linkedin.com/in/julienchaumond">Julien Chaumond</a> and <a href="https://thomwolf.io/">Thomas Wolf</a> in 2016, HuggingFace has become the GitHub of data scientists, AI researchers and engineers providing the <strong>world’s largest repository for</strong> <strong>open-source machine learning models, datasets, and libraries</strong>. It is the leading platform for natural language processing (NLP) and transformer-based AI models, powering AI development at companies like Meta, Google, and Microsoft. Hugging Face was valued at <strong>$4.5 billion </strong>in 2023<strong> </strong>and is heavily involved in promoting <strong>open-source AI</strong>.</li><li><a href="https://mistral.ai/en"><strong>MistralAI</strong></a><strong> </strong>: Founded in 2023, Mistral has become a symbol for France and Europe’s AI ambitions by developing <strong>Large Language Models (LLMs)</strong> that rival its American competitors <strong>OpenAI and Anthropic</strong>.<br>It has raised a total of approximately $1.27 billion and his current valued at <strong>$6 billion</strong>.</li></ul><p>Those unicorns show how France is turning research into real successes. In 2025 a growing number of startups are following their path.</p><h4>The Next Big Thing : Startups to watch</h4><p>According to the latest data, France has approximately <strong>750 AI startups</strong> in 2025. There are undoubtedly some hidden gems in this list that represent attractive ventures for investors and business opportunities for entrepreneurs. I am going to highlight some startups that are probably going to make the headlines in the next couple of months.</p><ul><li><a href="https://www.giskard.ai/"><strong>Giskard</strong></a><strong> </strong>: Founded in 2021 by <a href="https://www.linkedin.com/in/alexcombessi">Alex Combessie</a> &amp; <a href="https://www.jeanmarie-johnmathews.com/">Jean-Marie John-Mathews</a>, Giskard’s platform ensures the quality, security and compliance of AI models. Giskard has raised approximately $5 million and was valued at $10 million in 2022.</li><li><a href="https://www.heex.io/"><strong>Heex</strong></a><strong> </strong>: Founded in 2019 by <a href="https://fr.linkedin.com/in/brunomendesdasilva">Bruno Mendes Da Silva</a> and <a href="https://www.researchgate.net/profile/Arnaud-De-La-Fortelle-2">Arnaud de La Fortelle</a>, Heex develops smart data extraction and other solutions for autonomous vehicles, smart cities and industry 4.0. They have raised a total of $10 million across rounds in 2022 and 2024.</li><li><a href="https://www.bioptimus.com/"><strong>Bioptimus</strong></a><strong> </strong>: Founded in 2024 by a team of ex-Google DeepMind and <a href="https://www.owkin.com/">Owkin</a> scientists, Bioptimus operates at the intersection of AI and computational biology. Their research is expected to lead to breakthrough in disease prediction, drug discovery and genetic analysis. They have recently raised $76 million in seed funding.</li><li><a href="https://dust.tt/"><strong>Dust</strong></a> : Founded in 2023 by <a href="https://fr.linkedin.com/in/gabhubert">Gabriel Hubert</a> and <a href="https://github.com/spolu">Stanislas Polu</a> (ex-OpenAI), they aim at accelerating organizations with AI by creating AI Agents and an AI operating system. They have raised a Series A of $15 million in 2024.</li></ul><p>On a personal standpoint, I am very bullish on Dust, because like them I believe more needs to be done in the application layer for AI.</p><blockquote>Large Language Models are not self-sufficient</blockquote><p>There are many more startups that I could have included in the above list among which AnotherBrain, LightOn, Prophesee, Kyutai and Poolside.</p><h4>Foreign companies investing in France</h4><p><a href="https://www.poolside.ai/"><strong>Poolside</strong></a> is an interesting transition to this part of the article. Poolside develops LLMs specialized in coding and aim at competing with the likes of Cursor, Devin and Github Copilot. Poolside is another strong indicator of the dynamism of the french AI ecosystem as it’s originally an American company that has relocated its HQ in Paris in 2023. This is probably a first in recent history. It shows that France attractivity has improved and reinforces the significance of France in AI.</p><p>Outside of this wild example, several foreign companies have invested in the french AI ecosytem over the past decade:</p><ul><li><strong>Facebook/Meta</strong> : In 2015, they opened the FAIR Lab in Paris. The original LLaMa model came out of this lab.</li><li><strong>Google</strong> : In 2018, Google inaugurated a research center in Paris imitating Meta. In February 2024, they expanded their presence.</li><li><strong>Samsung</strong> : Also in 2018, Samsung launched its third global AI research center in France, after those in South Korea and the United States.</li><li><strong>Microsoft</strong> : In 2023, as a result of the 7th edition of Choose France summit, Microsoft announced a €4B plan to develop cloud infrastructure, upskill 1M people and support startups like MistralAI.</li><li><strong>OpenAI</strong> : Last year (2024), OpenAI opened its first european office outside of the UK. Unlike the other companies, this office is focused on commercial operations and public relations rather than research.</li><li><strong>Notable VCs : </strong>Andreessen Horowitz led Mistral AI’s €385M Series A in December 2023, valuing the company at €2 billion. Eric Schmidt, former Google CEO, participated in Mistral AI’s initial €105M seed round in June 2023, alongside Lightspeed Venture Partners and Xavier Niel.</li></ul><p>These investments not only highlight France’s growing appeal as an AI hub but also illustrate a powerful feedback loop — Meta’s FAIR Lab in Paris produced LLaMa, which later inspired former employees to launch Mistral AI, now backed by major VCs. This cycle of talent, research, and investment continues to strengthen France’s position in the global AI race.</p><blockquote>What are the french AI startups to watch in 2025 ? <br>Are there any prominent actor that I am missing ?</blockquote><blockquote>=&gt; Please let me know your thoughts in the <strong>comments.</strong></blockquote><h3>The challenges and the competition</h3><p>While the ecosystem is growing and self reinforcing, it faces several obstacles and a stiff competition.</p><h4>Competing Against Well-Funded Giants</h4><p>The french AI startups are competing against companies that have access to immense resources and partnerships. OpenAI alone received a $10 billion investment from Microsoft.<br>As of now, AI development relies on GPU power, primarily supplied by NVIDIA.</p><h4>Heritage</h4><p>France and Europe are paying their previous misses, they lack the infrastructure and compute limitations because of their lack of cloud actors like Microsoft Azure, AWS and Google Cloud.</p><h4>Regulatory and Policy Risks</h4><p>The EU AI Act imposes stricter compliance requirements that could slow down european startups like Mistral, Aleph Alpha and Helsing as it increases uncertainty, complexity and costs.</p><p>China’s DeepSeek exemplifies how regulatory flexibility accelerates AI innovation. DeepSeek recent success with their launch of the R1 model has been allowed (among other factors) by the looser data privacy laws they are subject to.</p><h4><strong>Scalability and Monetization Challenges</strong></h4><p>HuggingFace, Mistral, Dust all have adopted an open-source strategy.<br>However, monetizing open-source AI remains a complex challenge.</p><p>In contrast, American firms like OpenAI and Anthropic are more aggressive in terms of commercialization.</p><p>Thus, as of early 2025, the revenue trajectories of leading AI companies highlight a significant disparity between U.S. and French firms in terms of monetization strategies and financial outcomes. From the latest estimation Mistral generated $32 million of annual recurring revenue in 2024 when Anthropic generated $875 million and OpenAI $3.7 billion.</p><h3>Conclusion</h3><p>France has positioned itself as a formidable player in the global AI race. The numbers tell a compelling story. <strong>France ranks third in Europe for VC investment, with $6 billion raised in 2024</strong>, and it leads in AI funding. The French government’s <strong>€2.2 billion</strong> AI investment strategy and initiatives like the <a href="https://www.elysee.fr/en/emmanuel-macron/2024/05/13/7th-edition-of-the-choose-france-summit"><strong>Choose France Summit</strong></a> and the more recent <a href="https://www.euronews.com/next/2025/02/11/heres-what-has-been-announced-at-the-ai-action-summit"><strong>AI Action Summit</strong></a> have made Paris a key destination for global AI firms.</p><p>Yet, challenges remain. <strong>Compute infrastructure, regulatory hurdles, and scale-up capital</strong> are areas where France still lags behind its biggest competitors.</p><p>For <strong>VCs and investors</strong>, now is the time to double down on the French AI ecosystem before valuations skyrocket. For <strong>entrepreneurs</strong>, France offers a fertile ground to build AI-driven businesses, supported by a deep talent pool and increasing access to capital. And for <strong>policymakers</strong>, sustaining this momentum will require bold initiatives that match the ambition of France’s AI pioneers.</p><p><em>I’ve done a lot of research for this article. You can find below a small subset of the sources that I used.<br>By the way, I am Vianney, a software engineer working in Tech. I share my toughts, research and </em><a href="https://github.com/VianneyMI"><em>open-source projects</em></a><em> on </em><a href="https://medium.com/@vianney.mixtur_39698"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/vianney-mixtur-pro/"><em>LinkedIn</em></a><em>. Connect with me if you want some curated, authentic and practical insights.</em></p><h3>Some of my sources</h3><ol><li><a href="https://www.nature.com/nature-index/news/ten-global-institutions-universities-twenty-nineteen-annual-tables">https://www.nature.com/nature-index/news/ten-global-institutions-universities-twenty-nineteen-annual-tables</a></li><li><a href="https://azure.microsoft.com/fr-fr/blog/microsoft-is-a-leader-in-the-2024-gartner-magic-quadrant-for-data-science-and-machine-learning-platforms/">https://azure.microsoft.com/fr-fr/blog/microsoft-is-a-leader-in-the-2024-gartner-magic-quadrant-for-data-science-and-machine-learning-platforms/</a></li><li><a href="https://growjo.com/company/Mistral_AI">https://growjo.com/company/Mistral_AI</a></li><li><a href="https://techcrunch.com/2025/02/04/european-ai-startups-raised-8-billion-in-2024/">https://techcrunch.com/2025/02/04/european-ai-startups-raised-8-billion-in-2024/</a></li><li><a href="https://alexandre.substack.com/p/the-state-of-the-french-tech-ecosystem">https://alexandre.substack.com/p/the-state-of-the-french-tech-ecosystem</a></li><li><a href="https://aiindex.stanford.edu/report/">https://aiindex.stanford.edu/report/</a></li><li><a href="https://dealroom.co/reports">https://dealroom.co/reports</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b6096b80ab" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/france-in-the-ai-race-a-thriving-ecosystem-challenging-the-us-and-china-e4b6096b80ab">France in the AI Race: A Thriving Ecosystem Challenging the US and China</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Data into Solutions: Building a Smart App with Python and AI]]></title>
            <link>https://medium.com/data-science/transforming-data-into-solutions-building-a-smart-app-with-python-and-ai-c258be3b1fc2?source=rss-a4e4eaffe65------2</link>
            <guid isPermaLink="false">https://medium.com/p/c258be3b1fc2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[foodtech]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Vianney Mixtur]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 11:01:47 GMT</pubDate>
            <atom:updated>2025-01-03T10:51:10.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Some financial analysts worry that artificial intelligence may not justify the massive investments being made in the field. While I understand their concerns, I see things differently. I’m neither an AI Boomer nor an AI Doomer — I believe AI has the potential to drive innovation, enhance productivity, and deliver measurable business outcomes.</p><p>In my last article, I explored how Large Language Models (LLMs) can be used to structure unstructured data. This time, I want to go a step further: demonstrating how the outcome of structuring data with LLMs can serve as the <strong>foundation for building intelligent applications</strong>. Thus showing how to integrate AI in a bigger picture.</p><p>In this article, I’ll share how I used a modern stack to fast-track the development and deployment of Baker — a smart app which is the result of transforming a raw recipes dataset into an easy to use solution. This journey highlights more than just technical implementation; it showcases how AI can address practical challenges and deliver tangible value in real-world scenarios.</p><h3>Baker: Your Cooking Muse</h3><p>In <a href="https://towardsdatascience.com/the-lesser-known-rising-application-of-llms-775834116477"><strong>The (lesser-known) rising application of LLMs</strong></a>, I mentioned that I needed a recipes dataset to work on a personal project. Now, it’s time to reveal that project.</p><figure><img alt="A photo showing a woman following a recipe on both a book and a tablet" src="https://cdn-images-1.medium.com/max/1024/0*a5KBQ814jdQYPYZ8" /><figcaption>Photo by <a href="https://unsplash.com/@webfactoryltd?utm_source=medium&amp;utm_medium=referral">WebFactory Ltd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Managing food has always been a challenge for me. I struggle to find inspiration for meals, and as a result, I often let ingredients go to waste — something I’ve wanted to change for a long time. That’s why I set out to create a recipe recommender system that helps me (and others) use up ingredients before they go stale. The solution? <strong>Baker</strong>, my prototype for tackling this issue. This project reflects my passion for leveraging AI to tackle everyday challenges like <strong>food waste</strong>.</p><p>Baker is an open-source web application in its early stages, built almost entirely in Python. The app takes a list of ingredients and their quantities — mimicking what you might find in your fridge and pantry — and suggests recipes you can prepare using those ingredients. It’s designed to simplify meal preparation while encouraging smarter, more sustainable food choices. You can try the app yourself here:</p><p>⇒ <a href="https://mixit-baker.streamlit.app/">mixit-baker.streamlit.app</a></p><p>However, you might want to read the remaining of the article first. In one of the <a href="#e4df">next sections</a> , I’ll walk you through a demo of the application.</p><h3>From Idea to POC: Accelerated Development with AI and Modern Tools</h3><p>After the initial parsing of the dataset, I became busy with other duties and set this side project aside for months 😉. But technology evolves quickly. When I finally returned to it, a series of newer models, techniques, and tools had emerged or matured, providing an opportunity to revisit and enhance the project.</p><h4><strong>Revisiting Data Extraction with GPT-4o</strong></h4><p>The first step was to revisit my earlier work on data extraction and <a href="https://github.com/VianneyMI/baker/pull/10">update the results</a>. In my previous iteration, I had used <strong>MistralAI’s open-mixtral-8x7b</strong>, which had since been deprecated. This time, I switched to the newer and more advanced <strong>GPT-4o</strong>, and the results were remarkable.</p><p>To put the improvement into perspective:</p><ul><li>In the earlier run, the LLM failed to parse 89 recipes due to inconsistencies in JSON generation.</li><li>With GPT-4o, all 360 recipes in the dataset were parsed successfully, achieving <strong>a 100% success rate</strong>.</li></ul><p>This milestone reflects how quickly AI capabilities improve. Just months ago, LLMs often struggled to output valid JSON reliably. This iteration demonstrated not only better results but also how adopting newer tools can yield substantial gains.</p><h4><strong>Post-Processing Challenges</strong></h4><p>Even with improved extraction, the raw data required significant post-processing. Recipes featured inconsistent units — grams, teaspoons, cups, and more — making comparisons and recommendations challenging. To address this, I adopted a systematic approach:</p><ol><li><strong>Standardization:</strong> I defined a restricted set of units (e.g., grams for weight, milliliters for volume).</li><li><strong>Mapping and Conversion:</strong> All original units were mapped to this subset, with quantities adjusted accordingly.</li></ol><p>This normalization step was essential for enabling accurate ingredient filtering and powering the recipe recommendation engine. It also underscored a critical point: AI outputs must be contextually meaningful for their intended application, not just technically correct.</p><h4><strong>Building the Engine and Web Application</strong></h4><p>With the data cleaned, standardized, and ready for use, the next step was to start leveraging the data which I did by <a href="https://github.com/VianneyMI/baker/pull/18">building the engine logic and wrapping it in a web app</a>.</p><h4><strong>Quick Prototyping</strong></h4><p>Throughout Baker’s development, I embraced a quick prototyping philosophy. The goal was less building an app from day one but rather to explore tools and techniques, test ideas and gather feedback.</p><p><strong>From Notebooks to a POC app:</strong></p><p>The way I built my data pipeline and the web app using AI illustrate the quick prototyping philosophy.</p><ul><li><strong>The Data Pipeline:</strong> The entire pipeline for extraction and post-processing resides in Jupyter notebooks. While this setup is “minimal yet functional” compared to a full-fledged ETL pipeline, it provided the speed and flexibility to iterate quickly. Initially, I thought of it as a one-time process, but I’m now planning to <a href="https://github.com/VianneyMI/baker/issues/22">transform it</a> into something more robust and repeatible.</li><li><strong>The Web App:</strong> The web app leverages <a href="https://fastapi.tiangolo.com/"><strong>FastAPI</strong></a> for the backend and <a href="https://streamlit.io/"><strong>Streamlit</strong></a> for the frontend. These frameworks are accessible, developer-friendly, and perfect for rapidly prototyping interactive applications.</li><li><strong>Accelerated Development with AI:</strong> The frontend was generated entirely using <a href="https://www.cursor.com/"><strong>Cursor</strong></a>, an AI-powered development tool. While I had heard of Cursor before, this project allowed me to fully explore its potential. The experience was so enjoyable that I plan to write a dedicated article about it.</li></ul><p>By adopting this approach, I was able to build a working MVP in days rather than weeks or months.</p><p><strong>Open-Source:</strong></p><p>A marker of <strong>Baker</strong> is its <strong>open-source nature</strong>. By sharing the project on GitHub, I hope to:</p><ul><li><strong>Encourage Collaboration:</strong> Enable others to contribute new features, enhance the codebase, or extend the application with additional datasets.</li><li><strong>Inspire Learning:</strong> Provide a practical resource for those curious about leveraging LLMs, structuring unstructured data, or building recommendation systems.</li></ul><p>Open-sourcing makes it easier for others to reproduce results, contribute improvements, and exchange ideas. Collaboration not only strengthens <strong>Baker</strong> but also fosters collective innovation.</p><p><strong>Free Deployment: Accessible and Lightweight</strong></p><p>To make <strong>Baker</strong> accessible, I deployed it using free-tier services:</p><ul><li><a href="https://streamlit.io/cloud"><strong>Streamlit Cloud</strong></a>: Powers the frontend, delivering an intuitive and interactive user experience.</li><li><a href="https://www.koyeb.com/docs"><strong>Koyeb</strong></a>: Supports backend processing and API calls without incurring hosting costs.</li></ul><p>These platforms allowed me to deploy quickly and experiment without the financial or technical barriers of traditional hosting solutions. This deployment strategy highlights how modern tools make it possible to turn creative ideas into accessible applications at little to no cost.</p><h3><strong>Behind the Scenes: The Technology Powering Baker</strong></h3><p>In this section, I’ll share some implementation details of Baker. Again it is open-source so I invite my technical readers to go check the code on GitHub. Some readers might want to jump to the <a href="#e4df">next section</a>.</p><p>The application is minimalist with a simple 3 tier architecture and is built almost entirely in Python.</p><figure><img alt="An architecture diagram of the Baker application" src="https://cdn-images-1.medium.com/max/848/1*Wb8bqb8ClDw7DDrYlQO3JQ.png" /><figcaption>Photo by author</figcaption></figure><p>It is made of the following components:</p><ol><li><strong>Frontend</strong>: A <strong>Streamlit</strong> interface provides an intuitive platform for users to interact with the system, query recipes, and receive recommendations.</li><li><strong>Backend</strong>: Built with <strong>FastAPI</strong>, the backend serves as the interface for handling user queries and delivering recommendations.</li><li><strong>Engine</strong>: The engine contains the core logic for finding and filtering recipes, leveraging <a href="https://vianneymi.github.io/monggregate/"><strong>monggregate</strong></a> as a query builder.</li><li><strong>Database</strong>: The recipes are stored in a <a href="https://www.mongodb.com/"><strong>MongoDB</strong></a> database that processes the aggregation pipelines generated by the engine.</li></ol><h4>Backend Setup</h4><p>The backend is initialized in app.py, where FastAPI endpoints are defined. For instance:</p><pre>from fastapi import FastAPI<br>from baker.engine.core import find_recipes<br>from baker.models.ingredient import Ingredient<br><br>app = FastAPI()<br>@app.get(&quot;/&quot;)<br>def welcome():<br>    return {&quot;message&quot;: &quot;Welcome to the Baker API!&quot;}<br>@app.post(&quot;/recipes&quot;)<br>def _find_recipes(ingredients: list[Ingredient], serving_size: int = 1) -&gt; list[dict]:<br>    return find_recipes(ingredients, serving_size)</pre><p>The /recipes endpoint accepts a list of ingredients and a serving size then delegates the processing to the engine.</p><h4>Recipe Engine Logic</h4><p>The heart of the application resides in core.py within the engine directory. It manages database connections and query pipelines. Below is an example of the find_recipes function:</p><pre># Imports and the get_recipes_collection function are not included<br><br>def find_recipes(ingredients, serving_size=1):<br>    # Get the recipes collection<br>    recipes = get_recipes_collection()<br><br>    # Create the pipeline<br>    pipeline = Pipeline()<br>    pipeline = include_normalization_steps(pipeline, serving_size)<br>    query = generate_match_query(ingredients, serving_size)<br>    print(query)<br>    pipeline.match(query=query).project(<br>        include=[<br>            &quot;id&quot;,<br>            &quot;title&quot;,<br>            &quot;preparation_time&quot;,<br>            &quot;cooking_time&quot;,<br>            &quot;original_serving_size&quot;,<br>            &quot;serving_size&quot;,<br>            &quot;ingredients&quot;,<br>            &quot;steps&quot;,<br>        ],<br>        exclude=&quot;_id&quot;,<br>    )<br><br>    # Find the recipes<br>    result = recipes.aggregate(pipeline.export()).to_list(length=None)<br><br>    return result<br>    <br>def generate_match_query(ingredients: list[Ingredient], serving_size: int = 1) -&gt; dict:<br>    &quot;&quot;&quot;Generate the match query.&quot;&quot;&quot;<br><br>    operands = []<br>    for ingredient in ingredients:<br>        operand = {<br>            &quot;ingredients.name&quot;: ingredient.name,<br>            &quot;ingredients.unit&quot;: ingredient.unit,<br>            &quot;ingredients.quantity&quot;: {&quot;$lte&quot;: ingredient.quantity / serving_size},<br>        }<br>        operands.append(operand)<br><br>    query = {&quot;$and&quot;: operands}<br><br>    return query<br><br><br>def include_normalization_steps(pipeline: Pipeline, serving_size: int = 1):<br>    &quot;&quot;&quot;Adds steps in a pipeline to normalize the ingredients quantity in the db<br><br>    The steps below normalize the quantities of the ingredients in the recipes in the DB by the recipe serving size.<br><br>    &quot;&quot;&quot;<br><br>    # Unwind the ingredients<br>    pipeline.unwind(path=&quot;$ingredients&quot;)<br><br>    pipeline.add_fields({&quot;original_serving_size&quot;: &quot;$serving_size&quot;})<br>    # Add the normalized quantity<br>    pipeline.add_fields(<br>        {<br>            # &quot;orignal_serving_size&quot;: &quot;$serving_size&quot;,<br>            &quot;serving_size&quot;: serving_size,<br>            &quot;ingredients.quantity&quot;: S.multiply(<br>                S.field(&quot;ingredients.quantity&quot;),<br>                S.divide(serving_size, S.max([S.field(&quot;serving_size&quot;), 1])),<br>            ),<br>        }<br>    )<br><br>    # Group the results<br>    pipeline.group(<br>        by=&quot;_id&quot;,<br>        query={<br>            &quot;id&quot;: {&quot;$first&quot;: &quot;$id&quot;},<br>            &quot;title&quot;: {&quot;$first&quot;: &quot;$title&quot;},<br>            &quot;original_serving_size&quot;: {&quot;$first&quot;: &quot;$original_serving_size&quot;},<br>            &quot;serving_size&quot;: {&quot;$first&quot;: &quot;$serving_size&quot;},<br>            &quot;preparation_time&quot;: {&quot;$first&quot;: &quot;$preparation_time&quot;},<br>            &quot;cooking_time&quot;: {&quot;$first&quot;: &quot;$cooking_time&quot;},<br>            # &quot;directions_source_text&quot;: {&quot;$first&quot;: &quot;$directions_source_text&quot;},<br>            &quot;ingredients&quot;: {&quot;$addToSet&quot;: &quot;$ingredients&quot;},<br>            &quot;steps&quot;: {&quot;$first&quot;: &quot;$steps&quot;},<br>        },<br>    )<br>    return pipeline</pre><p>The core logic of <strong>Baker</strong> resides in the find_recipes function.</p><p>This function creates a MongoDB aggregation pipeline thanks to monggregate. This aggregation pipeline includes several steps.</p><p>The first steps are generated by the include_normalization_steps function that is going to dynamically update the quantities of the ingredients in the database to ensure we are comparing apples to apples. This is done by updating the ingredients quantities in the database to the user desired serving.</p><p>Then the actual matching logic is created by the generate_match_query function. Here we ensure, that the recipes don’t require more than what the user have for the ingredients concerned.</p><p>Finally a projection filters out the fields that we don’t need to return.</p><h3>User Guide: Discovering Recipes with Baker in a Few Clicks</h3><p><strong>Baker</strong> helps you discover a better fate for your ingredients by finding recipes that match what you already have at home.</p><p>The app features a simple form-based interface. Enter the ingredients you have, specify their quantities, and select the unit of measurement from the available options.</p><figure><img alt="A screenshot showing the Baker interface to enter ingredients" src="https://cdn-images-1.medium.com/max/887/1*NOR7Ivr0WvTTIq3fuKsClg.png" /><figcaption>Photo by author</figcaption></figure><p>In the example above, I’m searching for a recipe for <strong>two servings</strong> to use up 4 tomatoes and 2 carrots that have been sitting in my kitchen for a bit too long.</p><p><strong>Baker</strong> found two recipes! Clicking on a recipe lets you view the full details.</p><figure><img alt="A screenshot of the Baker interface showing how recipes are displayed" src="https://cdn-images-1.medium.com/max/855/1*tb_d9HrGgftSmTzcKvnYZw.png" /><figcaption>Photo by author</figcaption></figure><p><strong>Baker</strong> adapts the quantities in the recipe to match the serving size you’ve set. For example, if you adjust the serving size from two to four people, the app recalculates the ingredient quantities accordingly.</p><p>Updating the serving size may also change the recipes that appear. <strong>Baker</strong> ensures that the suggested recipes match not only the serving size but also the ingredients and quantities you have on hand. For instance, if you only have 4 tomatoes and 2 carrots for two people, <strong>Baker</strong> will avoid recommending recipes that require 4 tomatoes and 4 carrots.</p><h3>The Road Ahead: Scaling Baker for Broader Impact</h3><p>Baker is a side project developed quickly and pragmatically, a functional prototype rather than a production-ready application.</p><p>However, I’d love to see it grow into something more impactful.</p><p>There are several areas where the app can expand, both in functionality and sophistication. To move forward, let’s address its current limitations and explore possible enhancements.</p><h3>1 — Growing the Recipe Database</h3><p>Baker’s recipes originate from <a href="https://publicdomainrecipes.com/">Public Domain Recipes</a>, an open-source database of recipes. While this is an amazing project, the number of available recipes is limited. As a result, <strong>Baker</strong> only knows 360 recipes for now. To put this into perspective, some dedicated recipe websites claim to have tens of thousands recipes.</p><p>To scale, I’ll need to identify additional data sources for recipes.</p><h3>2 — Improving the Data Ingestion Pipeline</h3><p>At the moment, <strong>data ingestion</strong> is handled through Jupyter Notebooks. One of the main technical priorities is to transform these notebooks into robust Python scripts, integrate them into an admin section of <strong>Baker</strong>, or even spin them off into a dedicated app.</p><p>Additionally, I am convinced that there’s room for improving the parsing process performed by the LLMs to ensure greater consistency and accuracy.</p><h3>3 — Adding Semantic Search &amp; Flexibility</h3><p>Currently, recipes are searched by ingredient names through exact string matching. For example, searching for “tomato” will not retrieve recipes that mention “tomatoes.” This can be addressed by <a href="https://vianmixt.notion.site/Practical-Semantic-Search-with-MongoDB-and-OpenAI-451692801b41465fae1bea5f70238279">implementing a semantic search approach using vector databases</a>. With <strong>semantic search</strong>, variations of ingredient names — whether due to pluralization, regional differences, or translation — can be dynamically mapped to the same concept.</p><p>Moreover, semantic search would allow users to search in their native language, further broadening accessibility.</p><p>I also want to introduce <strong>greater flexibility in the search functionality</strong>. For example, if a user searches for recipes with tomatoes, carrots, and bananas but no such combination exists in the database, the search should still return recipes with subsets of the entered ingredients (e.g., tomatoes and carrots, tomatoes and bananas, or carrots and bananas).</p><p>From a feature standpoint, this is my top priority.</p><h3>Other Enhancements to Consider</h3><p>While the above are the main focus areas, there are plenty of other topics I’d like to address:</p><ul><li>UI enhancements</li><li>Sorting and ranking of recipes</li><li>Improved error handling and robustness</li><li>Adopting software engineering best practices</li><li>Performance optimization</li></ul><h3>Conclusion</h3><p>I hope you’ve enjoyed reading this journey of turning ideas into reality. If you did, <a href="https://buymeacoffee.com/vianmixt">consider supporting me on Buy Me a Coffee</a> to help fund future developments. Now, let’s summarize the key takeaways.</p><p>A few months ago, I wrote an article about how <strong>using LLMs for data structuration and extraction</strong> was a promising use case powered by the new Generative AI wave. In this follow-up, I’ve taken the concept further by demonstrating a tangible outcome: using a LLM-generated dataset to power a data-centric smart app, <strong>Baker</strong>.</p><p>Along the way, I aimed to show how this process has become more accessible with modern tools like <strong>Streamlit, FastAPI, Streamlit Cloud, Koyeb, and Cursor.</strong> If you want a deep dive on the tools I used, let me know in the comments.</p><p>These tools provide the flexibility and accessibility needed to focus on solving real problems rather than being overwhelmed by the complexity of managing multiple aspects — data pipelines, backend logic, frontend interfaces, CI/CD workflows, cloud deployments, testing, and the intricacies of various programming languages.</p><p>But this project isn’t just about recipes — it’s about unlocking the potential of unstructured data to solve real-world problems. For instance, the same approach used in <strong>Baker</strong> could be applied to create a personalized learning platform. By structuring educational content, such as lecture transcripts or articles, into accessible formats and building a recommendation engine, one could help users discover relevant learning materials based on their goals or interests.</p><p>Whether for education, product recommendations, or knowledge management, the principles and tools I’ve shared here can inspire countless applications.</p><p>As we step into the new year, I encourage you to reflect on your own untapped datasets and ideas. What could you build with the tools and knowledge shared here? With small steps, quick iterations, and a collaborative mindset, you, too, can create <strong>innovative solutions</strong> that make a difference.</p><p>Here’s to building a smarter, more data-driven future — together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c258be3b1fc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transforming-data-into-solutions-building-a-smart-app-with-python-and-ai-c258be3b1fc2">Transforming Data into Solutions: Building a Smart App with Python and AI</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The (lesser known) rising application of LLMs]]></title>
            <link>https://medium.com/data-science/the-lesser-known-rising-application-of-llms-775834116477?source=rss-a4e4eaffe65------2</link>
            <guid isPermaLink="false">https://medium.com/p/775834116477</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Vianney Mixtur]]></dc:creator>
            <pubDate>Mon, 13 May 2024 16:01:45 GMT</pubDate>
            <atom:updated>2024-05-17T08:10:09.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p><strong>Large Language Models</strong> (LLMs) are often described as <strong>Generative Artificial Intelligence</strong> (GenAI) as they indeed have the ability to generate text. The first popular application of LLMs were chatbots with ChatGPT leading the way. Then we extended their horizon to other tasks such as <a href="https://vianmixt.notion.site/Practical-Semantic-Search-with-MongoDB-and-OpenAI-451692801b41465fae1bea5f70238279"><strong>semantic search</strong></a> and <strong>retrieval augmented generation</strong>(RAG). Today, I want to talk about a rising application for LLM which is <strong>structuring unstructed data</strong> for which I am going to show you an example by structuring raw texts into JSON data.</p><p>Using LLMs for <strong>data structuration and extraction</strong> is a very promising application with a lot of potential. Here’s why:</p><ul><li><strong>Improved accuracy :</strong> LLMs understand the nuances of human language. This allows them to identify key information within messy, unstructured text with greater accuracy than traditional rule-based systems</li><li><strong>Automation potential</strong> : Extracting information from unstructured data can be a time-consuming and laborious task. LLMs can automate this process, freeing up human resources for other tasks and allowing for faster analysis of larger datasets.</li><li><strong>Adaptability and learning capabilities</strong>: LLMs, on the other hand, can be continuously fine-tuned and adapted to handle new data sources and information types. As they are exposed to more unstructured data, they can learn and improve their ability to identify patterns and extract relevant information.</li><li><strong>Business outcome :</strong> A vast amount of valuable information resides within unstructured textual data sources like emails, customer reviews, social media conversations, and internal documents. However, this data is often difficult to analyze. LLMs can unlock this hidden potential by transforming unstructured data into a structured format. This allows businesses to leverage powerful analytics tools to identify trends, and gain insights. Essentially, by structuring unstructured data with LLMs, businesses can transform a liability (unusable data) into an asset (valuable insights) that drives better decision-making and improves overall business outcomes.</li></ul><h3>An example</h3><p>Recently, I was searching for an open-source recipes dataset for a personal project but I could not find any except for <a href="https://github.com/ronaldlong46/public-domain-recipes">this github repository</a> containing the recipes displayed on <a href="https://publicdomainrecipes.com/">publicdomainrecipes.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nP7oGyWBMxZ0xkvO" /><figcaption>Photo by <a href="https://unsplash.com/@ugmonk?utm_source=medium&amp;utm_medium=referral">Jeff Sheldon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unfortunately, I needed a dataset that was more exploitable, i.e something closer to <strong>tabular data</strong> or to a <strong>NoSQL document</strong>. That’s how I thought about finding a way to transform the raw data into something more suitable to my needs, without spending hours, days and weeks doing it manually.</p><p>Let me show you how I used the power of Large Language Models to automate the process of converting the raw text into structured documents.</p><h4>Dataset</h4><p>The original dataset is a collection of markdown files. Each file representing a recipe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e78c841328793fe811b1cfafa7c62e17/href">https://medium.com/media/e78c841328793fe811b1cfafa7c62e17/href</a></iframe><p>As you can see, this is not completely unstructured, there are nice tabular metadata on top of the file, then there are 4 distincts sections:</p><ul><li>An introduction,</li><li>The list of ingredients</li><li>Directions</li><li>Some tips.</li></ul><p>Based on this observation, <a href="https://www.linkedin.com/in/sebastianbahr/">Sebastian Bahr</a>, developed a parser to transform the markdown files into JSON <a href="https://github.com/sebastianbahr/RecipeRecommender">here</a>.</p><p>The output of the parser is already more exploitable, besides Sebastian used it to <a href="https://towardsdatascience.com/build-a-recipe-recommender-chatbot-using-rag-and-hybrid-search-part-i-c4aa07d14dcf">build a recipe recommender chatbot</a>. However, there are still some drawbacks. The ingredients and directions keys contain raw texts that could be better structured. <br>As-is, some useful information is hidden. <br>For example, the quantities for the ingredients, the preparation or cooking time for each step.</p><h4>Code</h4><p>In the remainder of this article, I’ll show the steps that I undertook to get to JSON documents that look like the one below.</p><pre>{<br>    &quot;name&quot;: &quot;Crêpes&quot;,<br>    &quot;serving_size&quot;: 4,<br>    &quot;ingredients&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;name&quot;: &quot;white flour&quot;,<br>            &quot;quantity&quot;: 300.0,<br>            &quot;unit&quot;: &quot;g&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;name&quot;: &quot;eggs&quot;,<br>            &quot;quantity&quot;: 3.0,<br>            &quot;unit&quot;: &quot;unit&quot;<br>        },<br>        {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;milk&quot;,<br>            &quot;quantity&quot;: 60.0,<br>            &quot;unit&quot;: &quot;cl&quot;<br>        },<br>        {<br>            &quot;id&quot;: 4,<br>            &quot;name&quot;: &quot;beer&quot;,<br>            &quot;quantity&quot;: 20.0,<br>            &quot;unit&quot;: &quot;cl&quot;<br>        },<br>        {<br>            &quot;id&quot;: 5,<br>            &quot;name&quot;: &quot;butter&quot;,<br>            &quot;quantity&quot;: 30.0,<br>            &quot;unit&quot;: &quot;g&quot;<br>        }<br>    ],<br>    &quot;steps&quot;: [<br>        {<br>            &quot;number&quot;: 1,<br>            &quot;description&quot;: &quot;Mix flour, eggs, and melted butter in a bowl.&quot;,<br>            &quot;preparation_time&quot;: null,<br>            &quot;cooking_time&quot;: null,<br>            &quot;used_ingredients&quot;: [1,2,5]<br>        },<br>        {<br>            &quot;number&quot;: 2,<br>            &quot;description&quot;: &quot;Slowly add milk and beer until the dough becomes fluid enough.&quot;,<br>            &quot;preparation_time&quot;: 5,<br>            &quot;cooking_time&quot;: null,<br>            &quot;used_ingredients&quot;: [3,4]<br>        },<br>        {<br>            &quot;number&quot;: 3,<br>            &quot;description&quot;: &quot;Let the dough rest for one hour.&quot;,<br>            &quot;preparation_time&quot;: 60,<br>            &quot;cooking_time&quot;: null,<br>            &quot;used_ingredients&quot;: []<br>        },<br>        {<br>            &quot;number&quot;: 4,<br>            &quot;description&quot;: &quot;Cook the crêpe in a flat pan, one ladle at a time.&quot;,<br>            &quot;preparation_time&quot;: 10,<br>            &quot;cooking_time&quot;: null,<br>            &quot;used_ingredients&quot;: []<br>        }<br>    ]<br>}</pre><p>The code to reproduce the tutorial is on GitHub <a href="https://github.com/VianneyMI/baker">here</a>.</p><p>I relied on two powerful libraries <a href="https://www.langchain.com/">langchain</a> for communicating with LLM providers and <a href="https://docs.pydantic.dev/latest/">pydantic</a> to format the output of the LLMs.</p><p>First, I defined the two main components of a recipe with the Ingredientand Stepclasses.</p><p>In each class, I defined the relevant attributes and provided a description of the field and examples. Those are then fed to the LLMs by langchain leading to better results.</p><pre>&quot;&quot;&quot;`schemas.py`&quot;&quot;&quot;<br><br>from pydantic import BaseModel, Field, field_validator<br><br>class Ingredient(BaseModel):<br>    &quot;&quot;&quot;Ingredient schema&quot;&quot;&quot;<br><br>    id: int = Field(<br>        description=&quot;Randomly generated unique identifier of the ingredient&quot;,<br>        examples=[1, 2, 3, 4, 5, 6],<br>    )<br>    name: str = Field(<br>        description=&quot;The name of the ingredient&quot;, <br>        examples=[&quot;flour&quot;, &quot;sugar&quot;, &quot;salt&quot;]<br>    )<br>    quantity: float | None = Field(<br>        None,<br>        description=&quot;The quantity of the ingredient&quot;,<br>        examples=[200, 4, 0.5, 1, 1, 1],<br>    )<br>    unit: str | None = Field(<br>        None,<br>        description=&quot;The unit in which the quantity is specified&quot;,<br>        examples=[&quot;ml&quot;, &quot;unit&quot;, &quot;l&quot;, &quot;unit&quot;, &quot;teaspoon&quot;, &quot;tablespoon&quot;],<br>    )<br><br>    @field_validator(&quot;quantity&quot;, mode=&quot;before&quot;)<br>    def parse_quantity(cls, value: float | int | str | None):<br>        &quot;&quot;&quot;Converts the quantity to a float if it is not already one&quot;&quot;&quot;<br><br>        if isinstance(value, str):<br>            try:<br>                value = float(value)<br>            except ValueError:<br>                try:<br>                    value = eval(value)<br>                except Exception as e:<br>                    print(e)<br>                    pass<br><br>        return value<br><br><br>class Step(BaseModel):<br>    number: int | None = Field(<br>        None,<br>        description=&quot;The position of the step in the recipe&quot;,<br>        examples=[1, 2, 3, 4, 5, 6],<br>    )<br>    description: str = Field(<br>        description=&quot;The action that needs to be performed during that step&quot;,<br>        examples=[<br>            &quot;Preheat the oven to 180°C&quot;,<br>            &quot;Mix the flour and sugar in a bowl&quot;,<br>            &quot;Add the eggs and mix well&quot;,<br>            &quot;Pour the batter into a greased cake tin&quot;,<br>            &quot;Bake for 30 minutes&quot;,<br>            &quot;Let the cake cool down before serving&quot;,<br>        ],<br>    )<br>    preparation_time: int | None = Field(<br>        None,<br>        description=&quot;The preparation time mentioned in the step description if any.&quot;,<br>        examples=[5, 10, 15, 20, 25, 30],<br>    )<br>    cooking_time: int | None = Field(<br>        None,<br>        description=&quot;The cooking time mentioned in the step description if any.&quot;,<br>        examples=[5, 10, 15, 20, 25, 30],<br>    )<br>    used_ingredients: list[int] = Field(<br>        [],<br>        description=&quot;The list of ingredient ids used in the step&quot;,<br>        examples=[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]],<br>    )<br><br><br>class Recipe(BaseModel):<br>    &quot;&quot;&quot;Recipe schema&quot;&quot;&quot;<br><br>    name: str = Field(<br>        description=&quot;The name of the recipe&quot;,<br>        examples=[<br>            &quot;Chocolate Cake&quot;,<br>            &quot;Apple Pie&quot;,<br>            &quot;Pasta Carbonara&quot;,<br>            &quot;Pumpkin Soup&quot;,<br>            &quot;Chili con Carne&quot;,<br>        ],<br>    )<br>    serving_size: int | None = Field(<br>        None,<br>        description=&quot;The number of servings the recipe makes&quot;,<br>        examples=[1, 2, 4, 6, 8, 10],<br>    )<br>    ingredients: list[Ingredient] = []<br>    steps: list[Step] = []<br>    total_preparation_time: int | None = Field(<br>        None,<br>        description=&quot;The total preparation time for the recipe&quot;,<br>        examples=[5, 10, 15, 20, 25, 30],<br>    )<br>    total_cooking_time: int | None = Field(<br>        None,<br>        description=&quot;The total cooking time for the recipe&quot;,<br>        examples=[5, 10, 15, 20, 25, 30],<br>    )<br>    comments: list[str] = []</pre><p><strong>Technical Details</strong></p><ul><li>It is important to not have a model which is too strict here otherwise, the pydantic validation of the JSON outputted by the LLM will fail. A good way to give some flexibility is too provide default values like None or empty lists [] depending on the targeted output type.</li><li>Note the field_validatoron the quantityattribute of the Ingredient , is there to help the engine parse quantities. It was not initially there but by doing some trials, I found out that the LLM was often providing quantities as strings such as 1/3or 1/2 .</li><li>The used_ingredientsallow to formally link the ingredients to the relevant steps of the recipes.</li></ul><p>The model of the output being defined the rest of the process is pretty smooth.</p><p>In a prompt.pyfile, I defined a create_promptfunction to easily generate prompts. A “new” prompt is generated for every recipe. All prompts have the same basis but the recipe itself is passed as a variable to the base prompt to create a new one.</p><pre>&quot;&quot;&quot; `prompt.py`<br><br>The import statements and the create_prompt function have not been included <br>in this snippet.<br>&quot;&quot;&quot;<br># Note : Extra spaces have been included here for readability.<br><br>DEFAULT_BASE_PROMPT = &quot;&quot;&quot;<br>What are the ingredients and their associated quantities <br>as well as the steps to make the recipe described <br>by the following {ingredients} and {steps} provided as raw text ?<br><br>In particular, please provide the following information:<br>- The name of the recipe<br>- The serving size<br>- The ingredients and their associated quantities<br>- The steps to make the recipe and in particular, the duration of each step<br>- The total duration of the recipe broken <br>down into preparation, cooking and waiting time. <br>The totals must be consistent with the sum of the durations of the steps. <br>- Any additional comments<br><br>{format_instructions}<br>Make sure to provide a valid and well-formatted JSON.<br><br>&quot;&quot;&quot;</pre><p>The communication with the LLM logic was defined in therunfunction of thecore.pyfile, that I won’t show here for brevity.</p><p>Finally, I combined all those components in mydemo.ipynbnotebook whose content is shown below.</p><pre># demo.ipynb<br>import os<br>from pathlib import Path<br><br>import pandas as pd<br>from langchain.output_parsers import PydanticOutputParser<br>from langchain_mistralai.chat_models import ChatMistralAI<br>from dotenv import load_dotenv<br><br>from core import run<br>from prompt import DEFAULT_BASE_PROMPT, create_prompt<br>from schemas import Recipe<br> # End of first cell<br><br># Setup environment<br>load_dotenv()<br>MISTRAL_API_KEY = os.getenv(&quot;MISTRAL_API_KEY&quot;) #1<br> # End of second cell<br> <br># Load the data<br>path_to_data = Path(os.getcwd()) / &quot;data&quot; / &quot;input&quot; #2<br>df = pd.read_json(&quot;data/input/recipes_v1.json&quot;)<br>df.head()<br> # End of third cell<br><br># Preparing the components of the system<br>llm = ChatMistralAI(api_key=MISTRAL_API_KEY, model_name=&quot;open-mixtral-8x7b&quot;)<br>parser = PydanticOutputParser(pydantic_object=Recipe)<br>prompt = create_prompt(<br>    DEFAULT_BASE_PROMPT, <br>    parser, <br>    df[&quot;ingredients&quot;][0], <br>    df[&quot;direction&quot;][0]<br>)<br>#prompt  <br>  # End of fourth cell<br><br># Combining the components  <br>example = await run(llm, prompt, parser)<br>#example<br> # End of fifth cell</pre><p>I used <a href="https://mistral.ai/">MistralAI</a> as a LLM provider, with their open-mixtral-8x7bmodel which is a very good open-source alternative to <a href="https://openai.com/">OpenAI</a>. langchainallows you to easily switch provider given you have created an account on the provider’s platform.</p><p>If you are trying to reproduce the results:</p><ul><li>(#1) — Make sure you have a MISTRAL_API_KEYin a .env file or in your OS environment.</li><li>(#2) — Be careful to the path to the data. If you clone my repo, this won’t be an issue.</li></ul><p>Running the code on the entire dataset cost less than 2€.<br>The structured dataset resulting from this code can be found <a href="https://github.com/VianneyMI/baker/blob/main/data/output/parsed_recipes_all_8x7b.json">here</a> in my repository.<br>I am happy with the results but I could still try to iterate on the prompt, my field descriptions or the model used to improve them. I might try MistralAI newer model, the open-mixtral-8x22b or try another LLM provider by simply changing 2 or 3 lines of code thanks to langchain .</p><p>When I am ready, I can get back to my original project. Stay tuned if you want to know what it was. In the meantime, let me know in the comments what would you do with the final dataset ?</p><h3>Conclusion</h3><p>Large Language Models (LLMs) offer a powerful tool for structuring unstructured data. Their ability to understand and interpret human language nuances, automate laborious tasks, and adapt to evolving data make them an invaluable resource in data analysis. By unlocking the hidden potential within unstructured textual data, businesses can transform this data into valuable insights, driving better decision-making and business outcomes. The example provided, of transforming raw recipes data into a structured format, is just one of the countless possibilities that LLMs offer.</p><p>As we continue to explore and develop these models, we can expect to see many more innovative applications in the future. The journey of harnessing the full potential of LLMs is just beginning, and the road ahead promises to be an exciting one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775834116477" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-lesser-known-rising-application-of-llms-775834116477">The (lesser known) rising application of LLMs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB aggregation pipelines made easy with Monggregate]]></title>
            <link>https://blog.devgenius.io/mongo-db-aggregations-pipelines-made-easy-with-monggregate-680b322167d2?source=rss-a4e4eaffe65------2</link>
            <guid isPermaLink="false">https://medium.com/p/680b322167d2</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Vianney Mixtur]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 09:11:09 GMT</pubDate>
            <atom:updated>2023-01-18T21:32:38.708Z</atom:updated>
            <content:encoded><![CDATA[<p>Aggregation pipelines are the tool that allow the MongoDB database management system (DBMS) to <a href="https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922">really rival its SQL counterparts</a>.</p><figure><img alt="Diagram of an aggregation pipeline (https://stackoverflow.com/questions/12702080/mongodb-explain-for-aggregation-framework)" src="https://cdn-images-1.medium.com/max/665/1*5ZlDfUiM_uHPW6KwvszS_g.png" /><figcaption>Diagram of an aggregation pipeline — Image from <a href="https://stackoverflow.com/questions/12702080/mongodb-explain-for-aggregation-framework">https://stackoverflow.com/questions/12702080/mongodb-explain-for-aggregation-framework</a></figcaption></figure><p>However, there is a steep learning curve before being able to use them, especially for python developers as their syntax resembles disguised JavaScript.<br>Besides, with <em>pymongo</em>, which is the official MongoDB driver for python, there is only limited support for aggregation pipelines.</p><p>The<em> pymongo </em>library does<em> </em>expose an aggregate method but the pipeline argument that the method takes is just a list of complex nested dictionaries that quickly become quite long and overwhelming as shown in the following example taken from <a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto/#example">MongoDB official documentation</a>.</p><pre># Example of bucket_auto stage usage<br><br>db.artwork.aggregate( [<br>  {<br>    &quot;$facet&quot;: {<br>      &quot;price&quot;: [<br>        {<br>          &quot;$bucketAuto&quot;: {<br>            &quot;groupBy&quot;: &quot;$price&quot;,<br>            &quot;buckets&quot;: 4<br>          }<br>        }<br>      ],<br>      &quot;year&quot;: [<br>        {<br>          &quot;$bucketAuto&quot;: {<br>            &quot;groupBy&quot;: &quot;$year&quot;,<br>            &quot;buckets&quot;: 3,<br>             &quot;output&quot;: {<br>              &quot;count&quot;: { &quot;$sum&quot;: 1 },<br>              &quot;years&quot;: { &quot;$push&quot;: &quot;$year&quot; }<br>            }<br>          }<br>        }<br>      ],<br>      &quot;area&quot;: [<br>        {<br>          &quot;$bucketAuto&quot;: {<br>            &quot;groupBy&quot;: {<br>              &quot;$multiply&quot;: [ &quot;$dimensions.height&quot;, &quot;$dimensions.width&quot; ]<br>            },<br>            &quot;buckets&quot;: 4,<br>            &quot;output&quot;: {<br>              &quot;count&quot;: { &quot;$sum&quot;: 1 },<br>              &quot;titles&quot;: { &quot;$push&quot;: &quot;$title&quot; }<br>            }<br>          }<br>        }<br>      ]<br>    }<br>  }<br>] )</pre><h3>Here comes Monggregate !</h3><p>In order to improve the experience writing MongoDB aggregation pipelines, I wrote a library offering a more pythonic syntax.</p><p>The source code is available on <a href="https://github.com/VianneyMI/monggregate">GitHub</a> and the library is available on PyPI so you can install it with the command below:</p><pre>pip install monggregate</pre><p>In order to demonstrate the capabilities of the library, I am going to reuse the examples from this <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-aggregation/#getting-started">amazing tutorial</a> by Mark Smith.<br>In this tutorial, Mark first shows how you can use aggregation pipelines to perform queries that you can naturally do with the MongoDB Query Language (MQL). Then comes the most interesting parts where he shows how to perform joins and actual aggregations. Next, we will focus on those examples and see how do they translate to <em>monggregate</em> syntax.</p><p>The tutorial uses the <strong>sample_mflix </strong>dataset and requires at least python 3.6. You can refer to <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-crud/">this article</a> to setup your environnment to reproduce the examples below.</p><p>However, as of now, <em>monggregate</em> is only available for python 3.10 . <br>It should not be to hard to change the code to make it compatible with earlier python versions. The main 3.10 feature that I am using in <em>monggregate</em> is the ability to do things like:</p><pre>from pydantic import BaseModel<br><br>class Post(BaseModel):<br>    author : str<br>    comments : list[str]</pre><p>rather than:</p><pre>from typing import List<br>from pydantic import BaseModel<br><br>class Post(BaseModel):<br>    author : str<br>    comments : List[str]</pre><p>Since the library started as a side project, it was also an opportunity for me to try python 3.10 . Therefore, if you feel that the library could be useful to you in earlier python versions, feel free to either :</p><ul><li><a href="https://github.com/VianneyMI/monggregate/issues">Raise an issue</a></li><li><a href="https://github.com/VianneyMI/monggregate/pulls">Create a pull request</a></li><li><a href="https://github.com/VianneyMI/monggregate/fork">Fork the project</a></li></ul><p>Now we are going to show <em>monggregate</em> in action. The code samples below can also be found in a Jupyter Notebook and a python script <a href="https://github.com/VianneyMI/doc_monggregate">here on GitHub</a>.</p><h4>Example #1a : Look Up Related Data in Other Collections</h4><p>With <em>monggregate</em> making a join between the movies and comments collections of the sample_mflix database is as simple as:</p><pre># Preparing the pipeline<br>pipeline = Pipeline(collection=&quot;movies&quot;)<br>pipeline.lookup(<br>    right = &quot;comments&quot;, # collection to join<br>    left_on = &quot;_id&quot;, <br>    right_on = &quot;movie_id&quot;,<br>    name = &quot;related_comments&quot; # name of the field that will contain the matching documents<br>).limit(5)<br><br># Executing the pipeline<br>results = movie_collection.aggregate(pipeline())</pre><p>compared to :</p><pre># Look up related documents in the &#39;comments&#39; collection:<br>stage_lookup_comments = {<br>   &quot;$lookup&quot;: {<br>         &quot;from&quot;: &quot;comments&quot;, <br>         &quot;localField&quot;: &quot;_id&quot;, <br>         &quot;foreignField&quot;: &quot;movie_id&quot;, <br>         &quot;as&quot;: &quot;related_comments&quot;,<br>   }<br>}<br><br># Limit to the first 5 documents:<br>stage_limit_5 = { &quot;$limit&quot;: 5 }<br><br>pipeline = [<br>   stage_lookup_comments,<br>   stage_limit_5,<br>]<br><br>results = movie_collection.aggregate(pipeline)</pre><p>Here, the original pipeline is stil relatively simple so the added value is not clear. Let’s add a bit more complexity.</p><h4>Example #1b : Conditional lookup (constraining the query above)</h4><p>In the article it is proposed to filter out movies without a minimum of two comments. It is straightforward to do with <em>monggregate</em>:</p><pre><br>pipeline = Pipeline(collection=&quot;movies&quot;)<br>pipeline.lookup(<br>    right = &quot;comments&quot;,<br>    left_on = &quot;_id&quot;,<br>    right_on = &quot;movie_id&quot;,<br>    name = &quot;related_comments&quot;<br>).add_fields(<br>    comment_count = {<br>        &quot;$size&quot; : &quot;$related_comments&quot;<br>    }<br>).match(<br>    comment_count = {<br>        &quot;$gt&quot;:2<br>    }<br>).limit(5)</pre><p>compared to :</p><pre># Look up related documents in the &#39;comments&#39; collection:<br>    stage_lookup_comments = {<br>        &quot;$lookup&quot;: {<br>            &quot;from&quot;: &quot;comments&quot;, <br>            &quot;localField&quot;: &quot;_id&quot;, <br>            &quot;foreignField&quot;: &quot;movie_id&quot;, <br>            &quot;as&quot;: &quot;related_comments&quot;<br>        }<br>    }<br><br>    # Calculate the number of comments for each movie:<br>    stage_add_comment_count = {<br>        &quot;$addFields&quot;: {<br>            &quot;comment_count&quot;: {<br>                &quot;$size&quot;: &quot;$related_comments&quot;<br>            }<br>        } <br>    }<br><br>    # Match movie documents with more than 2 comments:<br>    stage_match_with_comments = {<br>        &quot;$match&quot;: {<br>            &quot;comment_count&quot;: {<br>                &quot;$gt&quot;: 2<br>            }<br>        } <br>    }<br>    # Limit to the first 5 documents:<br>    limit_5 = { &quot;$limit&quot;: 5 }<br><br>    # Optional limit to 1000 documents.<br>    # Run at the start of the pipeline, to speed things up during development:<br>    limit_1000 = { &quot;$limit&quot;: 1000 }<br><br>    pipeline = [<br>        # Uncomment the line below to run on 1000 documents instead of<br>        # the full collection, for speed:<br>        #<br>        # limit_1000,<br>        stage_lookup_comments,<br>        stage_add_comment_count,<br>        stage_match_with_comments,<br>        limit_5,<br>    ]</pre><h4>Example 2: Grouping documents</h4><p>In this example, we will finally understand the “aggregation” in “aggregation framework” by showing how to group documents.</p><p>Let’s see how many movies have been released each year:</p><pre><br>pipeline = Pipeline(collection=&quot;movies&quot;)<br>pipeline.match(<br>    year = {<br>        &quot;$type&quot; : &quot;number&quot;<br>    }<br>).group(<br>    by = &quot;year&quot;,<br>    query = {<br>        &quot;movie_count&quot; : {&quot;$sum&quot;:1},<br>        &quot;movie_titles&quot; : {&quot;$push&quot;:&quot;$title&quot;}<br>    }<br>).sort(<br>    by = &quot;_id&quot;, # year has in a way been renamed _id in the previous stage ...<br>                # this is a feature of MongoDb itself and it isn&#39;t something done by monggregate directly.<br>    descending = True<br>)</pre><p>compared to:</p><pre><br> stage_group_year = {<br>        &quot;$group&quot;: {<br>            &quot;_id&quot;: &quot;$year&quot;,<br>            &quot;movie_count&quot;: { &quot;$sum&quot;: 1 },<br>            &quot;movie_titles&quot;: { &quot;$push&quot;: &quot;$title&quot; },<br>        }<br>    }<br><br>    # Match a year-summary document where the year  (stored as `_id`) <br>    stage_match_years = {<br>        &quot;$match&quot;: {<br>            &quot;year&quot;: {<br>                &quot;$type&quot;: &quot;number&quot;,<br>            }<br>        }<br>    }<br>    <br>    # Sort year-summary documents by &#39;_id&#39;<br>    # (which is the year the document summarizes):<br>    stage_sort_year_ascending = {<br>        &quot;$sort&quot;: {&quot;_id&quot;: pymongo.ASCENDING}<br>    }<br><br>    pipeline = [<br>        stage_match_years,<br>        stage_group_year,<br>        stage_sort_year_ascending,<br>    ]</pre><p>Note that the step to filter out non-numeric years is present in the original article as the movies collection has documents with non-numeric years.</p><p>In SQL, the grouping would give something along the lines:</p><pre>SELECT COUNT(_id) AS movies_count, CONCAT(title, &#39;, &#39;) AS movie_titles<br>FROM movies<br>GROUP BY year</pre><p>The filter on year type most likely would not be necessary as SQL would not allow for rows to break the data model of the movies table in the first place.<br>In other words, there would not have been rows with non-numeric years.</p><h3>Conclusions and Next Steps</h3><p><em>monggregate </em>eases the process of building aggregation pipelines in python. <br>As it is shown in the examples above, it divides by two the number of lines required to perform a query. <br>It offers a syntax similar to what one may have experienced with other popular data science tools, languages and libraries such as MATLAB, SQL or <em>pandas</em>.</p><p>The library is open-source and is a work in progress, not all the stages are covered by an object-oriented programming (OOP) interface. Besides, in the examples above, there are multiple raw queries remaining and what is in my view, undesirable $ signs floating around. In order, to get rid of those, it is necessary to write interfaces for MongoDB <a href="https://www.mongodb.com/docs/manual/meta/aggregation-quick-reference/#operator-expressions">operators</a> as well. This endeavour has been initiated but was not included in this article and may be the topic of a follow-up article. Like for the stages, not all operators are covered by interfaces. <br>Yet the goal is to reach 100% of coverage this year.</p><p>Another interesting topic, would be to compare the performances between the two following approaches :</p><ul><li>querying all necessary documents from the database server, and then processing them on the backend using <em>pandas.</em></li><li>querying and processing them directly in the database server using the aggregation framework and <em>monggregate</em>.</li></ul><h3>References</h3><ul><li><a href="https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922">https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922</a></li><li><a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto/#example">https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto/#example</a></li><li><a href="https://www.mongodb.com/developer/languages/python/python-quickstart-aggregation/">https://www.mongodb.com/developer/languages/python/python-quickstart-aggregation/</a></li><li><a href="https://www.mongodb.com/developer/languages/python/python-quickstart-crud/">https://www.mongodb.com/developer/languages/python/python-quickstart-crud/</a></li><li><a href="https://www.mongodb.com/docs/manual/meta/aggregation-quick-reference/#operator-expressions">https://www.mongodb.com/docs/manual/meta/aggregation-quick-reference/#operator-expressions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=680b322167d2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mongo-db-aggregations-pipelines-made-easy-with-monggregate-680b322167d2">MongoDB aggregation pipelines made easy with Monggregate</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>