<?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 Chesta Dhingra on Medium]]></title>
        <description><![CDATA[Stories by Chesta Dhingra on Medium]]></description>
        <link>https://medium.com/@chestadhingra25?source=rss-d63e0ab3862e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*040SH1OzAbCcWTFBnt5toQ.jpeg</url>
            <title>Stories by Chesta Dhingra on Medium</title>
            <link>https://medium.com/@chestadhingra25?source=rss-d63e0ab3862e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:06:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chestadhingra25/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[Building, Dockerizing, and Deploying a Streamlit RAG App on AWS: A Complete Step-by-Step Guide]]></title>
            <link>https://medium.com/data-and-beyond/building-dockerizing-and-deploying-a-streamlit-rag-app-on-aws-a-complete-step-by-step-guide-e83f724d5f0a?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83f724d5f0a</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 08:05:20 GMT</pubDate>
            <atom:updated>2025-03-09T08:05:20.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOGqsHj5Rr4NGZNMcIc8ZA.png" /><figcaption>By Author</figcaption></figure><p><em>This article explores the step-by-step process of developing the Retrieval Augmented Generator based LLM for the private documents. We will cover everything from setting up the RAG pipeline to deploying it on AWS ElasticBeanStalk with load balancers, ensuring scalability and reliability.</em></p><p>In my previous article, <strong>“</strong><a href="https://medium.com/data-and-beyond/rag-demystified-a-beginners-guied-to-building-first-retrieval-augmented-generator-system-6842a8e6b39a"><strong>RAG Demystified: A Beginner’s Guide to Building Your First Retrieval-Augmented Generation System</strong></a><strong>,”</strong> I explained the core concepts of RAG, breaking down its <strong>four key steps</strong> that enable both basic and advanced implementations. Additionally, I discussed how RAG is becoming a powerful tool in the industry, supporting theoretical insights with practical examples.</p><p>This article takes a <strong>fully hands-on approach</strong>, guiding you through the <strong>end-to-end development</strong> of a <strong>Dockerized Streamlit-based RAG web application</strong>. We will start by developing the RAG logic, then build an interactive web app using <strong>Streamlit</strong>, and finally <strong>containerize the application with Docker</strong> to simplify deployment on <strong>AWS Elastic Beanstalk</strong> with <strong>load balancing</strong> for optimal performance.</p><p>To develop a <strong>Retrieval-Augmented Generation (RAG) application</strong> based on private documents, we will follow a structured approach. For simplicity, we will use the <strong>“Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks”</strong> research paper as our dataset.</p><p><strong>Step 1: Load the Document and Prepare the Data</strong></p><p>First, we start by <strong>loading the private document</strong> and preparing it for processing. Since LLMs perform better when provided with structured input, we need to split the document into meaningful chunks.</p><p><strong>Step 2: Text Chunking for Better Context Retention</strong></p><p>To ensure that our RAG pipeline <strong>effectively understands the context</strong> without hallucination, we will split the text into manageable <strong>chunks</strong> using the CharacterTextSplitter function. This helps in maintaining contextual integrity by providing slight overlaps between chunks.</p><pre>   text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)# Ensures slight overlap to retain context chunk_overlap<br>        docs = []<br>        for page in pages:<br>            page_texts = text_splitter.split_text(page.page_content)  # raw_text contains the document content<br>            for t in page_texts:<br>                # We re-wrap them as Document objects<br>                docs.append(page.copy(update={&quot;page_content&quot;: t}))</pre><p>This process ensures that <strong>important contextual connections</strong> between sentences are preserved, reducing the risk of LLM hallucinations.</p><p><strong>Step 3: Generating Embeddings using OpenAI API</strong></p><p>Next, we convert our text chunks into <strong>vector representations</strong> using OpenAI’s embedding model. These embeddings allow us to store and retrieve relevant text efficiently based on similarity search.</p><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br><br># Initialize OpenAI embeddings<br>embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)<br></pre><p><strong>Step 4: Storing Embeddings in ChromaDB for Retrieval</strong></p><p>We store these embeddings in <strong>ChromaDB</strong>, which acts as our <strong>vector database</strong> for efficient retrieval. The vector database helps find <strong>semantically similar content</strong> when a user queries the system.</p><pre># Initialize ChromaDB vector store and persist embeddings<br> vectorstore = Chroma.from_documents(<br>            docs,<br>            embedding=embeddings,  # Updated parameter name<br>            persist_directory=&quot;db_chroma&quot;<br>        )<br>        vectorstore.persist()</pre><p>By storing vector embeddings, we enable <strong>fast and accurate retrieval of relevant context</strong> when users input queries. The system searches the database to fetch the <strong>top three most similar vectors</strong>, ensuring <strong>contextually relevant responses</strong> from the LLM.</p><p>Now, we will integrate this entire pipeline with Streamlit to build an interactive and user-friendly web application. And name this file as <strong>app.py</strong></p><pre>#pip install -U langchain-community<br>import streamlit as st<br>import os<br>from langchain_text_splitters import CharacterTextSplitter<br># from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.chains import RetrievalQA<br>from langchain.llms import OpenAI<br>from langchain.embeddings import OpenAIEmbeddings<br><br># 1) Ingest &amp; embed docs (simple approach: do it at startup)<br>@st.cache_resource<br>def load_vectorstore(openai_api_key):<br>    try:<br>        # Example: load a single PDF from sample_docs<br>        loader = PyPDFLoader(&quot;RAG_researchpaper.pdf&quot;)<br>        pages = loader.load_and_split()<br>        <br>        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>        docs = []<br>        for page in pages:<br>            page_texts = text_splitter.split_text(page.page_content)<br>            for t in page_texts:<br>                # We re-wrap them as Document objects<br>                docs.append(page.copy(update={&quot;page_content&quot;: t}))<br>        <br>        embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)<br>        vectorstore = Chroma.from_documents(<br>            docs,<br>            embedding=embeddings,  # Updated parameter name<br>            persist_directory=&quot;db_chroma&quot;<br>        )<br>        vectorstore.persist()<br>        return vectorstore<br>    except Exception as e:<br>        st.error(f&quot;Error loading or processing the document: {str(e)}&quot;)<br>        return None<br><br># Streamlit UI<br>st.title(&quot;Simple RAG Chatbot&quot;)<br><br>openai_api_key = st.text_input(&quot;Enter your OpenAI API key:&quot;, type=&quot;password&quot;)<br>query = st.text_input(&quot;Ask a question about the document:&quot;)<br><br>if st.button(&quot;Submit&quot;):<br>    if not openai_api_key:<br>        st.warning(&quot;Please enter your OpenAI API key.&quot;)<br>        st.stop()<br>    <br>    with st.spinner(&quot;Processing your question...&quot;):<br>        # Load or build the vectorstore<br>        vectordb = load_vectorstore(openai_api_key)<br>        <br>        if vectordb is None:<br>            st.error(&quot;Failed to load the document database.&quot;)<br>            st.stop()<br>        <br>        retriever = vectordb.as_retriever(search_kwargs={&quot;k&quot;: 3})<br>        <br>        # 2) Setup the QA chain<br>        llm = OpenAI(temperature=0, openai_api_key=openai_api_key)<br>        <br>        qa_chain = RetrievalQA.from_chain_type(<br>            llm=llm,<br>            chain_type=&quot;stuff&quot;,<br>            retriever=retriever,<br>            return_source_documents=True<br>        )<br>        <br>        # 3) Ask the question<br>        try:<br>            result = qa_chain({&quot;query&quot;: query})<br>            <br>            if isinstance(result, dict) and &quot;result&quot; in result:<br>                answer = result[&quot;result&quot;]<br>                st.write(&quot;**Answer:** &quot;, answer)<br>                <br>                # Optionally display source documents<br>                sources = result.get(&quot;source_documents&quot;, [])<br>                if sources and st.checkbox(&quot;Show sources&quot;):<br>                    st.write(&quot;**Sources:**&quot;)<br>                    for i, doc in enumerate(sources):<br>                        st.write(f&quot;Source {i+1}:&quot;)<br>                        st.write(doc.page_content)<br>                        st.write(&quot;---&quot;)<br>            else:<br>                # Handle older LangChain versions where the result might be a string<br>                st.write(&quot;**Answer:** &quot;, result)<br>        except Exception as e:<br>            st.error(f&quot;Error generating answer: {str(e)}&quot;)</pre><p>Next, we will containerize the web application using Docker. The first step in this process is to create a Dockerfile.</p><pre># 1. Start from a lightweight Python base image<br>FROM python:3.9-slim<br><br># 2. Set the working directory<br>WORKDIR /app<br><br># 3. Copy the requirements file and install dependencies<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># 4. Copy the rest of your application code into the container<br>COPY . /app<br><br># 5. Expose Streamlit’s default port<br>EXPOSE 8501<br><br># 6. Run Streamlit at container start<br>ENTRYPOINT [&quot;streamlit&quot;, &quot;run&quot;]<br>CMD [&quot;app.py&quot;, &quot;--server.port=8501&quot;, &quot;--server.address=0.0.0.0&quot;]</pre><p>In this testing phase, we will first verify that the Dockerized web application runs smoothly in a local environment before deploying it to the cloud. To do this, we will build the Docker image using the following command:</p><pre>docker build -t my_streamlitchatbot_app .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGgPW9x5AMDJMVyNSu4SDw.png" /><figcaption>By Author</figcaption></figure><p>In the next step, we will run the Dockerized application locally using the following command to map the container port to the host machine:</p><pre>docker run -p 8501:8501 my_streamlitchatbot_app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBEA6wOedbzwCRtmhr3i0A.png" /></figure><p>After successfully testing the application locally, we can proceed with deploying the Dockerized RAG application on <strong>AWS Elastic Beanstalk</strong> by following the necessary deployment steps.</p><h3>Prerequisites for Deployment</h3><p>Before deploying the <strong>Dockerized Streamlit RAG application</strong> on <strong>AWS Elastic Beanstalk</strong>, ensure you have the following prerequisites:</p><ol><li><strong>AWS Console Login</strong> — You must have an <strong>active AWS account</strong>.</li><li><strong>AWS CLI Installed</strong> — You need the <strong>AWS Command Line Interface (CLI)</strong> installed. Follow the official <a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html">AWS CLI installation guide</a>.</li></ol><h3><strong><em>Step-by-Step Deployment of Dockerized Streamlit RAG App on AWS Elastic Beanstalk</em></strong></h3><p><strong>Step 1: Prepare the Application Bundle</strong></p><p>Before deploying, you need to create a <strong>deployment bundle</strong> that includes all necessary files. As seen in <strong>Image 1</strong>, ensure your project directory contains:</p><ul><li><strong>Dockerfile</strong></li><li><strong>app.py (Streamlit Application Script)</strong></li><li><strong>requirements.txt (Dependencies List)</strong></li><li><strong>db_chroma (ChromaDB Vector Storage for Retrieval)</strong></li><li><strong>Any other required files</strong></li></ul><p><strong>Step 2: Create an IAM User with Required Permissions</strong></p><p>To deploy the application, you need to create an <strong>IAM User</strong> with the necessary permissions:</p><ol><li>Go to <strong>AWS Console &gt; IAM &gt; Users</strong> and create a new user.</li><li>Assign the following <strong>permissions policies</strong>:</li></ol><ul><li>AdministratorAccess-AWSElasticBeanstalk</li><li>AmazonS3FullAccess</li><li>IAMFullAccess</li></ul><p>3. Navigate to the <strong>Security Credentials Tab</strong> and generate an <strong>Access Key</strong>.</p><p>4.<strong> Download the credentials file (CSV format)</strong> and keep it secure.</p><p><strong>Step 3: Configure AWS CLI</strong></p><p>Now, configure your <strong>AWS CLI</strong> to use the credentials generated in Step 2. Open a <strong>command prompt</strong> and run:</p><pre>aws configure<br><br>## You will be prompted to enter:<br><br>## Access Key ID<br>## Secret Access Key<br>## Preferred AWS Region (e.g., us-east-1)<br>## Default Output Format → Enter &quot;json&quot;</pre><p><strong>Step 4: Install Elastic Beanstalk CLI (EB CLI)</strong></p><p>If you are using a <strong>virtual environment</strong> like <strong>Miniconda</strong>, activate it and run:</p><pre>pip install awsebcli</pre><p>To verify the installation, check the EB CLI version:</p><pre>eb --version</pre><p>When you run the above command, it will ask for:</p><ul><li><strong>AWS Region</strong> → Select 1 for us-east-1</li><li><strong>Key Pair Name</strong> → Choose a name like &quot;streamlit-llm-app&quot;</li><li>This will helps in setting up SSH access for your instances as shown in <strong>Image2</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*FyD82seb9yWdm4bBbpiMng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDFcpMtjSB3ItOf62n3KJQ.png" /><figcaption>Image 1 and Image 2</figcaption></figure><p>Step 5: Create and Deploy the Elastic Beanstalk Environment</p><p>Now, create the <strong>Elastic Beanstalk environment</strong> using:</p><pre>eb create</pre><p>During this process, you’ll be prompted for:</p><ul><li><strong>Environment Name</strong> → Example: &quot;streamlit-rag-production&quot;</li><li><strong>DNS CNAME Prefix</strong> → Accept the default or enter a custom one.</li><li><strong>Load Balancer Type</strong> → Choose &quot;application&quot; (suitable for both testing and production).</li></ul><p>The setup will take <strong>5–10 minutes</strong> to deploy your <strong>Dockerized RAG Web App</strong> to AWS.</p><p>Refer to <strong>Figures 3 &amp; 4</strong> for successful deployment output and application interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOGqsHj5Rr4NGZNMcIc8ZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgYtFu0seYSp1zDfKhBOSw.png" /><figcaption>Images 3 &amp; 4</figcaption></figure><p>Once deployed, access your application using the <strong>Elastic Beanstalk URL</strong> generated during deployment. You should see the <strong>Simple RAG Chatbot Web Interface</strong>, as shown in <strong>Figure 4</strong>.</p><h3><strong>Overall Conclusion</strong></h3><p>By following these steps, you have successfully:</p><p>✅ <strong>Built a RAG-based LLM application</strong> optimized for private document retrieval.<br> ✅ <strong>Prevented LLM hallucinations</strong> by implementing structured chunking and retrieval mechanisms.<br> ✅ <strong>Dockerized the Streamlit-based RAG application</strong>, ensuring portability and ease of deployment.<br> ✅ <strong>Configured AWS CLI &amp; IAM permissions</strong>, enabling secure interaction with AWS services.<br> ✅ <strong>Deployed the application on AWS Elastic Beanstalk</strong> with load balancers for scalability and reliability.</p><p>With this setup, your <strong>RAG-powered chatbot</strong> is now live, offering efficient and contextually relevant responses based on private documents</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83f724d5f0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/building-dockerizing-and-deploying-a-streamlit-rag-app-on-aws-a-complete-step-by-step-guide-e83f724d5f0a">Building, Dockerizing, and Deploying a Streamlit RAG App on AWS: A Complete Step-by-Step Guide</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Demystified: A Beginner’s Guied to Building First Retrieval-Augmented Generator System.]]></title>
            <link>https://medium.com/data-and-beyond/rag-demystified-a-beginners-guied-to-building-first-retrieval-augmented-generator-system-6842a8e6b39a?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6842a8e6b39a</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[crawl4ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 21:17:24 GMT</pubDate>
            <atom:updated>2025-02-06T21:17:24.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lHV70oc7y0U6o2bLf2QdA.png" /><figcaption><strong>By</strong> <strong>AI</strong></figcaption></figure><p>Second article in LLM Series.</p><p>In our<em> </em><a href="https://medium.com/data-and-beyond/hands-on-with-llms-ai-agents-learn-by-doing-4d7a5173fe20"><strong><em>previous article</em></strong></a><em> </em>we learnt about how “<strong>Large Language Models”</strong> have revolutionized the world of Artificial Intelligence and beyond. It has transformed the way we interact with the unstructured data. Though, these models are quite powerful but they do struggle with factual accuracy and context grounding. To overcome these hallucinations <strong>RAG</strong> <strong><em>Retrieval Augmented Generator </em></strong>system plays a crucial role. This helps in strengthen the retrieval system of the generative models to produce accurate, contextually relevant responses.</p><p>In this article, we’ll demystify RAG by exploring:</p><ul><li><strong>What is RAG?</strong></li><li><strong>Why is it important?</strong></li><li><strong>A beginner-friendly RAG application</strong></li></ul><p><strong>What is RAG?</strong></p><p>Retrieval Augmented Generator is an advanced framework that helps in overcoming the limitations of generative models via scanning or incoorporating the external corpus - be it documents, databases, or even live data streams — to locate relevant pieces of information based on a user query. This is the <strong>first </strong>component of RAG system known as “<em>Retriever” </em>. Modern retrievers often leverage vector embeddings and similarity search algorithms (like FAISS) to quickly pinpoint the most relevant snippets.</p><p><strong>Second</strong> important component of RAG is “<em>Generator” </em>which is a pre-trained model that generates the relevant contextual output to produce a more factual and informed grounded response by leveraging both its internal knowledge and the externally retrieved context.</p><p>The above two steps are the crucial ones that helps in reducing the inaccuracies or hallucinations in order to get more informed and relevant output.</p><p>Moving forward lets breakdown the four <strong>key </strong>steps on which RAG operates:-</p><ol><li><strong>Indexing :- </strong>Data in any format structured, semi-structured or unstructured is preprocessed and converted into the embeddings using models like BERT, SBERT or OpenAI’s embedding APIs. These embeddings are stored in the vector databases that helps in fast retrieval of the query based on similarity search.</li><li><strong>Retrieval :- </strong>User inputs the query. The query is first transformed into a vector representation. The system searches the vector database to retrieve the most relevant documents or text chunks based on semantic similarity.</li><li><strong>Augmentation :- </strong>The retrieved documents are combined with the user’s prompt, enriching the input with relevant context before passing it to the LLM.</li><li><strong>Generation :- </strong>Finally, the LLM generates a response by leveraging both its pre-trained knowledge and the retrieved, dynamically fused external data, ensuring <strong>a more accurate and contextually relevant output</strong>.</li></ol><p><strong>Why RAG is important?</strong></p><p>It is essential and advantageous in terms of both technical and business perspective.</p><ul><li>It enhances the <strong>accuracy of generated responses</strong>, minimizing the risk of <strong>hallucinations</strong> (fabricated or incorrect information). This is especially crucial for applications such as <strong>customer support, medical diagnosis, and financial analysis</strong>, where accuracy is paramount.</li><li>It <strong>dynamically incorporates fresh, domain-specific knowledge</strong>, ensuring responses stay relevant to the latest context and industry updates.</li><li>By augmenting generation with <strong>retrieved facts</strong>, RAG significantly reduces the chances of misinformation and improves trustworthiness.</li><li>From a <strong>business standpoint</strong>, RAG builds <strong>trust and credibility</strong> with users, driving better engagement and adoption. Additionally, its <strong>fast retrieval mechanism</strong> enhances scalability, allowing businesses to <strong>generate highly contextual responses efficiently</strong>.</li></ul><p><strong>A beginner-friendly RAG application</strong></p><p>Finally, we have reached the last step, where we will build a beginner-friendly RAG application.</p><p>This simple implementation will help in understanding a <strong>basic use case</strong>, which can later be enhanced into a <strong>fully-fledged real-time business application</strong>.</p><p>In future articles, I will focus on <strong>building and deploying an LLM-based application on a cloud server.</strong></p><p>Now, let’s dive into the <strong>RAG application code</strong>, where we will explore <strong>Crawl4AI</strong> — a <strong>web crawling and data extraction tool optimized for AI applications</strong>.</p><pre>### Now, let&#39;s implement the four key steps we discussed earlier in code.<br>### you need to install faiss-cpu using the command &quot;! pip install faiss-cpu&quot;<br><br><br>### load the essential libraries<br><br>import os<br>import requests<br>from bs4 import BeautifulSoup<br>from langchain.docstore.document import Document<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import FAISS<br>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import RetrievalQA<br>from dotenv import load_dotenv, find_dotenv<br><br>## load the OpenAI API key without disclosing it<br>load_dotenv(find_dotenv(),override=True)<br><br>## list of URLs that would act as the documents need to be passed as an <br>## external and updated information<br><br>urls = [<br>    &quot;https://docs.crawl4ai.com/core/simple-crawling/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/crawler-result/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/browser-crawler-config/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/fit-markdown/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/page-interaction/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/content-selection/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/cache-modes/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/local-files/&quot;,<br>    &quot;https://docs.crawl4ai.com/core/link-media/&quot;,<br>    &quot;https://docs.crawl4ai.com/advanced/hooks-auth/&quot;,<br>    &quot;https://docs.crawl4ai.com/advanced/proxy-security/&quot;,<br>    &quot;https://docs.crawl4ai.com/advanced/session-management/&quot;,<br>    &quot;https://docs.crawl4ai.com/advanced/multi-url-crawling/&quot;<br>]<br><br><br><br>def fetch_docs(url):<br>    ## fetches the raw HTML<br>    response = requests.get(url)<br>    ## below function will raise an exception if the request encountered <br>    ## an HTTP error<br>    response.raise_for_status()<br>    ## pass the raw HTML (response.text) into the BeautifulSoup constructor, <br>    ## specifying &quot;html.parser&quot; as the parsing engine.<br>    soup = BeautifulSoup(response.text,&quot;html.parser&quot;)<br>    ## line finds all HTML elements of the specified types<br>    ## these tags typically contain main textual content, <br>    ## headings, and code examples.<br>    text_elements = soup.find_all([&quot;p&quot;, &quot;li&quot;, &quot;code&quot;, &quot;pre&quot;, &quot;h1&quot;, &quot;h2&quot;, &quot;h3&quot;])<br>    ## iterate over each elem in text_elements and <br>    ## use elem.get_text(separator=&quot; &quot;) to extract just the visible text, ignoring HTML tags.<br>    text_chunks = [elem.get_text(separator = &quot; &quot;) for elem in text_elements]<br>    return &quot;\n&quot;.join(text_chunks)<br><br># Create a list to hold all Documents<br>all_docs = []<br><br>for url in urls:<br>    text_data = fetch_docs(url)<br>    # Create a Document object for each URL<br>    # Convert web pages, PDFs, or text files,into a uniform internal representation<br>    doc = Document(page_content=text_data,metadata={&quot;source&quot;:url}) <br>    # (LangChain’s Document objects in this case)<br>    all_docs.append(doc)<br><br>print(f&quot;Number of raw documents: {len(all_docs)}&quot;)<br><br>## Chunking &amp; Embedding<br># Split these docs into smaller chunks and embed them for retrieval<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500,chunk_overlap = 200)<br><br>## This will contain a list of chunked Documents<br><br>all_chunked_docs = []<br><br>for doc in all_docs:<br>    chunked_docs = text_splitter.split_documents([doc])<br>    all_chunked_docs.extend(chunked_docs)<br><br>print(f&quot;Total chunked docs: {len(all_chunked_docs)}&quot;)<br><br><br># Chunking &amp; Embedding<br><br># Create embeddings &amp; vector store<br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-ada-002&quot;)<br><br># Vector Store<br>##  Insert the embeddings into a vector database<br>faiss_index = FAISS.from_documents(all_chunked_docs, embedding=embeddings)<br>retriever = faiss_index.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 3})<br><br># Retriever + LLM<br><br># Set up the QA chain<br>llm = ChatOpenAI(model_name=&quot;gpt-3.5-turbo&quot;, temperature=0)<br>qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type=&quot;stuff&quot;, retriever=retriever)<br><br><br># Ask a test query<br>question = &quot;How do I set up a simple crawling configuration and what are the required parameters?&quot;<br>answer = qa_chain.run(question)<br><br>print(&quot;Q:&quot;, question)<br>print(&quot;A:&quot;, answer)<br><br>## below is the output.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDiqVUIATDertHsx9QSePw.png" /></figure><p><em>Hope you found this helpful! Drop your thoughts below, and let’s connect on LinkedIn.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6842a8e6b39a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/rag-demystified-a-beginners-guied-to-building-first-retrieval-augmented-generator-system-6842a8e6b39a">RAG Demystified: A Beginner’s Guied to Building First Retrieval-Augmented Generator System.</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On with LLMs, AI Agents: Learn By Doing]]></title>
            <link>https://medium.com/data-and-beyond/hands-on-with-llms-ai-agents-learn-by-doing-4d7a5173fe20?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7a5173fe20</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[financial-analysis]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 12:31:12 GMT</pubDate>
            <atom:updated>2025-01-12T12:31:12.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGsTtzSd2KP-DWtevV2IOg.jpeg" /></figure><p><strong>Article Highlights:</strong></p><ol><li>Introduction</li><li>LLMs as Operating System for AI Agents, RAGs and intermediaries for Function Calling. A theoretical Approach</li><li>3.1 Implementation of AI Agents and Function Calling via simple Financial Agent. 3.2 Implementation of AI Agents and Function Calling via LLM models using Open AI API.</li></ol><p><strong>1 Introduction</strong></p><p>We are living in the era defined by <strong>Artificial Intelligence </strong>where its imapct is reshaping every field. The most groundbreaking advancement is the rise of <strong>Large Language Models </strong><em>“LLMs” </em>which have revolutionized data science and beyond. <strong>OpenAI’s</strong> launch of <strong>ChatGPT</strong> — a <em>human-interactive conversational chatbot </em>— marked a pivotal moment in this journey, captivating the world with its unprecedented capabilities. Since its debut, LLMs have continued to transform how we interact with data, solve problems, and unlock new possibilities in technology.</p><p><strong>2. LLMs as Operating System for AI Agents, RAGs and intermediaries for Function Calling. A theoretical Approach.</strong></p><p>LLMs are core that binds AI Agents, function calling and RAG (Retrieval Augmented Generation) together acting as the “<strong><em>operating system” </em></strong><em>.</em></p><ol><li>For Power <strong>AI Agents </strong>it acts as the “brains” of AI Agents, enabling them to interpret complex queries, break them into actionable steps via executing them directly or calling external tools for execution.</li><li>LLMs serve as powerful intermediaries in specific to F<strong>unctionCalling </strong>by interpreting user intent from natural language queries and determining the appropriate actions or functions to invoke. In “<em>function calling” </em>LLMs refers to their ability to invoke external functions example could be PythonRepl, APIs, or tools to handle specific tasks.</li><li><strong>Retrieval-Augmented Generation (RAG) </strong>it combines the generative power of LLMs with the retrieval capabilities of external databases or knowledge sources. It strongly relies on storing data embedings in vector databases. These embeddings would be the essence of your text data in a high-dimensional space. When an LLM lacks sufficient information to answer a query, RAG systems fetch relevant data from external sources to “augment” the LLM’s response which are vector databases.</li></ol><p>3. <strong>Implementation</strong></p><blockquote><strong><em>3.1 Implementation of AI Agents and Function Calling via simple Financial Agent.</em></strong></blockquote><p>This implementation demonstrates several key concepts:</p><ol><li><strong>Function Calling Architecture :- 1.1</strong> AI agent has the registered functions it can call(get_stock_data, analyze_trends,etc.). <strong>1.2 </strong>Each function has a specific purpose and can be called independently. <strong>1.3 </strong>Agent would decide which function to call based on the query.</li><li><strong>External Tool Integration :- 2.1 </strong>Will be using “<em>yfinances” </em>as an external API for real stock data. <strong>2.2 </strong>Integrates with “matplotlib” python library for visualization. <strong>2.3 </strong>Could be extended to use any other tools or APIs</li><li><strong>Query Understanding :- 3.1 </strong>In the below code we will be using simply keyword matching. <strong>3.2 </strong>In our second implementation we’ll be discussing the code in which we will be applying <strong>LLM </strong>for better understanding of the query.</li></ol><pre>import pandas as pd<br>import yfinance as yf<br>import json<br>import matplotlib.pyplot as plt<br>from typing import Dict, Any<br><br>class FinancialAgent:<br>    def __init__(self):<br>        # Optionally keep this dictionary if you want to dynamically call these methods.<br>        # Otherwise, you can remove it if you&#39;re using only the `execute` dispatch approach.<br>        self.available_functions = {<br>            &quot;get_stock_data&quot;: self.get_stock_data,<br>            &quot;analyze_trends&quot;: self.analyze_trends,<br>            &quot;plot_data&quot;: self.plot_data,<br>            &quot;generate_report&quot;: self.generate_report<br>        }<br><br>    def execute(self, query: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Main entry point to interpret the query and decide which handler method<br>        to call.<br>        &quot;&quot;&quot;<br>        # Example of a helper method that extracts a single symbol from the query<br>        # (Implement this logic as needed for your project.)<br>        symbol = self._extract_symbol(query)<br><br>        query_lower = query.lower()<br>        is_trend = &quot;trend&quot; in query_lower<br>        is_report = &quot;report&quot; in query_lower<br>        is_stock = &quot;stock&quot; in query_lower<br>        should_plot = &quot;plot&quot; in query_lower<br><br>        # Decide how to respond based on the keywords<br>        if is_trend:<br>            return self.handle_trend_analysis(symbol, should_plot)<br>        elif is_report:<br>            return self.handle_report_request(symbol)<br>        elif is_stock:<br>            return self.handle_stock_query(symbol, should_plot)<br>        elif should_plot:<br>            return self.handle_plot_only(symbol, should_plot)<br>        else:<br>            return {&quot;error&quot;: &quot;Could not interpret query. Please specify &#39;trend&#39;, &#39;stock&#39;, or &#39;report&#39;.&quot;}<br><br>    # ---------------------------------------------------------------------<br>    #                           Handlers<br>    # ---------------------------------------------------------------------<br><br>    def handle_trend_analysis(self, symbol: str, should_plot: bool) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        For queries explicitly asking about &#39;trend&#39;, we:<br>          1. Get the stock data<br>          2. Analyze the trends<br>          3. Optionally plot the data<br>          4. Return a minimal trend-focused response (no full report).<br>        &quot;&quot;&quot;<br>        data = self.get_stock_data(symbol)<br>        if data.empty:<br>            return {&quot;error&quot;: f&quot;No data found for &#39;{symbol}&#39;.&quot;}<br><br>        analysis = self.analyze_trends(data)<br>        <br>        if should_plot:<br>            plot_result = self.plot_data(data, f&quot;{symbol} Stock Trend Analysis&quot;)<br>        else:<br>            plot_result = &quot;Plotting was not requested.&quot;<br><br>        return {<br>            &quot;data&quot;: self._convert_dataframe_to_dict(data),<br>            &quot;analysis&quot;: analysis,<br>            &quot;trend_summary&quot;: self._generate_trend_summary(analysis),<br>            &quot;plot_status&quot;: plot_result<br>        }<br><br>    def handle_report_request(self, symbol: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        For queries explicitly requesting a report:<br>          1. Get stock data<br>          2. Analyze data<br>          3. Generate a full textual report or PDF<br>        &quot;&quot;&quot;<br>        data = self.get_stock_data(symbol)<br>        if data.empty:<br>            return {&quot;error&quot;: f&quot;No data found for &#39;{symbol}&#39;.&quot;}<br><br>        analysis = self.analyze_trends(data)<br>        report_str = self.generate_report(analysis)<br><br>        # If you want to include a plot in the report, uncomment:<br>        # plot_result = self.plot_data(data, f&quot;{symbol} Stock Report Chart&quot;)<br><br>        return {<br>            &quot;data&quot;: self._convert_dataframe_to_dict(data),<br>            &quot;analysis&quot;: analysis,<br>            &quot;report&quot;: report_str<br>            # &quot;plot_status&quot;: plot_result  # Uncomment if you want a plot<br>        }<br><br>    def handle_stock_query(self, symbol: str, should_plot: bool) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        For queries explicitly asking about &#39;stock&#39;, we:<br>          1. Fetch basic stock info or data<br>          2. Optionally plot the data<br>        &quot;&quot;&quot;<br>        data = self.get_stock_data(symbol)<br>        if data.empty:<br>            return {&quot;error&quot;: f&quot;No data found for &#39;{symbol}&#39;.&quot;}<br><br>        # You can define what &quot;stock query&quot; means: <br>        # maybe a simple data return, or minimal analysis, etc.<br>        # Example: just return the data for now:<br>        stock_info = {<br>            &quot;symbol&quot;: symbol,<br>            &quot;data&quot;: self._convert_dataframe_to_dict(data)<br>        }<br><br>        if should_plot:<br>            plot_result = self.plot_data(data, f&quot;{symbol} Stock Query Chart&quot;)<br>            stock_info[&quot;plot_status&quot;] = plot_result<br>        else:<br>            stock_info[&quot;plot_status&quot;] = &quot;Plotting was not requested.&quot;<br><br>        return stock_info<br><br>    def handle_plot_only(self, symbol: str, should_plot: bool) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        For queries that specifically request only a plot, we:<br>          1. Fetch the data<br>          2. Generate a plot<br>          3. Return minimal info (plus plot status).<br>        &quot;&quot;&quot;<br>        data = self.get_stock_data(symbol)<br>        if data.empty:<br>            return {&quot;error&quot;: f&quot;No data found for &#39;{symbol}&#39;.&quot;}<br><br>        if should_plot:<br>            plot_result = self.plot_data(data, f&quot;{symbol} Stock Plot&quot;)<br>            return {<br>                &quot;data&quot;: self._convert_dataframe_to_dict(data),<br>                &quot;plot_status&quot;: plot_result<br>            }<br>        else:<br>            return {<br>                &quot;data&quot;: self._convert_dataframe_to_dict(data),<br>                &quot;plot_status&quot;: &quot;Plotting was not requested.&quot;<br>            }<br><br>    # ---------------------------------------------------------------------<br>    #                         Utility Methods<br>    # ---------------------------------------------------------------------<br>    def get_stock_data(self, symbol: str, period: str = &quot;1mo&quot;) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;<br>        Fetches the stock data for given symbol &amp; period via yfinance.<br>        &quot;&quot;&quot;<br>        try:<br>            stock = yf.Ticker(symbol)<br>            data = stock.history(period=period)<br>            return data<br>        except Exception as e:<br>            return pd.DataFrame()<br><br>    def analyze_trends(self, data: pd.DataFrame) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Basic trend analysis: calculates average price, price changes, volatility, etc.<br>        &quot;&quot;&quot;<br>        if data.empty:<br>            return {&quot;error&quot;: &quot;No data to analyze.&quot;}<br><br>        close_prices = data[&#39;Close&#39;].values<br>        return {<br>            &quot;average_price&quot;: float(data[&#39;Close&#39;].mean()),<br>            &quot;price_change_pct&quot;: float((close_prices[-1] - close_prices[0]) / close_prices[0] * 100),<br>            &quot;volatility&quot;: float(data[&#39;Close&#39;].std()),<br>            &quot;volume_trend&quot;: &quot;increasing&quot; if data[&#39;Volume&#39;].is_monotonic_increasing else &quot;decreasing&quot;,<br>            &quot;latest_price&quot;: float(close_prices[-1]),<br>            &quot;start_date&quot;: data.index[0].strftime(&#39;%Y-%m-%d&#39;),<br>            &quot;end_date&quot;: data.index[-1].strftime(&#39;%Y-%m-%d&#39;)<br>        }<br><br>    def _generate_trend_summary(self, analysis: Dict[str, Any]) -&gt; str:<br>        &quot;&quot;&quot;<br>        Creates a concise summary of the trend analysis for quick reference.<br>        &quot;&quot;&quot;<br>        if &quot;error&quot; in analysis:<br>            return &quot;No trend summary available due to error or missing data.&quot;<br><br>        price_change_direction = &quot;Up&quot; if analysis[&quot;price_change_pct&quot;] &gt; 0 else &quot;Down&quot;<br>        return f&quot;&quot;&quot;<br>        Trend Summary:<br>        Period: {analysis[&#39;start_date&#39;]} to {analysis[&#39;end_date&#39;]}<br>        Latest Price: ${analysis[&#39;latest_price&#39;]:.2f}<br>        Price Movement: {price_change_direction} ({analysis[&#39;price_change_pct&#39;]:.2f}%)<br>        Volume Trend: {analysis[&#39;volume_trend&#39;]}<br>        Volatility: {analysis[&#39;volatility&#39;]:.2f}<br>        &quot;&quot;&quot;<br><br>    def plot_data(self, data: pd.DataFrame, title: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Creates a simple plot of &#39;Close&#39; price over time using matplotlib.<br>        Returns a dict with plot status or error.<br>        &quot;&quot;&quot;<br>        try:<br>            plt.figure(figsize=(12, 6))<br>            plt.plot(data.index, data[&#39;Close&#39;], label=&#39;Close Price&#39;)<br>            plt.title(title)<br>            plt.xlabel(&#39;Date&#39;)<br>            plt.ylabel(&#39;Price&#39;)<br>            plt.legend()<br>            # plt.show()  # Omit or include depending on your environment<br>            return {&quot;status&quot;: &quot;success&quot;, &quot;message&quot;: f&quot;Plot generated for {title}&quot;}<br>        except Exception as e:<br>            return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: str(e)}<br><br>    def generate_report(self, analysis: Dict[str, Any]) -&gt; str:<br>        &quot;&quot;&quot;<br>        Generates a textual representation of the analysis.<br>        &quot;&quot;&quot;<br>        if &quot;error&quot; in analysis:<br>            return f&quot;Cannot generate report: {analysis[&#39;error&#39;]}&quot;<br><br>        return f&quot;&quot;&quot;<br>        Financial Analysis Report<br>        ------------------------<br>        Period: {analysis[&#39;start_date&#39;]} to {analysis[&#39;end_date&#39;]}<br>        Latest Price: ${analysis[&#39;latest_price&#39;]:.2f}<br>        Average Price: ${analysis[&#39;average_price&#39;]:.2f}<br>        Price Change: {analysis[&#39;price_change_pct&#39;]:.2f}%<br>        Volatility: {analysis[&#39;volatility&#39;]:.2f}<br>        Volume Trend: {analysis[&#39;volume_trend&#39;]}<br>        &quot;&quot;&quot;<br><br>    def _convert_dataframe_to_dict(self, data: pd.DataFrame) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Converts a DataFrame to a JSON-serializable dict for easy response.<br>        &quot;&quot;&quot;<br>        return {<br>            &#39;dates&#39;: [d.strftime(&#39;%Y-%m-%d&#39;) for d in data.index],<br>            &#39;prices&#39;: data[&#39;Close&#39;].tolist(),<br>            &#39;volumes&#39;: data[&#39;Volume&#39;].tolist(),<br>            &#39;opens&#39;: data[&#39;Open&#39;].tolist(),<br>            &#39;highs&#39;: data[&#39;High&#39;].tolist(),<br>            &#39;lows&#39;: data[&#39;Low&#39;].tolist()<br>        }<br><br>    def _extract_symbol(self, query: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        Simple approach: if known keywords appear in the query, use that symbol.<br>        Otherwise default to AAPL.<br>        &quot;&quot;&quot;<br>        common_symbols = {<br>            &quot;TSLA&quot;: [&quot;tesla&quot;, &quot;tsla&quot;],<br>            &quot;AAPL&quot;: [&quot;apple&quot;, &quot;aapl&quot;],<br>            &quot;MSFT&quot;: [&quot;microsoft&quot;, &quot;msft&quot;]<br>        }<br>        query_lower = query.lower()<br>        for sym, keywords in common_symbols.items():<br>            if any(k in query_lower for k in keywords):<br>                return sym<br><br>        return &quot;AAPL&quot;  # default<br># Example usage:<br>if __name__ == &quot;__main__&quot;:<br>    agent = FinancialAgent()<br>    queries = [<br>        &quot;What&#39;s the trend for TSLA?&quot;,<br>        &quot;Generate a report for Apple&quot;,<br>        &quot;Get me stock info for Microsoft&quot;,<br>        &quot;Can you show me just the plot for TSLA stock?&quot;,<br>        &quot;Unrecognized query&quot;  # to illustrate error handling<br>    ]<br>    for q in queries:<br>        result = agent.execute(q)<br>        print(f&quot;\nQuery: {q}&quot;)<br>        print(&quot;Result:&quot;, json.dumps(result, indent=2))</pre><blockquote><strong>3.2 <em>Implementation of AI Agents and Function Calling for AI- Driven financial Assistance via Open AI APIs.</em></strong></blockquote><ol><li><strong>LLM Integration:- 1.1</strong> Uses OpenAI’s GPT-4 Turbo model. <strong>1.2</strong> Handles natural language processing. <strong>1.3</strong> Manages function calling and response generation.</li><li><strong>Financial Analysis Tools:- 2.1 </strong>Yahoo Finance integration for real-time data. <strong>2.2</strong> Technical analysis calculations. <strong>2.3 </strong>Trend analysis capabilities.</li><li><strong>Function Registry:- 3.1</strong> Defined available functions for the LLM. <strong>3.2</strong> Parameter specifications. <strong>3.3</strong> Input validation.</li></ol><pre>from typing import List, Dict, Any<br>import pandas as pd<br>import yfinance as yf<br>from datetime import datetime, timedelta<br>from openai import OpenAI<br>import json<br><br>class LLMFinancialAgent:<br>    def __init__(self, openai_api_key: str):<br>        self.client = OpenAI(api_key=openai_api_key)<br><br>        # Define available functions for OpenAI<br>        self.functions = [<br>            {<br>                &quot;name&quot;: &quot;get_stock_data&quot;,<br>                &quot;description&quot;: &quot;Fetch historical stock data for a given symbol&quot;,<br>                &quot;parameters&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;symbol&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;Stock ticker symbol (e.g., AAPL)&quot;<br>                        },<br>                        &quot;period&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;Time period for data (e.g., 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;symbol&quot;]<br>                }<br>            },<br>            {<br>                &quot;name&quot;: &quot;analyze_trends&quot;,<br>                &quot;description&quot;: &quot;Analyze stock price trends and patterns&quot;,<br>                &quot;parameters&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;data&quot;: {<br>                            &quot;type&quot;: &quot;object&quot;,<br>                            &quot;description&quot;: &quot;Stock price data in dictionary format&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;data&quot;]<br>                }<br>            }<br>        ]<br><br>    def execute(self, user_query: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Main execution function that uses LLM to interpret queries and execute appropriate actions<br>        &quot;&quot;&quot;<br>        try:<br>            # Get LLM&#39;s interpretation of the query<br>            messages = [<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a financial analysis assistant. Your task is to help analyze stock market data and trends.&quot;},<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query}<br>            ]<br><br>            response = self.client.chat.completions.create(<br>                model=&quot;gpt-4-turbo-preview&quot;,<br>                messages=messages,<br>                functions=self.functions,<br>                function_call=&quot;auto&quot;<br>            )<br><br>            # Extract the function call<br>            message = response.choices[0].message<br><br>            if message.function_call:<br>                # Execute the function<br>                function_name = message.function_call.name<br>                function_args = json.loads(message.function_call.arguments)<br><br>                # Call appropriate function<br>                result = getattr(self, function_name)(**function_args)<br><br>                # Get LLM to generate a natural language response<br>                messages.append({<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: None,<br>                    &quot;function_call&quot;: {<br>                        &quot;name&quot;: function_name,<br>                        &quot;arguments&quot;: message.function_call.arguments<br>                    }<br>                })<br>                messages.append({<br>                    &quot;role&quot;: &quot;function&quot;,<br>                    &quot;name&quot;: function_name,<br>                    &quot;content&quot;: json.dumps(result)<br>                })<br><br>                final_response = self.client.chat.completions.create(<br>                    model=&quot;gpt-4-turbo-preview&quot;,<br>                    messages=messages<br>                )<br><br>                return {<br>                    &quot;raw_data&quot;: result,<br>                    &quot;analysis&quot;: final_response.choices[0].message.content<br>                }<br><br>            return {&quot;error&quot;: &quot;No function call was made&quot;}<br><br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Error executing query: {str(e)}&quot;}<br><br>    def get_stock_data(self, symbol: str, period: str = &quot;1mo&quot;) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Fetch stock data using yfinance&quot;&quot;&quot;<br>        try:<br>            stock = yf.Ticker(symbol)<br>            data = stock.history(period=period)<br><br>            # Convert DataFrame to dictionary format<br>            data_dict = {<br>                &quot;dates&quot;: data.index.strftime(&#39;%Y-%m-%d&#39;).tolist(),<br>                &quot;prices&quot;: data[&#39;Close&#39;].tolist(),<br>                &quot;volumes&quot;: data[&#39;Volume&#39;].tolist()<br>            }<br><br>            return data_dict<br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Failed to fetch stock data: {str(e)}&quot;}<br><br>    def analyze_trends(self, data: Dict[str, Any]) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Analyze stock trends and patterns&quot;&quot;&quot;<br>        try:<br>            prices = data.get(&#39;prices&#39;, [])<br>            volumes = data.get(&#39;volumes&#39;, [])<br><br>            if not prices:<br>                return {&quot;error&quot;: &quot;No price data available&quot;}<br><br>            # Convert to pandas Series for analysis<br>            price_series = pd.Series(prices)<br>            volume_series = pd.Series(volumes)<br><br>            analysis = {<br>                &quot;average_price&quot;: float(price_series.mean()),<br>                &quot;price_change_pct&quot;: float((prices[-1] - prices[0]) / prices[0] * 100),<br>                &quot;volatility&quot;: float(price_series.std()),<br>                &quot;volume_trend&quot;: &quot;increasing&quot; if volume_series.is_monotonic_increasing else &quot;decreasing&quot;,<br>                &quot;price_trend&quot;: self._calculate_trend(price_series),<br>                &quot;technical_indicators&quot;: self._calculate_technical_indicators(price_series)<br>            }<br><br>            return analysis<br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Failed to analyze trends: {str(e)}&quot;}<br><br>    def _calculate_trend(self, prices: pd.Series) -&gt; str:<br>        &quot;&quot;&quot;Calculate overall trend direction&quot;&quot;&quot;<br>        if len(prices) &lt; 2:<br>            return &quot;insufficient data&quot;<br><br>        start_price = prices.iloc[0]<br>        end_price = prices.iloc[-1]<br>        price_change = ((end_price - start_price) / start_price) * 100<br><br>        if price_change &gt; 5:<br>            return &quot;strongly bullish&quot;<br>        elif price_change &gt; 0:<br>            return &quot;slightly bullish&quot;<br>        elif price_change &lt; -5:<br>            return &quot;strongly bearish&quot;<br>        elif price_change &lt; 0:<br>            return &quot;slightly bearish&quot;<br>        else:<br>            return &quot;neutral&quot;<br><br>    def _calculate_technical_indicators(self, prices: pd.Series) -&gt; Dict[str, float]:<br>        &quot;&quot;&quot;Calculate basic technical indicators&quot;&quot;&quot;<br>        return {<br>            &quot;SMA_20&quot;: float(prices.rolling(window=20).mean().iloc[-1]) if len(prices) &gt;= 20 else None,<br>            &quot;SMA_50&quot;: float(prices.rolling(window=50).mean().iloc[-1]) if len(prices) &gt;= 50 else None,<br>            &quot;RSI&quot;: self._calculate_rsi(prices) if len(prices) &gt;= 14 else None<br>        }<br><br>    def _calculate_rsi(self, prices: pd.Series, periods: int = 14) -&gt; float:<br>        &quot;&quot;&quot;Calculate Relative Strength Index&quot;&quot;&quot;<br>        delta = prices.diff()<br>        gain = (delta.where(delta &gt; 0, 0)).rolling(window=periods).mean()<br>        loss = (-delta.where(delta &lt; 0, 0)).rolling(window=periods).mean()<br><br>        rs = gain / loss<br>        rsi = 100 - (100 / (1 + rs))<br>        return float(rsi.iloc[-1])<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    # Initialize agent with your OpenAI API key<br>    agent = LLMFinancialAgent(&quot;your_API_key&quot;)<br><br>    # Example queries<br>    queries = [<br>        &quot;What&#39;s the current trend for AAPL stock?&quot;,<br>        &quot;Analyze Tesla stock performance over the last 3 months&quot;,<br>        &quot;Show me the technical indicators for Microsoft stock&quot;<br>    ]<br><br>    for query in queries:<br>        print(f&quot;\nQuery: {query}&quot;)<br>        result = agent.execute(query)<br>        print(&quot;Result:&quot;, json.dumps(result, indent=2))</pre><p><em>Hope you found this helpful! Drop your thoughts below, and let’s connect on LinkedIn. And heads up — I’m cooking up a deep dive into RAG implementation for my next article. Don’t want to miss it? Give me a follow!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7a5173fe20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/hands-on-with-llms-ai-agents-learn-by-doing-4d7a5173fe20">Hands-On with LLMs, AI Agents: Learn By Doing</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing OpenAI: Build a Smart Scraping Web Application with Streamlit and Generative AI]]></title>
            <link>https://medium.com/data-and-beyond/unleashing-openai-build-a-smart-scraping-web-application-with-streamlit-and-generative-ai-45ffb7c38cd3?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ffb7c38cd3</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 20:17:06 GMT</pubDate>
            <atom:updated>2024-11-05T20:17:06.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTuxPshZauTRCUhvHDZsfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Andrea De Santis</a> on <a href="https://unsplash.com/photos/black-and-white-robot-toy-on-red-wooden-table-zwd435-ewb4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>Deploy the web-application on Streamlit Cloud.</strong></p><p>The landscape of software development and data science has evolved significantly over recent years, particularly with breakthroughs in machine learning (ML) and deep learning. Advancements, especially in the realm of transformers, have led to powerful open-source and proprietary algorithms like <strong>LLaMA, BERT, ChatGPT,</strong> and <strong>Claude</strong>. These models have transformed how we approach complex data extraction tasks, opening up new possibilities for automating and simplifying data-intensive processes.</p><p>In this tutorial, we’ll leverage these advancements to build a <strong>Streamlit-based web application</strong> aimed at capturing key property information. This application will extract details like <strong>ratings, locations, reviews, amenities, and pricing</strong> for properties, using <strong>Selenium</strong> for web scraping and <strong>OpenAI API</strong> for data processing and enrichment. Our goal is to create a real-world, <strong>Generative AI (GenAI) application</strong> that facilitates data collection from secondary sources with minimal coding effort.</p><p><strong>Why this Application?</strong></p><p>This application streamlines that process by automating data collection, allowing users to <strong>download a CSV</strong> file containing comprehensive property data. This data can be leveraged in multiple ways:</p><ul><li><strong>Trend Analysis</strong>: Examine property trends, such as how frequently certain properties are sold or listed.</li><li><strong>Market Insights</strong>: Discover amenities and location preferences that appeal to customers.</li><li><strong>Comparative Analysis</strong>: Easily compare pricing across different properties.</li></ul><p>From a Data Scientist’s perspective, this approach requires less manual coding to scrape data specifically for reviews, amenities, locations etc. from websites, as GenAI models can simplify data scraping, parsing and summarization.</p><p><strong>Application Features</strong></p><p>Our <strong>GenAI-based property data extraction tool</strong> follows these key steps:</p><ol><li><strong>Data Extraction with Selenium</strong>: First, we use Selenium to load and capture data from the base URL. By leveraging specific XPath selectors, we identify and capture HTML tags containing the relevant information.</li><li><strong>Parsing HTML with BeautifulSoup</strong>: Using BeautifulSoup, we extract detailed data from these HTML tags, enabling a structured view of the content we need.</li><li><strong>Converting HTML to Text with </strong><strong>html2text</strong>: Next, we utilize the html2text library to convert these HTML elements into plain text. This transformation makes it easier to structure prompts for the <strong>OpenAI API</strong>, allowing us to capture additional property details like <strong>location, reviews, amenities, and listing names</strong> through GenAI-enhanced parsing.</li><li><strong>User Input and Data Structuring with Streamlit</strong>: Streamlit allows users to specify the <strong>city</strong> they want to analyze. Based on this input, we generate a structured <strong>pandas DataFrame</strong> of the data, which users can then download as a CSV file. This provides a user-friendly way to explore specific real estate markets.</li><li><strong>Deploying on Streamlit Cloud with CI/CD</strong>: After building and testing the application locally, we’ll deploy it on Streamlit Cloud. By pushing our source code to GitHub, we establish a streamlined CI/CD pipeline, ensuring that any future changes or updates are automatically integrated and deployed with ease.</li></ol><p>Below are the images of our desired output that we are capturing from the application we have created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8w-qjsCPI897MlzWNUSA8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IX5eOK6fpeb-QANOlLJidw.png" /><figcaption>By Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRD2vNKtaahjoQblP9uPYw.png" /><figcaption>By Author</figcaption></figure><p><strong>Limitations of Web Application</strong></p><p>Currently, the application could be improved by creating a more structured DataFrame specifically for property details such as <strong>Property Name, Reviews,</strong> and <strong>Amenities</strong>. This would ensure a cleaner, more organized dataset, allowing for easier analysis and integration with other systems.</p><p>Below is the link of <strong>github</strong> where you can have the access to the source-code (<a href="https://github.com/Chesta1/AI_webscraper">https://github.com/Chesta1/AI_webscraper</a>) and can access the web-application on <strong>Streamlit.io cloud</strong>(<a href="https://aiwebscraper-mlghp5ubuvbswsseywcxyt.streamlit.app/">https://aiwebscraper-mlghp5ubuvbswsseywcxyt.streamlit.app/</a>). But you would require to specify your own openai api key for working of webapplication.</p><p>I hope you enjoy this aticle and dont forget to provide your feedback. And if you have any questions please connect via linkedin.<a href="https://www.linkedin.com/in/chesta-dhingra-a6aa52110/">https://www.linkedin.com/in/chesta-dhingra-a6aa52110/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ffb7c38cd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/unleashing-openai-build-a-smart-scraping-web-application-with-streamlit-and-generative-ai-45ffb7c38cd3">Unleashing OpenAI: Build a Smart Scraping Web Application with Streamlit and Generative AI</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by Step Tutorial:Extracting and Storing Real Estate Prices Using Python,Selenium and AWS S3]]></title>
            <link>https://medium.com/data-and-beyond/step-by-step-tutorial-extracting-and-storing-real-estate-prices-using-python-selenium-and-aws-s3-367b605d17a0?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/367b605d17a0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Fri, 17 May 2024 17:22:39 GMT</pubDate>
            <atom:updated>2024-05-17T17:22:39.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yd-fXzaT8P-JCUoWH6zLJQ.jpeg" /><figcaption>Image by Freepik</figcaption></figure><p>In today’s data-driven world, the ability to efficiently gather and process information is crucial. Our latest project focuses on two pivotal stages of the <strong>ETL</strong> process — <strong>Extraction</strong> and <strong>Loading</strong> — tailored specifically for real estate data analysis.</p><p><strong>Extraction: Ethical Scraping from Realtor.com</strong></p><p>Our journey begins with the extraction of house pricing data from <em>realtor.com</em>, a leading property listing website. It’s vital to address the ethical considerations of web scraping right from the outset.</p><p>Our approach ensures compliance with the website’s terms of service and respects data privacy regulations. We utilize Python’s <strong>Selenium</strong> library, a robust tool for interacting with web elements, particularly effective with JavaScript-heavy sites.</p><p>Selenium isn’t just about simple data retrieval; it enables us to simulate real-user interactions. For enhanced efficiency and to respect site resources, we also employ a headless browser setup using the <strong>undetected-chrome library</strong>. This setup allows our script to scroll through web pages, mimicking human behavior, and thereby loading more data dynamically, including the crucial <strong>card-price</strong> details (prices of houses) of listed houses.</p><p><strong>Loading: Storing Data Securely on AWS S3</strong></p><p>After successfully extracting data, the next critical step in our data pipeline is securely loading it into an AWS S3 bucket. This process involves several important actions to ensure both security and functionality.</p><ol><li><strong>Setting Up an IAM User</strong>:- Firstly, create an IAM user in AWS. This user will have specific permissions necessary for the tasks at hand, without having unrestricted access to other AWS services. Grant programmatic access to this user via AWS CLI by attaching necessary policies, such as <strong>AWSAdministratorAccess</strong> and <strong>AWSS3FullAccess</strong>. This selective permission approach minimizes security risks while enabling necessary operations.</li><li><strong>Managing User Credentials:-</strong> Post creation, download the user’s credentials in a CSV file for record-keeping. Additionally, generate the <strong>User Access Key ID</strong> and <strong>Secret Access Key</strong> through the security settings of the IAM user. These keys are vital for integrating our <em>Python script</em> with the <em>AWS S3 service</em>, as they authenticate and authorize our actions programmatically.</li><li><strong>Creating the S3 Bucket:- </strong>Log in using the IAM user credentials to create an S3 bucket. When setting up the bucket, carefully adjust its access settings: <strong>1) </strong>Uncheck the option “<strong>Block all public access</strong>” if the application requires external accessibility. However, be cautious with this setting to avoid unintended public access. <strong>2) </strong>Configure a bucket policy to specify access <strong>permissions</strong>. Here is a template for such a policy, which you’ll need to customize with your specific details (IAM user account ID, user name, and bucket name):</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;arn:aws:iam::iamuseraccountID:user/nameofIAMUser&quot;<br>            },<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:DeleteObject&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::bucketname/*&quot;<br>        }<br>    ]<br>}</pre><p>Ensure to replace placeholders with your actual IAM user account ID, IAM user name, and the bucket name.</p><p>With these steps, your AWS IAM account and S3 bucket are ready to securely store the data extracted by your Python script. This setup not only ensures the integrity and confidentiality of your data but also provides a scalable solution for your data storage needs.</p><p><strong>In this section</strong>, we will explore the complete Python script that integrates Selenium for extracting real estate data and subsequently loading it into an AWS S3 bucket. This script is a practical example of how powerful tools can be combined to automate and streamline data collection and storage processes.</p><p><strong>Prerequisites</strong></p><ul><li>Ensure that you have installed Python, Selenium, boto3 (AWS SDK for Python), and other necessary libraries.</li><li>Configure your AWS credentials (as discussed in the previous sections) to allow programmatic access to your S3 bucket.</li></ul><p><strong>Python Script Overview</strong></p><ol><li><strong>Data Extraction Using Selenium</strong>: We’ll extract real estate pricing data from a webpage.</li><li><strong>Data Loading to AWS S3</strong>: We’ll securely upload the extracted data to the S3 bucket.</li></ol><pre>import boto3<br>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.chrome.options import Options<br>from selenium.webdriver.chrome.service import Service<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br><br>def fetch_prices(url):<br>    &quot;&quot;&quot;<br>    Fetches prices from the given URL using Selenium and returns them as a list.<br>    &quot;&quot;&quot;<br>  <br><br>    chr_options = Options()<br>    chr_options.add_experimental_option(&quot;detach&quot;, True)<br>    chr_options.add_experimental_option(&#39;excludeSwitches&#39;, [&#39;enable-logging&#39;])<br><br># Initialize the driver<br>    driver = webdriver.Chrome(service=Service(&#39;C:/Users/Chesta/ETL_real_estate_project/chromedriver.exe&#39;), options=chr_options)<br>    driver.get(url)<br>    WebDriverWait(driver,25)<br>    driver.maximize_window()<br><br>        # Extracting price elements based on their XPATH. Update the XPATH according to your target website.<br>    wait = WebDriverWait(driver,25)<br>    wait.until(EC.presence_of_element_located((By.XPATH, &quot;//*[@data-testid=&#39;card-price&#39;]&quot;)))<br>    prices = driver.find_elements(By.XPATH, &quot;//*[@data-testid=&#39;card-price&#39;]&quot;)<br>    price_list = [price.text for price in prices]<br>    print(price_list)<br><br>    driver.quit()<br>    return price_list<br><br>def upload_data_to_s3(data, bucket_name, file_name):<br>    &quot;&quot;&quot;<br>    Uploads given data to a specified S3 bucket using explicit AWS credentials.<br>    &quot;&quot;&quot;<br>    # Create a session with explicit credentials<br>    session = boto3.Session(<br>        aws_access_key_id=&#39;accesskeyid&#39;,<br>        aws_secret_access_key=&#39;secretaccess&#39;,<br>        region_name=&#39;us-east-1&#39;  # e.g., &#39;us-east-1&#39;<br>    )<br>    # print(&quot;connected with aws account&quot;)<br><br>    # Creating a connection to S3 using the session<br>    s3 = session.client(&#39;s3&#39;)<br>    print(s3)<br>    <br>    # Data needs to be in byte-form to upload to S3<br>    data_string = &#39;\n&#39;.join(data).encode(&#39;utf-8&#39;)<br>    <br>    # Uploading data to the specified bucket under the specified file name<br>    s3.put_object(Bucket=bucket_name, Key=file_name, Body=data_string)<br>    print(&quot;Data uploaded successfully to S3.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # URL of the page you want to scrape<br>    url = &#39;https://www.realtor.com/realestateandhomes-search/Henderson_NV/show-price-reduced/sby-6&#39;<br><br>    # Fetch prices from the website<br>    prices = fetch_prices(url)<br>    <br>    # S3 Bucket and file name where data will be stored<br>    bucket_name = &#39;nameofthebucket&#39;<br>    file_name = &#39;prices.txt&#39;<br>    <br>    # Upload the prices to AWS S3<br>    upload_data_to_s3(prices, bucket_name, file_name)</pre><p>After our data has been uploaded to AWS S3, it’s good practice to verify that everything went as planned. Here are straightforward command line instructions to check the files in your S3 bucket and to copy a file from S3 to your local machine for a sanity check.</p><pre>## to check the list of files in S3 bucket<br>C:\Users\Chesta&gt;aws s3 ls s3://extracted-data-store/prices.txt<br>2024-05-09 01:20:20         71 prices.txt<br><br>## copy the .txt from S3 bucket to local for the sanity check of data is loaded or not<br>C:\Users\Chesta&gt;aws s3 cp s3://extracted-data-store/prices.txt C:\Users\Chesta\Downloads\prices.txt<br><br>##download the prices.txt file from your S3 bucket to the Downloads <br>## directory on your local machine. If the download is successful, you should see a message similar to:<br>download: s3://extracted-data-store/prices.txt to Downloads\prices.txt</pre><p>Hope you had as much fun reading this as I did writing it! Got thoughts, feedback, or just want to chat about it? Drop your comments below — I’d love to hear from you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=367b605d17a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/step-by-step-tutorial-extracting-and-storing-real-estate-prices-using-python-selenium-and-aws-s3-367b605d17a0">Step by Step Tutorial:Extracting and Storing Real Estate Prices Using Python,Selenium and AWS S3</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerize and Deploy a Simple Flask App on AWS Using ECR and ECS]]></title>
            <link>https://medium.com/data-and-beyond/containerize-and-deploy-a-simple-flask-app-on-aws-using-ecr-and-ecs-28b47e3fc2a8?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b47e3fc2a8</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Wed, 15 May 2024 16:36:12 GMT</pubDate>
            <atom:updated>2024-05-15T16:36:12.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOY58ygmuRPQ1s95kIwb2w.png" /></figure><p>In this blog post, we will walk you through the process of creating a simple “Hello World” Flask application, containerizing it using Docker, and deploying it on AWS ECS with ECR. Whether you are a beginner or looking to refine your deployment skills, this step-by-step guide will help you get started with modern application deployment practices.</p><h4>Prerequisites</h4><p>Before we dive in, make sure you have the following prerequisites:</p><ol><li>An AWS account.</li><li>AWS CLI configured on your local machine.</li><li>Docker installed on your local machine.</li><li>Basic knowledge of Flask and Python.</li></ol><h3>Steps for First Simple Flask Deployment</h3><h4>1. Create a Simple Flask Application Printing “Hello-World”</h4><p>Code for the Flask Application; all the files for example <strong>app.py </strong>(containing the code), <strong>Dockerfile</strong>(to dockerize the flask application) and lastly the <strong>requirements.txt </strong>file, these all files should be in one folder.</p><ol><li>Set up your Flask application and save it with the name of <strong>app.py</strong>:</li></ol><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br><br>def hello_world():<br>    return &quot;Hello World&quot;<br><br>if __name__==&#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;,port=80)</pre><p>2. · Dockerize your application via creating the <strong>Dockerfile</strong></p><pre>•#use the python runtime <br>FROM python:3.9.19-slim<br>• <br>• # set the working directory to /app<br>• WORKDIR /app<br>• <br>• # copy the current directory content into the container at /app<br>• COPY . /app<br>• <br>• #install any neede packages specified in requirements.txt<br>• RUN pip install --no-cache-dir -r requirements.txt<br>• <br>• #Make port 80 available to the world outside this container<br>• EXPOSE 80<br>• <br>• #Define the environment variable<br>• ENV NAME=World<br>• <br>• #Run app.py when the container Launches<br>• CMD [&quot;python&quot;,&quot;app.py&quot;]</pre><p>3. Create a requirements.txt file with Flask installed; command would be</p><pre>pip freeze &gt; requirements.txt</pre><p>4. Build the Docker image and run the docker container using below commands</p><pre># build the image<br>docker build -t hello-world-flask <br><br># run the docker command<br>docker run -d -p 4000:80 hello-world-flask <br><br>## now navigate to &#39;http://localhost:4000&#39; to see your Flask app running inside the Docker container.<br><br>## above url will display the flask application.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*UmQZ4Bxq8KXFwWofFRsrtw.png" /><figcaption>By author</figcaption></figure><p>This ensures that our docker container is working absolutely fine on the local server.</p><p>We have successfully containerized the Python Flask app. The next steps involve deploying the Flask application on AWS ECR and ECS.</p><h3>Deploying on AWS Using ECR and ECS</h3><h4>1. Creating the IAM User with Appropriate Policies</h4><p>Before we deploy our Dockerized Flask application on AWS ECS, we need to set up an IAM user with the necessary permissions. This user will have the ability to manage ECS services and interact with ECR. Follow these steps to create the IAM user:</p><p>a. Create a new IAM user and attach the necessary permissions <strong>1)</strong>AdministratorAccess, 2) AmazonEC2ContainerRegistryFullAccess, 3) AmazonECS_FullAccess, 4)AmazonElasticContainerRegistryPublicFullAccess and last is 5) ECS-docker-service (this is the custom inline policy that is attached with theIAM user)</p><pre>## the custom inline policy that needs to be attached <br><br>i. {<br>ii.  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>iii.  &quot;Statement&quot;: [<br>iv.   {<br>v.    &quot;Effect&quot;: &quot;Allow&quot;,<br>vi.    &quot;Action&quot;: [<br>vii.     &quot;ecs:CreateCluster&quot;,<br>viii.     &quot;ecs:DescribeClusters&quot;,<br>ix.     &quot;ecs:ListClusters&quot;,<br>x.     &quot;ecs:DeleteCluster&quot;<br>xi.    ],<br>xii.    &quot;Resource&quot;: &quot;*&quot;<br>xiii.   }<br>xiv.  ]<br>xv. }</pre><p>Now that the IAM user is created, log in with the provided permissions. Search for ECR in the AWS Management Console to create the repository. Follow these steps to create the ECR repository:</p><ol><li>In the General Settings, set the visibility to Private for this app.</li><li>For the repository name, use the same name as the Docker image we created, which is hello-world-flask.</li><li>Click on Create Repository.</li></ol><p>Once the ECR repository is created, we’ll push the Docker image to AWS using the Windows command line. Follow these steps:</p><ol><li>In the Security Credentials section of the IAM user, generate the Access Key ID and Secret Access Key. These will be used for AWS credential configuration using the command aws configure on the command line.</li><li>Ensure you have access to Docker by logging in via the Docker CLI from the command line. It will ask for your user credentials (Username and Password) and, upon successful authentication, will display “Login Succeeded.”</li><li>Navigate to the folder containing your application, including the Dockerfile and requirements.txt.</li><li>Click on the ECR repository you created and view the Push Commands. Follow the commands provided by ECR to push your Docker container to AWS ECR.</li></ol><p>Once the Docker container is successfully pushed to ECR, you will see an image tag with the Image URI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hlCIZFasAqn-jIlkMRj2aQ.png" /><figcaption>By Author</figcaption></figure><p>Now, for the third and final part of deploying and running the Docker containerized Flask application image on an AWS server, we’ll use <strong>ECS</strong> (<strong>Elastic Container Service</strong>). Follow these steps:</p><ol><li>Create the <strong>Cluster</strong>: Use AWS Fargate as the infrastructure to create the cluster.</li><li>Create <strong>Task Definitions</strong>: 1) In <strong>Task</strong> <strong>Definitions</strong>, create a new task using AWS Fargate. 2) Provide the Image URI that was created during the ECR step for the Docker container. 3) Leave the rest of the configuration as default or as it is in the task definition.</li><li>Run the <strong>Task</strong>: 1) Click on the cluster you created (e.g., demo-cluster2), 2) Navigate to the Tasks tab and click on the task ID, which is a unique alphanumeric value. This will open a new page with tabs like Configuration, Logs, Networking, Volumes, and Tags, 3) Click on the <strong>Networking tab</strong>, then on “<em>Security Groups”</em>.</li><li><strong>Configure Security Groups</strong>: You will be directed to the Security Groups page. In the Inbound Rules section, click on Edit Inbound Rules and add a rule as shown below, then save it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ow5wBtuTk8mExfRrKX0kNw.png" /><figcaption>By Author</figcaption></figure><p>By following these steps and using the<strong> public IP</strong>, you will be able to see the “Hello World” page running on your AWS server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Nd3OZ4mFgC9WJr30PkMPiQ.png" /><figcaption>By Author</figcaption></figure><p>I hope you enjoyed this detailed, comprehensive article on deploying a Dockerized Flask web application on AWS using ECR and ECS. Please follow for more detailed articles and feel free to provide your feedback</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b47e3fc2a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/containerize-and-deploy-a-simple-flask-app-on-aws-using-ecr-and-ecs-28b47e3fc2a8">Containerize and Deploy a Simple Flask App on AWS Using ECR and ECS</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data Structures to Science: DSA in Data-Driven World.]]></title>
            <link>https://medium.com/data-and-beyond/from-data-structures-to-science-dsa-in-data-driven-world-d5a7f093a300?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a7f093a300</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 06:37:31 GMT</pubDate>
            <atom:updated>2024-04-01T06:37:31.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiqy11RfyotD5dn3bEOQsg.jpeg" /></figure><p>In this DSA series we venture beyond traditional interview questions to explore the foundational concepts of Data Structures and Algorithms and their practical application on the real datasets. I have designed this immersive journey into understanding how DSA can be powerful tool in hands of Data Scientist.</p><p>By integrating DSA principles with hands-on dataset analysis, aiming to provide a dual learning experience.</p><p>Let’s start our journey via providing a brief introduction towards data structures and algorithms followed by its implementation on the house pricing dataset.</p><ol><li>First Data Structure and Algorithm that we’ll be discussing is the Merge Sort. This is used for sorting the arrays or lists efficiently. It divide the array into smaller parts, sort those parts and then merge them together. Merge Sort algorithm is based on divide-and-conquer algorithm. Based on the dataset that we have; we’ll apply the merge sort algorithm on <strong>SalesPrice</strong> column of the dataset. Below is code for the same.</li></ol><pre>## first import the pandas library to read the dataset<br>import pandas as pd<br>data = pd.read_csv(&quot;train.csv&quot;)<br><br>## turn series into list<br>a=data[&#39;SalePrice&#39;].tolist()<br><br>## now create a merge sort algorithm that will merge the sort arrays<br><br>def merge(arr,l,mid,r):<br>  left = arr[l:mid+1]<br>  right = arr[mid+1:r+1]<br>  m = len(left)<br>  n = len(right)<br>  i=0<br>  j=0<br>  k=l<br>  while i&lt;m and j&lt;n:<br>    if left[i]&lt;right[j]:<br>      arr[k] = left[i]<br>        i+=1<br>     else:<br>        arr[k]=right[j]<br>        j+=1<br>     k+=1<br>   while i&lt;m:<br>      arr[k]=left[i]<br>      i+=1<br>      k+=1<br>   while j&lt;n:<br>      arr[k]=left[j]<br>      j+=1<br>      k+=1<br><br><br>def merge_sort(arr,l,r):<br>  if l&lt;r:<br>    mid=(l+r)//2<br>    merge_sort(arr,l,mid)<br>    merge_sort(arr,mid+1,r)<br>    merge(arr,l,mid,r)<br><br><br>## now we have created the merge sort and did the sorting of the array in the dataset<br>## itself.<br>## the first merge is doing the comparison of the sorting values that has been<br>## created by the merge_sort functionand then creating a whole sorted list.<br><br>## to do the implementation of the same on the dataset or the list<br>## that we have created that is &quot;a&quot;<br><br>mergesort(a, 0, len(a)-1)<br><br><br>a[:5]<br><br>## below is the output result of<br># [34900, 35311, 37900, 39300, 40000] </pre><p>2. After sorting an array or dataset using the merge sort algorithm, the next step often involves searching for specific elements within this sorted array. The <strong>binary search algorithm,</strong> another example of a divide-and-conquer strategy, is ideally suited for this task. However, it’s crucial to note that binary search requires the array to be sorted beforehand, making it a perfect follow-up to merge sort</p><pre>## create a binary function that will divide the data and then find the elements<br>## provided by the user<br><br>def find_elements(arr,low,high):<br>  mid = (low+high)//2<br>  if low&gt;high:<br>    return -1<br>  if arr[mid]==val:<br>    return mid<br>  elif arr[mid]&lt;val:<br>    return find_elements(arr,mid+1,high)<br>  else:<br>    return find_elements(arr,low,mid-1)<br><br><br>## above function will find the index of the elemnts.<br>## there might be chances that the same value appeared more than once in the dataset<br>## thus to find the frequency of it we create one more function<br>## that helps in finding all the occurrences<br><br>def find_occurrences(arr,val,index):<br>  if index==-1:<br>  occurrences =[index]<br>  left = index-1<br>  while left&gt;=0 and arr[index]==val:<br>    occurrences.append(left)<br>    left-=1<br>  while right &lt; len(arr) and arr[index]==val:<br>    occurrences.append(right)<br>    right+=1<br>  return sorted(occurrences)<br><br># now we can apply both the functions first to find the desired element<br>## and second to find the occurrence of the elements appeared in the list<br><br>high =len(sale_prices)<br>low=0<br>val = 200000<br><br>index = find_elements(a, val, low, high)<br>all_occurrences = find_occurrences(a, val, index)<br>print(all_occurrences)<br><br>## this will provide below results<br># [1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032]</pre><p>3. Ready to mix a little DSA magic with real-world data? We’re zooming in on how to find the shortest paths, not just on maps, but in data columns! This cool trick will show you the power of data structures and algorithms in action, making sense of data in ways that are both super useful and kinda fun. It’s like finding the shortest line at the grocery store but for numbers. Let’s dive in!</p><pre>class solution:<br>  def min_dist(self,arr,a,b,n=None):<br>      if n is None:<br>          n= len(arr)<br>       index_a = None<br>       index_b = None<br>       min_distance = float(&quot;inf&quot;)<br><br>      for i in range n:<br>          if arr[i]==a:<br>              index_a = i<br>               if index_b is not None:<br>                  current_dist = abs(index_a-index_b)<br>                  if current_dist&lt;min_distance:<br>                     min_distance = current_distance<br>           if arr[i]==b:<br>              index_b = i<br>              if index_a is not None:<br>                  current_dist = abs(index_b-index_a)<br>                  if current_dist &lt; min_distnce:<br>                     min_distnce = current_dist<br>      if index_a is None or index_b is None:<br>           min_distance =-1<br>      else:<br>          if min_distance==float(&quot;inf&quot;):<br>              min_distance =-1<br>      return min_distance<br><br>min_dist_dataset = solution().min_dist(sale_prices,a=200000, b=250000)<br>min_dist_dataset</pre><p>Up next in our DSA meets Data Science adventure, we’ll tackle even more mind-bending concepts and dive into algorithms that’ll seriously level up the logic and coding game. Stay tuned, because we’re just getting started on this journey to become data wizards together!</p><p>Hope you had as much fun reading this as I did writing it! Got thoughts, feedback, or just want to chat about it? Drop your comments below — I’d love to hear from you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a7f093a300" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/from-data-structures-to-science-dsa-in-data-driven-world-d5a7f093a300">From Data Structures to Science: DSA in Data-Driven World.</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Words: The Magic of Text Genertaion with Transformers]]></title>
            <link>https://medium.datadriveninvestor.com/revolutionizing-words-the-magic-of-text-genertaion-with-transformers-1b6bc34e1f03?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b6bc34e1f03</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 08:50:32 GMT</pubDate>
            <atom:updated>2024-03-28T09:03:58.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPAz5z2oBsy6H4u971s00w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jonathan Kemper</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-computer-screen-with-a-purple-background-N8AYH8R2rWQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Unlocking the Future: A dive into Theory and Practice Behind AI’s the most innovative mind.</p><p>In our recent series where we delve and explored the recent <a href="https://medium.com/data-and-beyond/find-the-trending-topics-in-data-science-and-software-development-using-ml-python-aa52bcad2e7a">trends in data science and machine learning</a>, culminating hands-on demonstration of <a href="https://medium.com/datadriveninvestor/various-text-generating-techniques-using-ml-and-lstm-networks-8173a6029a29">text generation </a>using techniques like TF-IDF and LSTM.</p><p>As we continue our series, we’ll delve into the cutting-edge and increasingly sophisticated techniques of text-generation, specifically through the use of <strong><em>Transformers. </em></strong>Our focus will be on generating the text data, includes titles via using dataset name <a href="https://www.kaggle.com/datasets/chestadhingra/trends-in-data-science-and-software-development">Trends in Data Science and Software Development</a>.</p><p>A significant limitation of text generation using LSTMs is their struggle to retain the context of the words in longer sentences. <strong>Transformers </strong>are effectively able to overcome this challenge by employing an attention mechanism that meticulously evaluates the relevance of each word in context of longer sentences and ensures a comprehensive understanding of the text data.</p><p>Mentioning significant pointers of Transformers that helps in providing a high level understanding of its architecture and its Core Concepts.</p><ol><li>They possess the ability to process data in parallel, meaning an entire sentence can be put into the model at once. This parallelization allow encoder to efficiently analyze each word simultaneously,enhancing model’s effectiveness. Thanks to this parallel processing capability they are highly scalable, which makes them a perfect candidate for handling large datasets and complex language modeling tasks.</li><li>The Transformer model is structured into encoder and decoder sections, each comprising six layers. Each encoder layer features a <strong>multi-head attention</strong> mechanism and a feed-forward layer. In contrast, the decoder layers are equipped with two types of attention mechanisms: masked multi-head attention and standard multi-head attention, in addition to a feed-forward layer. This architecture enables the model to effectively process and generate language sequences by focusing on different aspects of the input data. In addition to that <strong>masked multihead attention</strong> layer prevents the decoder from peeking at future tokens, ensuring that predictions for a position can only depends on known outputs.</li><li>Words are fed into the model as embeddings, which are vector representations of the text data. This format allows for the efficient processing of language. During parallelization, the multi-head attention layer in the encoders facilitates the exchange of information between words. This process enables the model to assess and understand the relevance and relationship of each word to others in the sequence.</li><li>In the transformers we do have the concept of <strong>positional encoding. </strong>Since Transformers do not process data sequentially, they use positional encodings to understand the order of words in a sentence. This is crucial for maintaining the sequence’s meaning, as the order of words can change the intended message.</li><li>Normalization and Skip connections:<strong> — </strong>These components help stabilize the learning process. Normalization adjusts the activations to have a mean of zero and a standard deviation of one, helping to prevent the vanishing or exploding gradient problem. Skip connections, also known as residual connections, allow parts of the input to bypass certain layers, which helps the network learn more effectively by mitigating the risk of information loss.</li></ol><p>Transformers have markedly revolutionized several domains, with their impact on machine translation standing out as particularly profound. Models like BERT and GPT-3 have blurred the lines between machine-generated and human translations, showcasing an unprecedented level of linguistic understanding.</p><p>Now, let’s explore the practical application of Transformers by diving into a project that utilizes a trending titles dataset from <a href="https://www.kaggle.com/datasets/chestadhingra/trends-in-data-science-and-software-development">Kaggle</a>. This endeavor not only highlights the versatility of Transformers in generating engaging text but also offers valuable insights into the nuances of their implementation.</p><p>In this project, we’ve successfully implemented Transformer models and fine-tuned them to generate text. However, we’ve encountered a challenge regarding the generated text’s quality, which has not consistently met our high standards. This issue may stem from the limited size of the dataset or from an insufficient number of training epochs. Both factors are crucial in determining the model’s ability to learn and generate high-quality, contextually appropriate text.</p><p>To address this limitation, we’re considering expanding our dataset and increasing the number of epochs for training. By doing so, we aim to enhance the model’s exposure to diverse linguistic patterns and contexts, thereby improving the quality of the generated text. This approach underscores the importance of thorough dataset preparation and adequate training in the successful application of Transformer models.</p><p>Diving deeper into the practical aspects of Transformer models and exploring the intricacies of text generation, the complete implementation, along with the fine-tuning process, is detailed in our comprehensive <a href="https://github.com/Chesta1/nlp/blob/main/Text_generation_finetuning.ipynb">notebook</a>.</p><p>I hope you found this article insightful.For more such content, follow me on Medium.</p><p>Your feedback and engagement are always appreciated.</p><p><em>References</em></p><h4><a href="https://www.youtube.com/watch?v=_UVfwBqcnbM&amp;t=574s"><em>Transformers for beginners | What are they and how do they work</em></a></h4><ul><li><a href="https://jalammar.github.io/illustrated-transformer/">The Illustrated Transformer</a></li><li><a href="https://doi.org/10.48550/arXiv.1706.03762">Attention Is All You Need</a></li></ul><h4><a href="https://www.youtube.com/watch?v=qaWMOYf4ri8&amp;t=71s">What are Transformer Models and how do they work?</a></h4><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>DDI Services: <a href="https://linktr.ee/datadriveninvestor">https://linktr.ee/datadriveninvestor</a></p><p>Featured Articles:</p><ul><li><a href="https://www.datadriveninvestor.com/2024/03/20/accelerating-success-through-the-singapore-fund-asset-management-platform/">Introducing Singapore&#39;s Fund Platform | DataDrivenInvestor</a></li><li><a href="https://www.datadriveninvestor.com/2024/03/26/singapore-unveiling-a-tapestry-of-possibilities-and-global-connections/">Singapore: Unveiling a Tapestry of Possibilities and Global Connections | DataDrivenInvestor</a></li></ul><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b6bc34e1f03" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/revolutionizing-words-the-magic-of-text-genertaion-with-transformers-1b6bc34e1f03">Revolutionizing Words: The Magic of Text Genertaion with Transformers</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Various Text Generating Techniques using ML and LSTM Networks]]></title>
            <link>https://medium.datadriveninvestor.com/various-text-generating-techniques-using-ml-and-lstm-networks-8173a6029a29?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8173a6029a29</guid>
            <category><![CDATA[text-generation]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 05:59:48 GMT</pubDate>
            <atom:updated>2024-02-20T06:12:49.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQ9-QXMmmrVxqdwlTnzGDA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@micahboswell?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Micah Boswell</a> on <a href="https://unsplash.com/photos/handwritten-text-00nHr1Lpq6w?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In our previous article, we delved into the process of data collection and explored how machine learning techniques, such as Latent Dirichlet Allocation (LDA), can uncover the latest trends within the tech and data science industries.</p><p>Continuing from where we left off, this article will shift focus towards advanced natural language processing (NLP) techniques. Our aim is to demonstrate how these methods can not only generate engaging titles but also provide recommendations for article titles that align with current industry trends.</p><p>This article will delve into three sophisticated techniques that stand at the forefront of text generation:</p><ol><li><strong>TfIDF</strong>: The Term Frequency-Inverse Document Frequency (TF-IDF) technique is a pivotal tool in natural language processing, especially for generating text in a heuristic manner. It excels in identifying significant keywords within a document by not only considering the frequency of a word <em>t</em> in a given document <em>d</em> but also its distribution across a set of documents <em>D</em>. The mathematical formulation of TF-IDF, expressed as <strong>tf-idf(<em>t</em>,<em>d</em>,<em>D</em>)=tf(<em>t</em>,<em>d</em>)⋅idf(<em>t</em>,<em>D</em>)</strong>, plays a crucial role in the effective selection of keywords. This methodology underscores the importance of a word based on its frequency within the document and its uniqueness across the entire document corpus. By doing so, <strong>TF-IDF</strong> provides a dual focus: it values words that are<strong> common</strong> within a particular document yet <strong>rare</strong> in others, thereby highlighting terms that are uniquely informative about the document’s content. This nuanced approach ensures that the keywords identified are not only relevant but also carry a significant weight in representing the document’s theme, making it an invaluable technique for generating contextually rich and focused text titles.</li><li><strong>Word2Vec: </strong>Word2Vec is a popular and influential technique in the field of natural language processing (NLP) that maps words to high-dimensional vector spaces, effectively translating words into numerical form so that machines can understand them. It starts by processing of large corpus of text, word by word, considering the context of each word. Size of “context window” can vary based on the model configuration. First model will initialize a random vector, through training process it will adjust the vectors. It does have two architectures one is <strong>CBOW (</strong>predict words based on the context<strong>) </strong>and second is <strong>Skip-Gram </strong>it uses the word to predict its surrounded context (this is effective for learning representations of the rare words).</li><li><strong>LSTM Long Short Term Memory:- </strong>This is a Recurrent Neural Network, in which it process the data one step at a time, maintaining a hidden state and a cell state throughout the sequence. For each timestep LSTMs update its state based on the current input, previous hidden state and the previous cell state, applying its gates to manage information flow. based on its architecture, it can learn which data ina sequence is important to remember and which can be forgotten. In this <strong>Backpropagation Through Time </strong>is used where gradients are propagated through timesteps, allowing the network to update its weights.</li></ol><p>Employing the methodologies of TF-IDF, Word2Vec, and LSTM, I successfully executed text generation tasks with considerable efficacy. This approach has not only enabled the generation of fitting article titles but has also significantly enhanced my natural language processing (NLP) capabilities. Through this process, I have been able to produce quality results in response to input queries. The practical application of these advanced techniques has proven instrumental in both refining my NLP skills and in achieving the desired outcomes in text generation based on specific user inputs.</p><p>To illustrate the practical application of TF-IDF, Word2Vec, and LSTM in text generation, below is an abstract of the code developed for this project. The code demonstrates the integration of these NLP techniques to generate article titles and process input queries effectively. For a deeper dive into the implementation and to access the full source code, please visit the <a href="https://github.com/Chesta1/nlp"><strong>GitHub repository.</strong></a></p><p>The project is structured to first preprocess the input data using TF-IDF to identify key terms, then employ Word2Vec to generate word embeddings that capture semantic meanings. Finally, an LSTM model is trained to generate text based on the embeddings. Instructions on how to set up and run the code are provided in the repository, along with examples and a guide for navigating the codebase.</p><p>Your feedback and contributions to the project are welcome, as we aim to continuously improve and refine our approach to NLP tasks.</p><pre>#clean the data for that simple_clean_text is defined<br><br>def simple_clean_text(x):<br>    x = x.lower()<br>    x = re.sub(&#39;[^a-z]&#39;,&quot; &quot;,x)<br>    x = re.sub(&#39; +&#39;,&#39; &#39;,x).strip()<br>    words = x.split()<br>    <br>    lemmatizer = WordNetLemmatizer()<br>    words =[lemmatizer.lemmatize(i) for i in words]<br><br>    words = [w for w in words if w not in STOPWORDS]<br>        <br>        <br>    return &quot; &quot;.join(words)<br><br>##applying the function on the text data<br><br>combine_df2[&#39;text&#39;] = combine_df2[&#39;text&#39;].apply(lambda x: simple_clean_text(x))<br><br>## utilizing the TfIDF and cosine similarity the model helps in providing the <br># recommendation of the titles that can be used based on the query that is been asked<br># by the user; based on the concept of cosine similarity<br><br><br># Vectorize the titles using TF-IDF<br>tfidf_vectorizer = TfidfVectorizer(stop_words=&#39;english&#39;)<br>tfidf_matrix = tfidf_vectorizer.fit_transform(combine_df2[&#39;text&#39;])  # Assuming &#39;title&#39; is the column name<br><br># Function to find similar titles based on a query<br>def find_similar_titles(query, top_n=5):<br>    query_tfidf = tfidf_vectorizer.transform([query])<br>    cos_similarities = cosine_similarity(query_tfidf, tfidf_matrix).flatten()<br>    similar_indices = cos_similarities.argsort()[-top_n:][::-1]<br>    <br>    similar_titles = combine_df2[&#39;text&#39;].iloc[similar_indices]<br>    return similar_titles<br><br># Example Query<br>query = &quot;ai models&quot;  # Replace with your query<br>similar_titles = find_similar_titles(query)<br>print(&quot;Titles similar to the query:&quot;, similar_titles)<br><br>## results for this would appear somewhat like this<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atyeGzd83Nygk7sRHHaSTQ.png" /></figure><p><strong>Second is word2vec</strong></p><pre><br>## after cleaning the data<br>from gensim.models.word2vec import Word2Vec<br><br>#create the model<br><br>word2vec_model = Word2Vec(min_count=0,workers=8,vector_size=15)<br><br>#prepare the vocab<br><br>word2vec_model.build_vocab(combine_df2[&#39;text&#39;].values)<br><br>#train the model<br><br>word2vec_model.train(combine_df2[&#39;text&#39;].values,total_examples=word2vec_model.corpus_count,epochs=30)<br><br>model_wv_contents = {<br>    &quot;Vocabulary Size&quot;: len(word2vec_model.wv),<br>    &quot;Sample Words&quot;: word2vec_model.wv.index_to_key[:10],  # First 10 words in the vocabulary<br>    &quot;Vector for a Sample Word (&#39;data&#39;)&quot;: word2vec_model.wv[&#39;data&#39;] if &#39;data&#39; in word2vec_model.wv else &quot;Not in Vocabulary&quot;<br>}<br><br>model_wv_contents<br><br>query_sentence = &quot;machine learning trends&quot;<br><br>def average_vector(sentence,model):<br>    words = sentence.split()<br>    # print(words)<br><br>    word_vectors = [model.wv[word] for word in words if word in model.wv]<br><br>    if len(word_vectors)==0:<br>        return np.zeros(model.vector_size)<br>    else:<br>        return np.mean(word_vectors,axis=0)<br><br>query_vector = average_vector(query_sentence,word2vec_model)<br>title_vectors = [average_vector(&quot; &quot;.join(row), word2vec_model) for row in combine_df2.text]<br><br>similarities =[cosine_similarity([query_vector], [title_vector])[0][0] for title_vector in title_vectors]<br><br>titles_with_similarities = list(zip(combine_df2[&#39;text&#39;],similarities))<br><br>sorted_titles = sorted(titles_with_similarities,key=lambda x: x[1],reverse=True)<br><br>for title in range(len(sorted_titles[:5])):<br>    print(f&#39;{&quot; &quot;.join(sorted_titles[title][0])}: {(sorted_titles[title][1])}&#39;)</pre><p>Output of the above <strong>word2vec</strong> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZVcVWG275pMzjQbgXQNUg.png" /></figure><p>With the help of deep learning using <strong>LSTM </strong>methodology we can generate the text via providing the query from the user and it has privided some decent good results. Below is the code for the same.</p><pre>tokenizer = Tokenizer()<br><br># in the function we are generating the tokens and then creating the input sequences <br># and finding how many total words are in the dataset.<br><br>def get_the_seq(corpus):<br>    tokenizer.fit_on_texts(corpus)<br>    total_words = len(tokenizer.word_index)+1<br><br>    input_seq=[]<br><br>    for line in corpus:<br>        token_list = tokenizer.texts_to_sequences([line])[0]<br>        for i in range(1,len(token_list)):<br>            n_gram_sequence = token_list[:i+1]<br>            input_seq.append(n_gram_sequence)<br>    <br>    return input_seq, total_words<br><br># generate the padded sequences<br>def generated_padded_sequence(input_sequences):<br>    max_sequences_len = max([len(x) for x in input_sequences])<br><br>    input_sequences = np.array(pad_sequences(input_sequences,maxlen=max_sequences_len,padding=&#39;pre&#39;))<br><br>    predictors, label = input_sequences[:,:-1],input_sequences[:,-1]<br>    label = ku.to_categorical(label,num_classes=total_words)<br>    return predictors, label, max_sequences_len<br><br>predictors,label,max_seq_len = generated_padded_sequence(input_sequences)<br><br>## now build the model and print the model summary<br><br>def create_model(max_sequence_len, total_words):<br>    input_len = max_sequence_len - 1<br>    model = Sequential()<br>    <br>    # Add Input Embedding Layer<br>    model.add(Embedding(total_words, 10, input_length=input_len))<br>    <br>    # Add Hidden Layer 1 - LSTM Layer<br>    model.add(LSTM(100))<br>    model.add(Dropout(0.1))<br>    <br>    # Add Output Layer<br>    model.add(Dense(total_words, activation=&#39;softmax&#39;))<br><br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;)<br>    <br>    return model<br><br>model = create_model(max_seq_len, total_words)<br>model.summary()<br><br># fit the model<br><br>model.fit(predictors, label, epochs=100, verbose=5)<br><br># for generating the text we will be using the function generate_text<br><br>def generate_text(seed_text, next_words, model, max_sequence_len):<br>    for _ in range(next_words):<br>        token_list = tokenizer.texts_to_sequences([seed_text])[0]<br>        token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding=&#39;pre&#39;)<br>        predicted = model.predict(token_list, verbose=0)<br>        print(predicted)<br>        predicted_class = np.argmax(predicted,axis=1)<br>        <br>        output_word = &quot;&quot;<br>        for word,index in tokenizer.word_index.items():<br>            if index == predicted_class:<br>                output_word = word<br>                break<br>        seed_text += &quot; &quot;+output_word<br>    return seed_text.title()<br><br>print (generate_text(&quot;AI and LLM&quot;, 5, model, max_seq_len))<br><br>##below is the output</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*XiXPEJwO-FBHjIp618jlqg.png" /></figure><p>I hope you found this article insightful and for more such content, follow me on Medium. Your feedback and engagement are always appreciated.</p><p><em>References</em></p><p><a href="https://www.tandfonline.com/doi/full/10.1080/03081079.2017.1291635">https://www.tandfonline.com/doi/full/10.1080/03081079.2017.1291635</a></p><p><a href="https://jalammar.github.io/illustrated-word2vec/">The Illustrated Word2vec</a></p><p><em>LSTM networks explained by ritvikmath</em></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8173a6029a29" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/various-text-generating-techniques-using-ml-and-lstm-networks-8173a6029a29">Various Text Generating Techniques using ML and LSTM Networks</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the Trending Topics in Data Science and Software Development using ML & Python!!]]></title>
            <link>https://medium.com/data-and-beyond/find-the-trending-topics-in-data-science-and-software-development-using-ml-python-aa52bcad2e7a?source=rss-d63e0ab3862e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa52bcad2e7a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-collection]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Chesta Dhingra]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 06:55:50 GMT</pubDate>
            <atom:updated>2024-01-11T06:55:50.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TR0Dd9FDR07pH024pqPJ7A.jpeg" /><figcaption>Credits to Joshua Hoehne Unsplash</figcaption></figure><p><strong>Harnessing Selenium, Python and ML for Dynamic Insights into Tech World’s Pulse.</strong></p><p>Three major reasons behind doing this research or project is to</p><ol><li><strong>Identify Community Focus:- </strong>Analyzing the latest trends from past 30 days, that highlights the area in which data science and software development communities are focusing on.</li><li><strong>Enhancing the Python Skills:- </strong>The project serve as a practical platform for enhancing my python coding abilities.</li><li><strong>Advancing NLP Competency:- </strong>Lastly via applying the machine and deep learning principles on this endeavour will helps in elevating my maneuver in Natural Language Processing.</li></ol><p>With this overview, I trust you have a solid understanding of project’s objectives and it’s significance in evolving world of Data Science. Now let’s not delay any further.</p><p>It’s time to delve into the practical journey of this research, from meticulous collection of data using selenium and the analyse the patterns and drive the insights using advanced machine learning algorithms.</p><p><strong>Collecting Data</strong></p><p>Starting with the project, collecting and cleaning the data is always a hard part. Here I took the advantage of one of the popular libraries of python named <strong>Selenium</strong> to extract the data from various prominent data science blogs. Importantly, this task was conducted with a steadfast commitment to the ethical guidelines governing web scraping. Three major elements which are required for the data are <strong>Article’s Title, Date </strong>and <strong>Subtitle. </strong>We can also include the name of the sites if it is required for doing site wise analysis. First, we’ll be defining the resources from which we’ll be collecting the data</p><pre>towards_ds_url = &quot;https://towardsdatascience.com/latest&quot;<br><br>data_science_central_url = &quot;https://www.datasciencecentral.com/articles/&quot;<br><br>levelup_url = &quot;https://levelup.gitconnected.com/latest&quot;</pre><p>Great!! We have define our resources now let’s start collecting the data via defining the elements which are relevant for doing the analysis sepecifically for the latest 30 days.</p><p>The pivotal tool which act as an intermediate between the python and browser is the diver. The most common browser is chrome so I’ll be using the chrome driver that seamlessly connects my python <strong>selenium</strong> library with the browser and browser automate the data collection process.</p><pre>&quot;&quot;&quot;defining the functions to setup the driver, parse the dates<br>and scrape the sites to collect the data<br>&quot;&quot;&quot;<br><br>def setup_driver(chrome_service, chrome_options): #function to setup the driver based on the browser you are using<br>    driver = webdriver.Chrome(service=chrome_service, options=chrome_options)<br>    driver.maximize_window()<br>    return driver<br><br><br># each blog site has its own way of storing the dates based on that we have create two different<br># parse date functions<br>def parse_towards_ds_date(date_element):<br>    date_string = date_element.get_attribute(&#39;datetime&#39;)[:-1]  # Adjust attribute as needed<br>    return datetime.fromisoformat(date_string)<br><br>def parse_data_science_central_date(date_element):<br>    date_string = date_element.get_attribute(&#39;content&#39;)  # Adjust attribute as needed<br>    return datetime.strptime(date_string, &quot;%Y-%m-%d&quot;)<br><br># finally we&#39;ll be creating the logic to collect the data from all three different resources.<br>def scrape_articles(driver, url, xpath_title, xpath_subtitle,xpath_date, parse_date, days_back=30, scroll_pause_time=30):<br>    data = []<br>    end_date = datetime.now() - timedelta(days=days_back)<br>    try:<br>        driver.get(url)<br>        html = driver.find_element(By.TAG_NAME, &quot;html&quot;)<br>        while True:<br>            titles = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.XPATH, xpath_title)))<br>            subtitles = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.XPATH, xpath_subtitle)))<br>            date_elements = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.XPATH, xpath_date)))<br><br>            for title, subtitle,date_element in zip(titles, subtitles,date_elements):<br>                article_date = parse_date(date_element)  # Pass the entire element to the parse_date function<br>                 if article_date &lt; end_date:<br>                    <br>                    raise StopIteration<br>                   <br>                 if not any(d[&#39;title&#39;] == title.text for d in data):<br>                    print(f&quot;Title: {title.text}, Date: {article_date}&quot;)<br>                    data.append({&quot;title&quot;: title.text, &quot;date&quot;: article_date,&#39;SubTitle&#39;: subtitle.text if subtitle.text else None})<br><br>            html.send_keys(Keys.PAGE_DOWN)<br>            time.sleep(scroll_pause_time)<br>    <br>    except Exception as e:<br>        logging.error(f&quot;An error occurred: {e}&quot;)<br>    finally:<br>        driver.quit()<br>    return data</pre><p><strong>Data Cleaning</strong></p><p>Once data is harvetsed from different resources, our focus will be on cleaning the data. It is one of the most crucial steps when we are dealing with unstructured data specifically in context of Natural Language Processing.</p><p>Data that we have collected is enriched with information but also contains some numeric as well as non-alpha numeric characters. This information is not relevant in context of the research or project that we are working on. To refine our dataset we remove these numeric and non-alphanumeric characters, also we’ll be eleminating the punctuations as well as stopwords- those common words which are offering little to no value on our trend analysis.</p><p>This cleansing step is not merely tidying up the data; it’s about sculpting into a form that’s primed for insightful analysis.</p><pre>&quot;&quot;&quot;<br>Defining the function that will clean the title and subtitle columns of the dataset.<br>First standardize the data via lowering all the uppercase character to lower.<br>Eleminating the non-alpha values.<br>Removing the trailing spaces.<br>and lastly tokenizing the words using split method.<br>&quot;&quot;&quot;<br><br>def simple_clean_text(x):<br>    x = x.lower()<br>    x = re.sub(&#39;[^a-z]&#39;,&quot; &quot;,x)<br>    x = re.sub(&#39; +&#39;,&#39; &#39;,x).strip()<br>    words = x.split()<br>    return &quot; &quot;.join(words)<br><br># applying the function on the dataset after combining all the rows of the data<br># that we have collected<br><br>combine_data2[&#39;title&#39;] = combine_data2[&#39;title&#39;].apply(lambda x: simple_clean_text(x))<br>combine_data2[&#39;SubTitle&#39;] = combine_data2[&#39;SubTitle&#39;].apply(lambda x: simple_clean_text(x))<br>combine_data2.head()</pre><p>Data is collected and cleaned. Now, it’s time for real exciting exercise where we are leveraging the power of advanced Machine Learning algorithms to pinpoint the areas that are garnering the significant attention in data science and software development communities.</p><p><strong>Trend Analysis</strong></p><p>While doing the analysis we’ll be taking the advantage of python <strong>scikit-learn </strong>library. As computer understands only numbers thus it is quintessential to convert text of documents to a matrix of token counts using the <strong>CountVectorizer </strong>from scikit-learn library.</p><pre><br>no_features =1000 #max number of words to be consider in the analysis<br>no_topics = 10 #number of topics to consider <br>no_top_words = 10 #number of topics to display for each topic<br><br>tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=no_features,stop_words=&quot;english&quot;)<br><br>#after defining the vectorizer we will fit it on the data that we have cleaned<br>tf = tf_vectorizer.fit_transform(combine_data2[&#39;title&#39;])<br>tf_feature_names = tf_vectorizer.get_feature_names_out()</pre><p>Once the text is converted into matrix, we’ll be implementing the <strong>Latent Dirichlet Allocation (LDA) </strong>a statistical model that is used to extract abstract topics within a collection of documents. The main algorithm used to infer hidden structure in LDA are Variational Bayes and Gibbs Sampling.</p><p>At the core LDA is actually a bayesian probabilstic model, it makes an assumption that there are latent or hidden variables that determine the observable data (words in document).</p><p>For example, we have large collection of news article from sports, politics to entertainment and we need to organize them in an order. LDA is a statistical method that helps you to organize them.</p><p>First it makes an assumption that each document is a mixture of various topics and each topic is a mixture of various words. Then it makes random guesses about the topic composition of each document and word composition of each topic.Iteratively it will improve the guesses about both document-topic and topic-word compositions. <strong>Bayesian Approach </strong>comes in when it updates the beliefs based on new evidences. Everytime LDA sees a word in a document, it updates its belief about the composition of that document and relevant topics.</p><p>As we get a basic understanding of LDA, we can implement it on our CountVectorizer transformed data using <strong>LatentDirichletAllocation() </strong>function from the scikit-learn.</p><pre><br>lda = LatentDirichletAllocation(n_components=no_topics,max_iter=5,learning_method=&#39;online&#39;,learning_offset=50,random_state=0).fit(tf)<br>&quot;&quot;&quot;<br>model is fitted on the dataset and now we want to see the top 10 components of each <br>abstract topic that is hidden using LDA from the documents or the titles that we have collecetd.<br>&quot;&quot;&quot;<br><br># now to extract the features or the top n words for each document we&#39;ll <br># define the function that will take model, feature_names and no_words as parameter.<br><br>def display_topics(model, feature_names, no_top_words):<br>    topics = {}<br>    for topic_idx, topic in enumerate(model.components_):<br>        topics[f&quot;Topic {topic_idx}&quot;] = &quot; &quot;.join([feature_names[i] for i in topic.argsort()[:-no_top_words -1:-1]])<br>    return topics<br># this will create 10 no_topics and for each number of topic total of top 10 words<br># will be displayed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcXWdhV0sCQZIJI34Q8Djg.png" /><figcaption>Output of the above code displaying 10 topics with 10 most frequent words in each.</figcaption></figure><p>Now, we will generate labels based on the most relevant words for each topic to accurately represent their content.</p><p>From our analysis, we conclude that in the past 30 days, the data science and machine learning community has primarily focused on <strong>AI &amp; Models</strong>, followed by <strong>Coding &amp; Implementation</strong>. The third major area of interest lies at the intersection of <strong>Data Science &amp; Python</strong> and <strong>Machine Learning Tools</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EM1i1DwyLdZE-7vcBwVtEQ.png" /></figure><p>Moving forward, in my upcoming article, I will delve into Deep Learning methodologies aimed at text generation and title recommendations, utilizing this very dataset.</p><p>I hope you found this article insightful and you can find the whole code of scraping the data in the given <a href="https://github.com/Chesta1/Python_programming/tree/master/Web_scraping_folder">github link</a> and the code of <em>analysis</em> with the given <a href="https://github.com/Chesta1/nlp/blob/main/defining_labels.ipynb">github link</a>. For more such content, follow me on Medium.</p><p>Additionally, you can access the curated dataset on Kaggle through the link provided below.</p><p>Your feedback and engagement are always appreciated.</p><p><em>References</em></p><p><a href="https://www.kaggle.com/datasets/chestadhingra/trends-in-data-science-and-software-development">Trends in Data Science and Software Development</a></p><p><em>Latent Dirichlet Allocation research paper by David M. Blei, Andrew Y. Ng, Michael I. Jordan</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa52bcad2e7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/find-the-trending-topics-in-data-science-and-software-development-using-ml-python-aa52bcad2e7a">Find the Trending Topics in Data Science and Software Development using ML &amp; Python!!</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>