<?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 Hanish on Medium]]></title>
        <description><![CDATA[Stories by Hanish on Medium]]></description>
        <link>https://medium.com/@sarahanish9?source=rss-8c3aa7313282------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JebkeunJE8o-7SmQ</url>
            <title>Stories by Hanish on Medium</title>
            <link>https://medium.com/@sarahanish9?source=rss-8c3aa7313282------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:44:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarahanish9/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[Replacing Logos in Videos with Streamlit and OpenCV]]></title>
            <link>https://medium.com/@sarahanish9/replacing-logos-in-videos-with-streamlit-and-opencv-650cf84a623f?source=rss-8c3aa7313282------2</link>
            <guid isPermaLink="false">https://medium.com/p/650cf84a623f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[logo-replacement]]></category>
            <dc:creator><![CDATA[Hanish]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 07:14:09 GMT</pubDate>
            <atom:updated>2024-06-05T07:14:09.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSkuPlrIIsbmh0J6FgKNEg.png" /></figure><p>In this blog post, we’ll explore how to replace logos in a video using OpenCV and Streamlit. This task involves detecting a logo in each frame of a video and replacing it with another video. The tutorial will guide you through the implementation step by step, using Python.</p><p><strong>Prerequisites</strong></p><p>Before we begin, ensure you have the following installed:</p><ul><li>Python 3.x</li><li>OpenCV</li><li>Streamlit</li><li>NumPy</li><li>Tqdm</li></ul><p>You can install the required libraries using pip:</p><pre>pip install opencv-python-headless streamlit numpy tqdm</pre><h3>Overview</h3><p>Our goal is to create a Streamlit application that allows users to upload an input video, a logo image to be replaced, and a replacement video. The application will process the input video frame by frame, detect the specified logo, and replace it with the corresponding frame from the replacement video.</p><h3>Step-by-Step Implementation</h3><h3>1. Setting Up Streamlit</h3><p>Streamlit makes it easy to create web applications for machine learning and data science projects. We’ll use it to build a user interface for our application.</p><p>Create a new Python file (e.g., app.py) and start by importing the necessary libraries:</p><pre>import streamlit as st<br>import cv2<br>import numpy as np<br>from tqdm import tqdm<br>import tempfile<br></pre><h3>2. Video Logo Replacement Function</h3><p>We need a function that processes the video, detects the logo in each frame, and replaces it with the replacement video. Here’s the complete function:</p><pre>def replace_logo_with_video(input_video_path, output_video_path, old_logo_path, replacement_video_path):<br>    cap_main = cv2.VideoCapture(input_video_path)<br>    cap_replacement = cv2.VideoCapture(replacement_video_path)<br>    if not cap_main.isOpened() or not cap_replacement.isOpened():<br>        st.error(&quot;Error: Could not open video(s).&quot;)<br>        return<br><br>    old_logo = cv2.imread(old_logo_path)<br>    if old_logo is None:<br>        st.error(&quot;Error: Could not load logo image.&quot;)<br>        return<br><br>    frame_width = int(cap_main.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(cap_main.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    fps = cap_main.get(cv2.CAP_PROP_FPS)<br>    total_frames_main = int(cap_main.get(cv2.CAP_PROP_FRAME_COUNT))<br>    total_frames_replacement = int(cap_replacement.get(cv2.CAP_PROP_FRAME_COUNT))<br><br>    fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>    out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))<br><br>    sift = cv2.SIFT_create()<br>    kp_old, des_old = sift.detectAndCompute(old_logo, None)<br><br>    FLANN_INDEX_KDTREE = 1<br>    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)<br>    search_params = dict(checks=50)<br>    flann = cv2.FlannBasedMatcher(index_params, search_params)<br><br>    frame_idx = 0<br>    with tqdm(total=total_frames_main, desc=&quot;Processing video frames&quot;) as pbar:<br>        while True:<br>            ret_main, frame_main = cap_main.read()<br>            ret_replacement, frame_replacement = cap_replacement.read()<br><br>            if not ret_main or (frame_idx &gt;= total_frames_replacement):<br>                break<br><br>            if not ret_replacement:<br>                cap_replacement.set(cv2.CAP_PROP_POS_FRAMES, 0)<br>                ret_replacement, frame_replacement = cap_replacement.read()<br><br>            kp_frame, des_frame = sift.detectAndCompute(frame_main, None)<br><br>            matches = flann.knnMatch(des_old, des_frame, k=2)<br>            good_matches = []<br>            for m, n in matches:<br>                if m.distance &lt; 0.7 * n.distance:<br>                    good_matches.append(m)<br><br>            if len(good_matches) &gt; 10:<br>                src_pts = np.float32([kp_old[m.queryIdx].pt for m in good_matches]).reshape(-1, 2)<br>                dst_pts = np.float32([kp_frame[m.trainIdx].pt for m in good_matches]).reshape(-1, 2)<br><br>                M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)<br>                if M is not None:<br>                    h, w = old_logo.shape[:2]<br>                    pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2)<br>                    dst = cv2.perspectiveTransform(pts, M)<br><br>                    dst = np.int32(dst)<br><br>                    x, y, w, h = cv2.boundingRect(dst)<br>                    frame_replacement_resized = cv2.resize(frame_replacement, (w, h))<br><br>                    mask_new_video = np.zeros((frame_height, frame_width), dtype=np.uint8)<br>                    cv2.fillConvexPoly(mask_new_video, dst, 255)<br><br>                    frame_roi = frame_main[y:y+h, x:x+w]<br>                    if frame_roi.shape[:2] == frame_replacement_resized.shape[:2]:<br>                        frame_main[y:y+h, x:x+w] = frame_replacement_resized<br>                    else:<br>                        st.warning(f&quot;Skipped frame due to size mismatch. Frame ROI shape: {frame_roi.shape}, Replacement video frame shape: {frame_replacement_resized.shape}&quot;)<br><br>            out.write(frame_main)<br>            frame_idx += 1<br>            pbar.update(1)<br><br>    cap_main.release()<br>    cap_replacement.release()<br>    out.release()<br>    cv2.destroyAllWindows()</pre><h3>3. Building the Streamlit Interface</h3><p>Next, we need to build the Streamlit interface to allow users to upload their videos and logo images.</p><pre># Streamlit UI<br>st.title(&quot;Video Logo Replacement with Video&quot;)<br>input_video = st.file_uploader(&quot;Upload Input Video&quot;, type=[&quot;mp4&quot;, &quot;mov&quot;, &quot;avi&quot;])<br>old_logo = st.file_uploader(&quot;Upload Old Logo Image&quot;, type=[&quot;png&quot;, &quot;jpg&quot;, &quot;jpeg&quot;])<br>replacement_video = st.file_uploader(&quot;Upload Replacement Video&quot;, type=[&quot;mp4&quot;, &quot;mov&quot;, &quot;avi&quot;])<br><br>if st.button(&quot;Replace Logo with Video&quot;):<br>    if input_video and old_logo and replacement_video:<br>        with tempfile.NamedTemporaryFile(delete=False) as temp_input_video:<br>            temp_input_video.write(input_video.read())<br>            input_video_path = temp_input_video.name<br><br>        with tempfile.NamedTemporaryFile(delete=False) as temp_old_logo:<br>            temp_old_logo.write(old_logo.read())<br>            old_logo_path = temp_old_logo.name<br><br>        with tempfile.NamedTemporaryFile(delete=False) as temp_replacement_video:<br>            temp_replacement_video.write(replacement_video.read())<br>            replacement_video_path = temp_replacement_video.name<br><br>        output_video_path = &quot;output_video_with_video.mp4&quot;<br>        replace_logo_with_video(input_video_path, output_video_path, old_logo_path, replacement_video_path)<br>        st.video(output_video_path)</pre><h3>4. Running the Application</h3><p>To run the application, simply execute the following command in your terminal:</p><pre>streamlit run app.py</pre><p>This will launch a local web server and open your default web browser to display the application.</p><h3>Conclusion</h3><p>In this tutorial, we built a Streamlit application that allows users to replace a logo in a video with another video using OpenCV. The key steps involved detecting the logo using feature matching, computing the homography to find the logo’s position, and replacing it with frames from the replacement video.</p><p>This project demonstrates the power of OpenCV for computer vision tasks and Streamlit for creating interactive web applications. You can extend this project further by adding more features such as adjusting the transparency of the replacement video or allowing multiple logo replacements in a single video.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650cf84a623f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Art and Ethics of Face Swapping: Deepfakes and Reality Manipulation]]></title>
            <link>https://medium.com/@sarahanish9/exploring-the-art-and-ethics-of-face-swapping-deepfakes-and-reality-manipulation-a47457bd9abf?source=rss-8c3aa7313282------2</link>
            <guid isPermaLink="false">https://medium.com/p/a47457bd9abf</guid>
            <category><![CDATA[face-swap]]></category>
            <category><![CDATA[deepfakes]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[roop]]></category>
            <dc:creator><![CDATA[Hanish]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 05:00:30 GMT</pubDate>
            <atom:updated>2023-08-16T05:00:30.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*x-w5YJMzG6WM0VEEzjAosw.jpeg" /></figure><p><strong>Introduction:</strong></p><p>In the ever-evolving landscape of technology, artificial intelligence has introduced us to numerous groundbreaking applications. One such innovation is the creation of deepfakes, a blend of “deep learning” and “fake,” which enables us to manipulate digital content, particularly faces, in unprecedented ways. This article delves into the captivating world of face swapping using deepfakes and ROOP (Reality Object Oriented Programming), exploring both the artistic possibilities and the ethical concerns that arise from these technologies.</p><p><strong>Unveiling the Magic of Deepfakes and ROOP:</strong></p><p>Deepfakes, powered by neural networks and machine learning algorithms, can convincingly replace one person’s face with another in videos or images. On the other hand, Reality Object Oriented Programming (ROOP) provides a powerful framework for creating interactive and immersive digital experiences that can alter reality in real-time. The fusion of these two technologies opens the door to a new realm of creative expression, enabling artists and developers to reimagine storytelling, entertainment, and even education.</p><p><strong>The Artistic Marvels of Face Swapping:</strong></p><p>Imagine a world where actors can effortlessly slip into historical roles or portray characters in ways previously deemed impossible. Deepfake and ROOP technologies offer artists the tools to transform performances, turning ordinary scenes into extraordinary spectacles. A filmmaker, for instance, can use these techniques to showcase an actor’s versatility by seamlessly swapping faces, thus providing an entirely fresh perspective on storytelling.</p><p><strong>Pushing the Boundaries of Reality:</strong></p><p>ROOP takes the concept of digital art to the next level by allowing users to actively participate in, modify, and reshape virtual environments. For instance, a gaming experience could become intensely immersive as players personalize their avatars with their own faces or those of their favorite celebrities. This interconnectedness between digital and real-world elements illustrates the potential of technology to redefine how we interact with our surroundings.</p><p><strong>The Ethical Quandaries:</strong></p><p>However, this brave new world is not without its ethical concerns. The ease with which deepfakes can be created has raised alarms about the potential misuse of this technology for malicious purposes, including spreading misinformation, identity theft, or compromising personal privacy. As artists and developers push the boundaries of creativity, society must grapple with the implications of blurring the lines between reality and digital fabrication.</p><p><strong>Navigating the Moral Compass:</strong></p><p>The responsible use of deepfakes and ROOP lies in the hands of creators, consumers, and policymakers alike. Implementing safeguards to ensure proper attribution, consent, and transparency becomes crucial to maintaining the integrity of digital content. Striking a balance between artistic freedom and ethical considerations will define how these technologies shape our future.</p><p><strong>Conclusion:</strong></p><p>The fusion of deepfakes and ROOP introduces a tantalizing tapestry of possibilities for artists, storytellers, and tech enthusiasts alike. This transformative potential, however, comes hand in hand with the responsibility to uphold ethical standards and safeguard against the misuse of these tools. As we continue to explore the creative landscape of face swapping using deepfakes and ROOP, it is imperative that we engage in thoughtful discourse and take deliberate steps toward a future where innovation coexists harmoniously with integrity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a47457bd9abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Interactive Virtual Dressing Room with OpenCV]]></title>
            <link>https://medium.com/@sarahanish9/creating-an-interactive-virtual-dressing-room-with-opencv-fc3d8630f82c?source=rss-8c3aa7313282------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3d8630f82c</guid>
            <category><![CDATA[pose-detection]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-dressing-room]]></category>
            <dc:creator><![CDATA[Hanish]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 14:27:17 GMT</pubDate>
            <atom:updated>2023-08-10T14:27:17.371Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Step-by-step guide to building an interactive virtual dressing room using Python and OpenCV</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*cmbqFt-JsUXpZyQ1ggn61w.jpeg" /></figure><h3>Introduction</h3><p>In today’s technology-driven world, innovation knows no bounds. Imagine being able to try on different outfits without ever changing clothes physically. With the power of computer vision and OpenCV, you can create an interactive virtual dressing room that overlays virtual shirts onto a person’s body in real-time using their webcam feed. In this tutorial, we’ll walk through the process of building such an application step by step.</p><h3>Getting Started</h3><p>To follow along with this tutorial, you’ll need to have Python and a few libraries installed on your system. If you haven’t already, install the required libraries using the following commands</p><pre>pip install opencv-python<br>pip install cvzone</pre><p>Once the libraries are installed, let’s dive into the code.</p><h3>Setting Up the Environment</h3><p>We’ll start by importing the necessary libraries and initializing the webcam feed for capturing video. We’ll also load the images of shirts that we want to overlay and create buttons for interacting with the application:</p><pre>import os<br>import cv2<br>from cvzone.PoseModule import PoseDetector<br><br># Initialize webcam<br>cap = cv2.VideoCapture(0)<br>detector = PoseDetector()<br><br># Path to shirt images<br>shirtFolderPath = &quot;C:/Users/hanis/Downloads/Resources-1/Resources/Shirts&quot;<br>listShirts = os.listdir(shirtFolderPath)<br><br># Calculate the fixed aspect ratio<br>fixedRatio = 262 / 190  # widthOfShirt / widthOfPoint11to12<br>shirtRatioHeightWidth = 581 / 440<br><br># Initialize image number for shirt selection<br>imageNumber = 0<br><br># Load overlay images and buttons<br>imgButtonRight = cv2.imread(&quot;C:/Users/hanis/Downloads/Resources-1/Resources/button.png&quot;, cv2.IMREAD_UNCHANGED)<br>imgButtonLeft = cv2.flip(imgButtonRight, 1)<br><br># Resize the overlay images<br>overlay_width = 128<br>overlay_height = 128<br>imgButtonRight = cv2.resize(imgButtonRight, (overlay_width, overlay_height))[:, :, :3]<br>imgButtonLeft = cv2.resize(imgButtonLeft, (overlay_width, overlay_height))[:, :, :3]</pre><h3>Overlaying Shirts in Real-Time</h3><p>The core functionality of our virtual dressing room lies in overlaying virtual shirts on the person’s body captured by the webcam. We’ll achieve this through a series of steps:</p><h3>1. Capturing Webcam Feed and Pose Detection</h3><pre>while True:<br>    success, img = cap.read()<br>    img = detector.findPose(img)<br>    <br>    lmList, bboxInfo = detector.findPosition(img, bboxWithHands=False, draw=False)<br>    if lmList:<br>        # Your code here<br>        pass</pre><h3>2. Preparing the Shirt Image</h3><pre>        # Calculate necessary parameters for shirt placement<br>        lm11 = lmList[11][1:3]<br>        lm12 = lmList[12][1:3]<br>        imgShirt = cv2.imread(os.path.join(shirtFolderPath, listShirts[imageNumber]), cv2.IMREAD_UNCHANGED)<br><br>        # Calculate the width of the shirt based on pose landmarks<br>        widthOfShirt = int((lm11[0] - lm12[0]) * fixedRatio)<br>        imgShirt = cv2.resize(imgShirt, (widthOfShirt, int(widthOfShirt * shirtRatioHeightWidth)))<br><br>        # Calculate offset based on current scale<br>        currentScale = (lm11[0] - lm12[0]) / 190<br>        offset = int(44 * currentScale), int(48 * currentScale)</pre><h3>3. Overlaying the Shirt</h3><pre>        # Overlay the shirt on the person&#39;s body<br>        try:<br>            for c in range(3):<br>                img[lm12[1] - offset[1]:lm12[1] - offset[1] + imgShirt.shape[0], <br>                    lm12[0] - offset[0]:lm12[0] - offset[0] + imgShirt.shape[1], c] = \<br>                    img[lm12[1] - offset[1]:lm12[1] - offset[1] + imgShirt.shape[0], <br>                    lm12[0] - offset[0]:lm12[0] - offset[0] + imgShirt.shape[1], c] * \<br>                    (1 - imgShirt[:, :, 3] / 255.0)<br>        except:<br>            pass</pre><h3>4. Adding Interactive Buttons</h3><pre>        # Overlay interactive buttons for shirt selection<br>        overlay_right_x = img.shape[1] - imgButtonRight.shape[1] - 10<br>        overlay_left_x = 10<br><br>        img[293:293 + imgButtonRight.shape[0], overlay_right_x:overlay_right_x + imgButtonRight.shape[1]] = imgButtonRight<br>        img[293:293 + imgButtonLeft.shape[0], overlay_left_x:overlay_left_x + imgButtonLeft.shape[1]] = imgButtonLeft</pre><h3>5. Interacting with the Application</h3><pre>        # Implement button interaction for shirt selection<br>        if lmList[16][1] &lt; 300:<br>            counterRight += 1<br>            cv2.ellipse(img, (139, 360), (66, 66), 0, 0,<br>                        counterRight * selectionSpeed, (0, 255, 0), 20)<br>            if counterRight * selectionSpeed &gt; 360:<br>                counterRight = 0<br>                if imageNumber &lt; len(listShirts) - 1:<br>                    imageNumber += 1<br>        elif lmList[15][1] &gt; 900:<br>            counterLeft += 1<br>            cv2.ellipse(img, (1138, 360), (66, 66), 0, 0,<br>                        counterLeft * selectionSpeed, (0, 255, 0), 20)<br>            if counterLeft * selectionSpeed &gt; 360:<br>                counterLeft = 0<br>                if imageNumber &gt; 0:<br>                    imageNumber -= 1<br>        else:<br>            counterRight = 0<br>            counterLeft = 0</pre><h3>Conclusion</h3><p>Congratulations! You’ve successfully built an interactive virtual dressing room using OpenCV and Python. This project showcases the fascinating possibilities that arise when technology meets creativity. Feel free to explore further by adding more shirts, optimizing the overlay process, and even experimenting with advanced computer vision techniques. Now you have the tools to virtually try on different outfits without stepping into a changing room. Happy coding and innovating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3d8630f82c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Dialogflow Chatbot with Webhook Integration for FastAPI and MongoDB]]></title>
            <link>https://medium.com/@sarahanish9/building-a-dialogflow-chatbot-with-webhook-integration-for-fastapi-and-mongodb-e1fe4b1a2fb?source=rss-8c3aa7313282------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1fe4b1a2fb</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[dialogflow]]></category>
            <dc:creator><![CDATA[Hanish]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:04:39 GMT</pubDate>
            <atom:updated>2023-07-04T07:04:39.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXldg_eh7tvq2rmcj2kRnA.jpeg" /></figure><p><strong>Introduction:</strong><br>In order to provide automated support and enhance user experiences, chatbots have grown in popularity. We will examine how to use webhooks to create a Dialogflow chatbot that is integrated with the FastAPI in this lesson. We will concentrate on getting property information out of a MongoDB database and showing it in the chatbot interface. In the MongoDB database, we will also keep user data for later processing. You will have a fully functional chatbot capable of retrieving property information and obtaining user data at the end of this session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQpQJjVtSuUFxXmb64hqYw.png" /></figure><p><strong>Prerequisites</strong>: You need to have a basic understanding of Python, FastAPI, Dialogflow, and MongoDB to follow along with this lesson. Before continuing, ensure that you have these installed and configured.</p><p><strong>Step 1: Setting up the Project</strong><br>Let’s start by setting up our project environment. Open a terminal or command prompt and follow these steps</p><pre>$ mkdir dialogflow-chatbot<br>$ cd dialogflow-chatbot<br>$ python3 -m venv venv<br>$ source venv/bin/activate  # For Linux/Mac<br>$ .\venv\Scripts\activate  # For Windows<br></pre><p><strong>Step 2: Installing Dependencies</strong></p><p>Next, we need to install the required dependencies. Create a new file called requirements.txt in your project directory and add the following dependencies:</p><pre>fastapi<br>pymongo<br>pydantic<br>uvicorn</pre><p>Save the file and install the dependencies using pip:</p><pre>$ pip install -r requirements.txt</pre><p><strong>Step 3: Setting up MongoDB Connection</strong></p><p>To connect to our MongoDB database, open the main.py file in your favorite code editor and add the following code:</p><pre>import logging<br>from fastapi import FastAPI, Request<br>from fastapi.responses import JSONResponse<br>from pydantic import BaseModel<br>from pymongo import MongoClient<br><br># Connection URL and database name<br>client = MongoClient(&quot;mongodb_URL&quot;)<br>db = client[&quot;Database_name&quot;]<br>property_collection = db[&quot;Collection_name&quot;]<br>response_collection = db[&quot;Collection_name&quot;]<br><br># Define the request models<br>class PropertyRequest(BaseModel):<br>    location: str<br><br>class ResponseRequest(BaseModel):<br>    name: str<br>    email: str<br>    phone_number: str<br><br># Create FastAPI application<br>app = FastAPI()</pre><p><strong>Step 4</strong>:<strong> Implementing the Dialogflow Webhook Integration</strong></p><p>Let’s define the route and logic for handling Dialogflow’s webhook integration. Add the following code to main.py:</p><pre>@app.post(&quot;/fulfillment&quot;)<br>async def fulfillment(request: Request):<br>    # Get the JSON payload from the request<br>    payload = await request.json()<br><br>    # Extract the intent name<br>    intent_name = payload[&quot;queryResult&quot;][&quot;intent&quot;][&quot;displayName&quot;]<br><br>    if intent_name == &quot;Details&quot;:<br>        # Retrieve user information from the payload<br>        name = payload[&quot;queryResult&quot;][&quot;parameters&quot;][&quot;name&quot;]<br>        email = payload[&quot;queryResult&quot;][&quot;parameters&quot;][&quot;email&quot;]<br>        phone_number = payload[&quot;queryResult&quot;][&quot;parameters&quot;][&quot;phone_number&quot;]<br><br>        # Create a new response document<br>        response_doc = {<br>            &quot;name&quot;: name,<br>            &quot;email&quot;: email,<br>            &quot;phone_number&quot;: phone_number<br>        }<br><br>        # Save the response document to the &#39;responses&#39; collection<br>        response_collection.insert_one(response_doc)<br><br>    elif intent_name == &quot;Yes&quot;:<br>        # Retrieve location parameter from the payload<br>        location = payload[&quot;queryResult&quot;][&quot;parameters&quot;][&quot;Location&quot;]<br><br>        # Create a query object to filter based on location<br>        query = {&quot;Location&quot;: location}<br><br>        # Retrieve properties matching the location filter<br>        result = property_collection.find(query)<br>        properties_list = list(result)<br><br>        # Prepare the response<br>        fulfillment_messages = [<br>            {<br>                &quot;payload&quot;: {<br>                    &quot;richContent&quot;: [<br>                        [<br>                            {<br>                                &quot;type&quot;: &quot;image&quot;,<br>                                &quot;rawUrl&quot;: property[&#39;Image&#39;],<br>                                &quot;accessibilityText&quot;: f&quot;{property[&#39;Type_&#39;]} in {property[&#39;Location&#39;]}&quot;<br>                            },<br>                            {<br>                                &quot;type&quot;: &quot;info&quot;,<br>                                &quot;title&quot;: f&quot;{property[&#39;Type_&#39;]} in {property[&#39;Location&#39;]}&quot;,<br>                                &quot;subtitle&quot;: f&quot;Price: {property[&#39;Price&#39;]}, Bedrooms: {property[&#39;Bed_Rooms&#39;]}, Bathrooms: {property[&#39;Bathrooms&#39;]}&quot;<br>                            }<br>                        ]<br>                    ]<br>                }<br>            }<br>            for property in properties_list<br>        ]<br><br>        # Add a message before the properties<br>        fulfillment_messages.insert(0, {<br>            &quot;text&quot;: {<br>                &quot;text&quot;: [&quot;Here are your amazing properties✌️&quot;]<br>            }<br>        })<br><br>        response = {<br>            &quot;fulfillmentMessages&quot;: fulfillment_messages<br>        }<br><br>        return JSONResponse(content=response, headers={&quot;Content-Type&quot;: &quot;application/json&quot;})<br><br>    else:<br>        logging.warning(&quot;Unsupported intent triggered&quot;)<br>        return JSONResponse(content={&quot;fulfillmentMessages&quot;: [{&quot;text&quot;: {&quot;text&quot;: [&quot;This fulfillment is not triggered for the specified intent.&quot;]}}]}, headers={&quot;Content-Type&quot;: &quot;application/json&quot;})</pre><p><strong>Step 5: Running the FastAPI App </strong>:</p><p>To run the FastAPI application, add the following code at the end of main.py:</p><pre>if __name__ == &quot;__main__&quot;:<br>    logging.basicConfig(level=logging.INFO)<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p><strong>Step 6: Deploying FastAPI App</strong></p><p>Deploy the FastAPI app by running the following command in the terminal:</p><pre>$ uvicorn main:app --reload</pre><p>The application will start running at <a href="http://localhost:8000.">http://localhost:8000.</a></p><p><strong>Step 7: Integrating with Dialogflow</strong></p><ol><li>Open the Dialogflow console and navigate to your agent.</li><li>Go to the “Fulfillment” section.</li><li>Enable the “Webhook” option and enter the URL of your FastAPI application</li><li>Save your changes</li></ol><p><strong>Step 8: Testing the Chatbot</strong></p><ol><li>In the Dialogflow console, go to the “Test” section.</li><li>Start a conversation with your chatbot and ask questions related to property details.</li><li>The chatbot will retrieve property information from the MongoDB database and display it in the chat interface.</li><li>If the user provides personal information, it will be stored in the MongoDB database for further processing.</li></ol><p><strong>Let’s go through the code step by step to understand its functionality:</strong></p><ol><li>First, the necessary libraries and modules are imported:</li></ol><ul><li>logging is imported for logging purposes.</li><li>FastAPI is imported to create the FastAPI application.</li><li>Request is imported from fastapi to handle incoming requests.</li><li>JSONResponse is imported from fastapi.responses to create JSON responses.</li><li>BaseModel is imported from pydantic to define request models.</li><li>MongoClient is imported from pymongo to connect to MongoDB.</li></ul><p>2. The MongoDB connection details are defined using MongoClient. Update this section with your own MongoDB connection URL and database details.</p><p>3. Two collections are defined:</p><ul><li>The First collection represents the collection in the MongoDB database that stores property information.</li><li>The Second collection represents the collection in the MongoDB database that stores user responses.</li></ul><p>4. Two request models are defined using BaseModel:</p><ul><li>PropertyRequest represents the request model for retrieving property details based on location.</li><li>ResponseRequest represents the request model for storing user response information.</li></ul><p>5. The FastAPI application is created using FastAPI().</p><p>6. The /fulfillment route is defined as a POST route that handles the fulfillment logic for Dialogflow webhook integration. It expects a Request object as input.</p><p>7. Inside the fulfillment route function:</p><ul><li>The JSON payload from the request is extracted using await request.json().</li><li>The intent name is extracted from the payload to determine the appropriate fulfillment logic.</li></ul><p>8. If the intent name is “Details”:</p><ul><li>The user information (name, email, phone number) is retrieved from the payload.</li><li>A new response document is created with the user information.</li><li>The response document is inserted into the responses collection in the MongoDB database.</li></ul><p>9. If the intent name is “Yes”:</p><ul><li>The location parameter is retrieved from the payload.</li><li>A query object is created to filter properties based on the location.</li><li>Properties matching the location filter are retrieved from the properties collection in the MongoDB database.</li><li>The property details are prepared in the format expected by Dialogflow’s rich content response.</li><li>A fulfillment response is created with the property details and a message.</li><li>The fulfillment response is returned as a JSON response</li></ul><p>10. If the intent name does not match any supported intents:</p><ul><li>A warning message is logged.</li><li>A response is returned indicating that the fulfillment is not triggered for the specified intent.</li></ul><p>11.Finally, the code checks if the main.py file is being run directly (not imported as a module):</p><ul><li>The logging level is set to INFO.</li><li>The FastAPI application is run using uvicorn on host=&quot;0.0.0.0&quot; and port=8000.</li></ul><p>To summarize, the code sets up a FastAPI application that handles the fulfillment logic for a Dialogflow chatbot. It retrieves property details from a MongoDB database based on user queries and displays them in the chatbot using rich content responses. User information provided during the conversation is stored in the MongoDB database for further processing.</p><p>Remember to customize the code according to your specific requirements, such as adding more intents, modifying the response format, and implementing error handling and authentication as needed.</p><p><strong>Conclusion:</strong></p><p>In this tutorial, we created a Dialogflow chatbot and used webhooks to interface it with FastAPI. We learned how to extract and show property details from a MongoDB database in the chatbot. We also saved user information in the MongoDB database. This chatbot can be improved further by adding new intents, enabling natural language comprehension, and interacting with other services.</p><p>Remember to adapt the code to your needs and to guarantee correct error handling, security, and authentication in a production environment. Have fun coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1fe4b1a2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>