<?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 Madhan on Medium]]></title>
        <description><![CDATA[Stories by Madhan on Medium]]></description>
        <link>https://medium.com/@madhan.p.m.56?source=rss-cf0ba6ecf8ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S-2_Ip6n33ue0hSuUMwM8g.jpeg</url>
            <title>Stories by Madhan on Medium</title>
            <link>https://medium.com/@madhan.p.m.56?source=rss-cf0ba6ecf8ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:38:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhan.p.m.56/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[Transforming Sales Tracking Data into Actionable Insights: A Step-by-Step Guide for Analysts Using…]]></title>
            <link>https://medium.com/@madhan.p.m.56/transforming-sales-tracking-data-into-actionable-insights-a-step-by-step-guide-for-analysts-using-0a952e1a386a?source=rss-cf0ba6ecf8ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a952e1a386a</guid>
            <dc:creator><![CDATA[Madhan]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 19:27:55 GMT</pubDate>
            <atom:updated>2024-09-06T19:27:55.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transforming Sales Tracking Data into Actionable Insights: A Step-by-Step Guide for Analysts Using Excel</h3><p>Sales tracking data holds valuable insights, but the challenge is converting messy, raw data into actionable intelligence. Recently, I worked on a sales tracking project that involved cleaning and categorizing data, performing trend analysis, and creating interactive dashboards using <strong>Microsoft Excel</strong>. In this blog, I’ll guide you through this step-by-step process, showing how Excel’s capabilities can help transform data into insights.</p><h3>Step 1: Cleaning and Categorizing Data in Excel</h3><p>The first step in any data analysis project is cleaning the data. For this project, I categorized sales leads based on their status (Cold, Warm, or Hot) using a color-coded system:</p><ul><li><strong>Red</strong> = Cold</li><li><strong>Yellow</strong> = Warm</li><li><strong>Green</strong> = Hot</li></ul><p>To automate the categorization of sales leads in Excel, you can use <strong>Conditional Formatting</strong> to highlight rows based on values. But for more complex automation, using <strong>VBA (Visual Basic for Applications)</strong> is efficient.</p><p>Here’s a simple VBA script that automates lead categorization based on cell color:</p><pre>Function GetCellColorStatus(cell As Range) As String<br>    Select Case cell.Interior.Color<br>        Case 255    &#39; Red<br>            GetCellColorStatus = &quot;Cold&quot;<br>        Case 65535  &#39; Yellow<br>            GetCellColorStatus = &quot;Warm&quot;<br>        Case 5296274 &#39; Green<br>            GetCellColorStatus = &quot;Hot&quot;<br>        Case Else<br>            GetCellColorStatus = &quot;Unknown&quot;<br>    End Select<br>End Function</pre><p>By running this VBA function, Excel can automatically categorize hundreds of leads, saving hours of manual data entry.</p><h3>Step 2: Extracting Domain Names from URLs in Excel</h3><p>Cleaning data also involves extracting useful information from URLs. In the <strong>Source_Site</strong> column, I needed to extract just the domain name from the URL to streamline the analysis. You can achieve this using the following Excel formula:</p><pre>=IF(U2 = &quot;&quot;, &quot;No Source&quot;, MID(U2, SEARCH(&quot;//&quot;, U2) + 2, SEARCH(&quot;/&quot;, U2, SEARCH(&quot;//&quot;, U2) + 2) - SEARCH(&quot;//&quot;, U2) - 2))</pre><p>This formula extracts the domain name from a URL. For example, it converts “https://e27.co/startup/first-page-pte-ltd” to simply “e27.co,” making it easier to analyze lead sources.</p><h3>Step 3: Conducting Sentiment Analysis of Sales Conversations in Excel</h3><p>Understanding the sentiment of sales conversations is vital for gauging client engagement. Based on the conversation’s description, I performed sentiment analysis using key terms. I categorized conversations as <strong>Positive</strong>, <strong>Negative</strong>, or <strong>Neutral</strong> based on words like:</p><ul><li>Positive: “email sent,” “follow-up,” “responded”</li><li>Negative: “no answer,” “not interested”</li><li>Neutral: “cold email,” “called”</li></ul><p>Here’s a formula that automatically detects sentiment based on keywords:</p><pre>=IF(OR(ISNUMBER(SEARCH(&quot;no answer&quot;, LOWER(S2))), ISNUMBER(SEARCH(&quot;not interested&quot;, LOWER(S2)))), &quot;Negative&quot;,<br>IF(OR(ISNUMBER(SEARCH(&quot;email sent&quot;, LOWER(S2))), ISNUMBER(SEARCH(&quot;follow up&quot;, LOWER(S2))), ISNUMBER(SEARCH(&quot;spoke&quot;, LOWER(S2)))), &quot;Positive&quot;,<br>&quot;Neutral&quot;))</pre><p>With this, Excel flags the sentiment for each interaction, allowing quick filtering of leads that need immediate attention.</p><h3>Step 4: Time-Based Trend Analysis</h3><p>To perform trend analysis, I created new columns for <strong>Month</strong> and <strong>Year</strong> based on the “Created” and “Last Modified” date columns. You can use Excel’s <strong>TEXT</strong> and <strong>YEAR</strong> functions to extract these values:</p><pre>=TEXT(B2, &quot;yyyy&quot;)<br>=TEXT(B2, &quot;mmm&quot;)</pre><p>This allowed me to track the progress of sales leads over time and identify performance trends across different months and years.</p><h3>Step 5: Creating Pivot Tables for In-Depth Analysis</h3><p>Once the data was cleaned and categorized, I used <strong>Pivot Tables</strong> to uncover deeper insights. These helped me answer key business questions such as:</p><ol><li><strong>How many leads are Cold, Warm, or Hot?</strong></li><li><strong>Which months saw the highest lead conversions?</strong></li><li><strong>Which countries or regions performed the best?</strong></li><li><strong>Which industries showed the most potential?</strong></li></ol><p><strong>Pivot Tables</strong> allow you to filter and group data, providing a detailed view of trends and patterns. For instance, I created a pivot table to analyze sales leads by their current status, geography, and industry.</p><h3>Step 6: Building an Interactive Excel Dashboard</h3><p>Finally, I built an interactive dashboard using Excel to visualize the data and make it accessible to decision-makers. Key features of the dashboard included:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4Bq8Rm2WEu7fPSlkcqYkA.jpeg" /></figure><ul><li><strong>Slicers</strong>: To filter data by lead status (Cold, Warm, Hot)</li><li><strong>Charts and Graphs</strong>: To provide visual insights into trends over time, geographical distribution, and industry breakdowns</li></ul><p>I used <strong>Pivot Charts</strong> to create dynamic, easy-to-read visualizations of the data. The dashboard allowed for interactive exploration of the data, offering a quick overview of key performance indicators (KPIs) like conversion rates and lead status trends.</p><h3>Conclusion</h3><p>Turning raw sales tracking data into actionable insights is essential for effective decision-making. By using Excel’s data cleaning tools, advanced formulas, and visualizations, you can unlock powerful insights that drive strategic action. Whether you’re automating tedious tasks with VBA or creating dynamic dashboards, Excel is an indispensable tool for any business analyst looking to turn data into results.</p><p>This step-by-step process showcases the power of Excel in data transformation, making it a perfect skill to highlight when applying for roles like Business Analyst or Data Analyst.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a952e1a386a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Whatsapp Chat Analysis: A Data-Driven Approach to Analyse Interaction behaviour & patterns]]></title>
            <link>https://medium.com/@madhan.p.m.56/whatsapp-chat-analysis-a-data-driven-approach-to-business-decision-making-89bee2434fcf?source=rss-cf0ba6ecf8ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bee2434fcf</guid>
            <dc:creator><![CDATA[Madhan]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 17:28:45 GMT</pubDate>
            <atom:updated>2024-09-06T20:02:13.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation Behind Chat Analysis</h3><p>In today’s digital age, communication has shifted significantly towards instant messaging platforms like WhatsApp. With millions of users exchanging messages daily, the data embedded in these conversations offers valuable insights. Analyzing WhatsApp chat data provides a unique opportunity to understand communication patterns, user behavior, and interaction dynamics. This information is particularly beneficial for businesses and organizations looking to enhance customer engagement, improve communication strategies, and make data-driven decisions.</p><h3>Objective</h3><p>The primary objective of this blog is to demonstrate how to perform a detailed analysis of WhatsApp chat data using Python and Streamlit. We’ll explore various aspects of chat data, such as message frequency, user activity, word clouds, and emoji usage, to gain insights that can inform business decisions and communication strategies.</p><h3>How Chat Analysis Can Help in Business Decision Making</h3><ol><li><strong>Understanding Customer Behavior</strong>: By analyzing message frequency and content, businesses can understand customer engagement patterns and preferences.</li><li><strong>Identifying Key Interactions</strong>: Highlighting active users and analyzing communication trends can help in identifying key stakeholders or influencers.</li><li><strong>Improving Communication Strategies</strong>: Insights from word clouds and emoji usage can guide the tone and style of communication.</li><li><strong>Enhancing Customer Support</strong>: Analyzing peak activity times can help in optimizing support resources and response times.</li></ol><h3>Step-by-Step Explanation of the Analysis</h3><h3>1. Data Preprocessing</h3><p>Before diving into the analysis, we need to preprocess the WhatsApp chat data. This involves cleaning and structuring the raw chat export data.</p><pre>import re<br>import pandas as pd<br>from urlextract import URLExtract<br><br>extract = URLExtract()<br><br>def preprocess(data):<br>    pattern = &#39;\d{1,2}/\d{1,2}/\d{2,4},\s\d{1,2}:\d{2}\s[APap][Mm]\s-\s&#39;<br>    messages = re.split(pattern, data)[1:]<br>    dates = re.findall(pattern, data)<br>    clean_dates = [date.replace(&#39;\u202f&#39;, &#39; &#39;) for date in dates]<br>    df = pd.DataFrame({&#39;user_message&#39;: messages, &#39;message_date&#39;: clean_dates})<br>    df[&#39;message_date&#39;] = pd.to_datetime(df[&#39;message_date&#39;], format=&#39;%d/%m/%y, %I:%M %p - &#39;, errors=&#39;coerce&#39;)<br>    df.rename(columns={&#39;message_date&#39;: &#39;date&#39;}, inplace=True)<br>    df[&#39;only_date&#39;] = df[&#39;date&#39;].dt.date<br>    df[&#39;year&#39;] = df[&#39;date&#39;].dt.year<br>    df[&#39;month_num&#39;] = df[&#39;date&#39;].dt.month<br>    df[&#39;month&#39;] = df[&#39;date&#39;].dt.month_name()<br>    df[&#39;day&#39;] = df[&#39;date&#39;].dt.day<br>    df[&#39;day_name&#39;] = df[&#39;date&#39;].dt.day_name()<br>    df[&#39;hour&#39;] = df[&#39;date&#39;].dt.hour<br>    df[&#39;minute&#39;] = df[&#39;date&#39;].dt.minute<br>    df[&#39;formatted_date&#39;] = df[&#39;date&#39;].dt.strftime(&#39;%d/%m/%y, %I:%M %p&#39;)<br><br>    users, messages = [], []<br>    for message in df[&#39;user_message&#39;]:<br>        entry = re.split(&#39;([\w\W]+?):\s&#39;, message)<br>        if entry[1:]:<br>            users.append(entry[1])<br>            messages.append(&#39; &#39;.join(entry[2:]))<br>        else:<br>            users.append(&#39;group_notification&#39;)<br>            messages.append(entry[0])<br><br>    df[&#39;user&#39;] = users<br>    df[&#39;message&#39;] = messages<br>    df.drop(columns=[&#39;user_message&#39;], inplace=True)<br>    df = df[[&#39;formatted_date&#39;, &#39;user&#39;, &#39;message&#39;, &#39;year&#39;, &#39;month_num&#39;, &#39;month&#39;, &#39;day&#39;, &#39;day_name&#39;, &#39;hour&#39;, &#39;minute&#39;]]<br>    <br>    period = []<br>    for hour in df[&#39;hour&#39;]:<br>        if hour == 23:<br>            period.append(f&quot;{hour}-00&quot;)<br>        elif hour == 0:<br>            period.append(&quot;00-01&quot;)<br>        else:<br>            period.append(f&quot;{hour}-{hour+1}&quot;)<br>    df[&#39;period&#39;] = period<br><br>    return df</pre><h3>2. Upload and Display Data</h3><p>Using Streamlit, users can upload their chat file and view the structured data.</p><pre>import streamlit as st<br><br>st.sidebar.title(&quot;WhatsApp Chat Analyzer&quot;)<br>uploaded_file = st.sidebar.file_uploader(&quot;Choose a file&quot;)<br>if uploaded_file is not None:<br>    bytes_data = uploaded_file.getvalue()<br>    data = bytes_data.decode(&quot;utf-8&quot;)<br>    df = preprocess(data)<br>    st.dataframe(df)</pre><h3>3. Analyzing Basic Metrics</h3><p>We will calculate and display basic metrics such as total messages, words, media shared, and links shared.</p><pre>def fetch_stats(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br><br>    num_messages = df.shape[0]<br>    words = [word for message in df[&#39;message&#39;] for word in message.split()]<br>    num_media_messages = df[df[&#39;message&#39;] == &#39;&lt;Media omitted&gt;\n&#39;].shape[0]<br>    links = [link for message in df[&#39;message&#39;] for link in extract.find_urls(message)]<br>    <br>    return num_messages, len(words), num_media_messages, len(links)<br><br># Displaying the stats<br>if st.sidebar.button(&quot;Show Analysis&quot;):<br>    num_messages, words, num_media_messages, links = fetch_stats(selected_user, df)<br>    col1, col2, col3, col4 = st.columns(4)<br>    with col1:<br>        st.header(&#39;Total Messages&#39;)<br>        st.title(num_messages)<br>    with col2:<br>        st.header(&#39;Total Words&#39;)<br>        st.title(words)<br>    with col3:<br>        st.header(&#39;Media Shared&#39;)<br>        st.title(num_media_messages)<br>    with col4:<br>        st.header(&#39;Links Shared&#39;)<br>        st.title(links)</pre><h3>4. Visualizing User Activity</h3><p>We will visualize the activity of users over different time periods using bar charts and heatmaps.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Most Busy Users<br>def most_busy_users(df):<br>    x = df[&#39;user&#39;].value_counts().head()<br>    df = round((df[&#39;user&#39;].value_counts() / df.shape[0]) * 100, 2).reset_index().rename(columns={&#39;user&#39;: &#39;name&#39;, &#39;count&#39;: &#39;percentage&#39;})<br>    return x, df<br><br># Word Cloud and Most Common Words<br>from wordcloud import WordCloud<br>from collections import Counter<br><br>def create_wordcloud(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br>    temp = df[df[&#39;user&#39;] != &#39;group_notification&#39;]<br>    temp = temp[temp[&#39;message&#39;] != &#39;&lt;Media omitted&gt;\n&#39;]<br>    <br>    def remove_stop_words(message):<br>        y = [word for word in message.lower().split() if word not in stop_words]<br>        return &quot; &quot;.join(y)<br><br>    wc = WordCloud(width=500, height=500, min_font_size=10, background_color=&#39;white&#39;)<br>    temp[&#39;message&#39;] = temp[&#39;message&#39;].apply(remove_stop_words)<br>    df_wc = wc.generate(temp[&#39;message&#39;].str.cat(sep=&quot; &quot;))<br>    return df_wc<br><br>def most_common_words(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br>    temp = df[df[&#39;user&#39;] != &#39;group_notification&#39;]<br>    temp = temp[temp[&#39;message&#39;] != &#39;&lt;Media omitted&gt;\n&#39;]<br>    words = [word for message in temp[&#39;message&#39;] for word in message.lower().split() if word not in stop_words]<br>    most_common_df = pd.DataFrame(Counter(words).most_common(20))<br>    return most_common_df<br><br># Emoji Analysis<br>import emoji<br>from collections import Counter<br><br>def emoji_helper(selected_user, df):<br>    if selected_user != &#39;Overall&#39;:<br>        df = df[df[&#39;user&#39;] == selected_user]<br>    emojis = [char for message in df[&#39;message&#39;] for char in message if char in emoji.EMOJI_DATA]<br>    emoji_counts = Counter(emojis)<br>    emoji_df = pd.DataFrame(emoji_counts.most_common(5), columns=[&#39;emoji&#39;, &#39;count&#39;])<br>    return emoji_df</pre><h3>5. Advanced Analysis</h3><p>Perform association tests and heatmaps to analyze user interaction patterns across days and months.</p><pre>from scipy.stats import chi2_contingency<br><br>def user_day_association_test(df, user1, user2, year, selected_month):<br>    df_filtered = df[(df[&#39;year&#39;] == year) &amp; (df[&#39;month&#39;] == selected_month)]<br>    <br>    if user1 != &#39;Overall&#39; and user2 != &#39;Overall&#39;:<br>        df_filtered = df_filtered[df_filtered[&#39;user&#39;].isin([user1, user2])]<br>    elif user1 != &#39;Overall&#39;:<br>        df_filtered = df_filtered[df_filtered[&#39;user&#39;] == user1]<br>    elif user2 != &#39;Overall&#39;:<br>        df_filtered = df_filtered[df_filtered[&#39;user&#39;] == user2]<br>    <br>    if df_filtered.empty:<br>        return None, None, None, None, None, None<br>    <br>    contingency_table = pd.crosstab(df_filtered[&#39;user&#39;], df_filtered[&#39;day_name&#39;])<br>    <br>    chi2, p_value, dof, expected = chi2_contingency(contingency_table)<br>    observed_minus_expected = contingency_table - pd.DataFrame(expected, index=contingency_table.index, columns=contingency_table.columns)<br>    <br>    return chi2, p_value, dof, expected, contingency_table, observed_minus_expected<br><br># Plotting Heatmaps<br>def plot_heatmap(df):<br>    heatmap = df.pivot_table(index=&#39;day_name&#39;, columns=&#39;period&#39;, values=&#39;user&#39;, aggfunc=&#39;count&#39;, fill_value=0)<br>    plt.figure(figsize=(12, 6))<br>    sns.heatmap(heatmap, annot=True, cmap=&#39;Blues&#39;, fmt=&#39;d&#39;)<br>    plt.title(&#39;Activity Heatmap&#39;)<br>    st.pyplot()</pre><h3>Conclusion</h3><p>Analyzing WhatsApp chat data can yield significant insights into communication patterns, user behavior, and interaction dynamics. By leveraging Python and Streamlit, you can preprocess data, visualize user activity, and derive actionable insights to drive better decision-making. Whether you’re a business looking to optimize customer interactions or an individual curious about your chat history, this analysis can provide valuable perspectives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bee2434fcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Business Insights: SQL-Driven Data Analysis for Cochin Traders]]></title>
            <link>https://medium.com/@madhan.p.m.56/unlocking-business-insights-sql-driven-data-analysis-for-cochin-traders-b4ef652973f8?source=rss-cf0ba6ecf8ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ef652973f8</guid>
            <dc:creator><![CDATA[Madhan]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 18:21:20 GMT</pubDate>
            <atom:updated>2024-08-16T18:30:41.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This document presents a series of SQL queries designed to extract critical business insights from Cochin Traders’ database. The queries address various business objectives, including sales performance, inventory management, customer behavior, and revenue analysis. Each section includes the SQL query, insights derived, and actionable recommendations, with a focus on performance improvements through alternative queries where applicable.</p><p><strong>Schema:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*JOwGyr3SfFwODGmbqBHfpw.jpeg" /></figure><h3>Query Analysis</h3><h3>1. Identifying Sales Representatives</h3><p><strong>Business Objective:</strong> Retrieve the full name and hiring date of employees with the title “Sales Representative.”</p><pre>SELECT CONCAT(firstname, &quot; &quot;, lastname) AS full_name, hiredate, title <br>FROM cochin_traders.employees<br>WHERE title = &#39;Sales Representative&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*pTGEtb6zawBgcYtKaMQviw.jpeg" /></figure><h3>2. Inventory Reorder Analysis</h3><p><strong>Business Objective:</strong> Determine which products in inventory need to be reordered.</p><pre>SELECT * <br>FROM cochin_traders.products<br>WHERE unitsinstock &lt; reorderlevel<br>ORDER BY productid;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*JPjdSJI1DH00FmT7zlrYfA.jpeg" /></figure><h3>3. Customer Ordering Patterns</h3><p><strong>Business Objective:</strong> Display details of customers who have placed more than 5 orders.</p><p><strong>Query:</strong></p><pre>WITH a AS (<br>    SELECT customerid, COUNT(customerid) AS No_of_orders <br>    FROM cochin_traders.orders<br>    GROUP BY customerid<br>    HAVING COUNT(customerid) &gt; 5<br>)<br>SELECT a.customerid, a.No_of_orders, c.companyname, c.contactname, c.contacttitle, c.city, c.region, c.country<br>FROM a <br>JOIN cochin_traders.customers AS c ON a.customerid = c.customerid<br>ORDER BY a.No_of_orders;</pre><p><strong>Optimized Query:</strong></p><pre>WITH a AS (<br>    SELECT customerid <br>    FROM cochin_traders.orders<br>    GROUP BY customerid<br>    HAVING COUNT(customerid) &gt; 5<br>)<br>SELECT * <br>FROM cochin_traders.customers<br>WHERE customerid IN (SELECT customerid FROM a);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PIZlnpR0kjtxaxAEJhBew.jpeg" /></figure><p><strong>Why Use the Alternative Query:</strong> The optimized query uses a subquery in the WHERE clause, which can be more efficient for large datasets. By directly selecting from the customer table using the IN clause with the result from the subquery, it reduces the need for a complex join operation.</p><h3>4. Unengaged Customers with Top Employee</h3><p><strong>Business Objective:</strong> Identify customers who have never placed an order with Margaret Peacock.</p><p><strong>Query (Using CTE and Joins):</strong></p><pre>WITH emp4order AS (<br>    SELECT * <br>    FROM cochin_traders.orders<br>    WHERE employeeid = 4<br>)<br>SELECT DISTINCT c.customerid, c.companyname, c.contactname, c.contacttitle<br>FROM cochin_traders.customers AS c <br>LEFT JOIN emp4order AS e ON c.customerid = e.customerid<br>WHERE e.customerid IS NULL;</pre><p><strong>Query (Using Subquery):</strong></p><pre>SELECT DISTINCT customerid, companyname, contactname, contacttitle<br>FROM cochin_traders.customers<br>WHERE customerid NOT IN (<br>    SELECT customerid <br>    FROM cochin_traders.orders <br>    WHERE employeeid = 4<br>);</pre><p><strong>Why Use the Alternative Query:</strong> The subquery approach avoids the need for a join operation, which can be more efficient in scenarios with large datasets or when the join involves a large number of rows. This approach also simplifies the query and may result in better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ErrjdfJ0ZEh49PTW2ZFKtg.jpeg" /></figure><h3>5. Best-Selling Products Analysis</h3><p><strong>Business Objective:</strong> Identify the top 5 best-selling products based on the quantity ordered.</p><p><strong>Query (Using ORDER BY &amp; LIMIT):</strong></p><pre>WITH topquantity AS (<br>    SELECT productid, SUM(quantity) AS total_quantity <br>    FROM cochin_traders.orders_details<br>    GROUP BY productid<br>    ORDER BY SUM(quantity) DESC<br>    LIMIT 5<br>)<br>SELECT * <br>FROM topquantity AS t <br>JOIN cochin_traders.products AS p ON t.productid = p.productid;</pre><p><strong>Query (Using DENSE RANK):</strong></p><pre>WITH topquantity AS (<br>    SELECT productid, SUM(quantity) AS total_quantity <br>    FROM cochin_traders.orders_details<br>    GROUP BY productid<br>),<br>rnk AS (<br>    SELECT p.*, DENSE_RANK() OVER (ORDER BY t.total_quantity DESC) AS quantityrnk<br>    FROM topquantity AS t <br>    JOIN cochin_traders.products AS p ON t.productid = p.productid<br>)<br>SELECT * <br>FROM rnk<br>WHERE quantityrnk &lt;= 5;</pre><p><strong>Why Use the Alternative Query:</strong> The DENSE_RANK() method is beneficial when there are ties in the quantity ordered. It ensures all top products are considered, even if multiple products have the same order quantity. This approach is more robust for ranking with ties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4T3hK4s_eW75gaO12b0DpA.jpeg" /></figure><h3>6. Monthly Order Count Analysis for 1997</h3><p><strong>Business Objective:</strong> Analyze the number of orders placed each month in 1997.</p><p><strong>Query:</strong></p><pre>SELECT MONTH(orderdate) AS month, COUNT(*) AS Monthly_Order_Count <br>FROM cochin_traders.orders<br>WHERE YEAR(orderdate) = 1997<br>GROUP BY MONTH(orderdate);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*RE4cwROJmlrKb0V-NlSz4Q.jpeg" /></figure><h3>7. Monthly Revenue Difference Analysis</h3><p><strong>Business Objective:</strong> Determine the month-over-month difference in sales revenue.</p><pre>WITH revenue AS (<br>    SELECT *, ROUND(unitprice * quantity) AS rev<br>    FROM cochin_traders.orders_details<br>),<br>monthsplit AS (<br>    SELECT r.*, YEAR(o.orderdate) AS orderyear, MONTH(o.orderdate) AS ordermonth<br>    FROM revenue AS r <br>    JOIN cochin_traders.orders AS o ON r.orderid = o.orderid<br>    ORDER BY orderyear, ordermonth<br>)<br>SELECT orderyear, ordermonth, SUM(rev) AS total_monthly_order,<br>LAG(SUM(rev), 1, 0) OVER (PARTITION BY orderyear ORDER BY ordermonth) AS prev_month_revenue,<br>SUM(rev) - LAG(SUM(rev), 1, 0) OVER (PARTITION BY orderyear ORDER BY ordermonth) AS diff_revenue_prevmonth<br>FROM monthsplit<br>GROUP BY orderyear, ordermonth;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*SuCiCaV2Q7AWnsyr0hXDWA.jpeg" /></figure><h3>8. Product Revenue Percentage Analysis</h3><p><strong>Business Objective:</strong> Compute the percentage of total sales revenue contributed by each product.</p><p><strong>Query:</strong></p><pre>WITH revenue AS (<br>    SELECT *, ROUND(unitprice * quantity) AS rev<br>    FROM cochin_traders.orders_details<br>),<br>total_revenue AS (<br>    SELECT SUM(rev) AS total_revenue<br>    FROM revenue<br>),<br>product_revenue AS (<br>    SELECT p.productid, p.productname, SUM(r.rev) AS product_revenue<br>    FROM revenue AS r <br>    JOIN cochin_traders.products AS p ON r.productid = p.productid<br>    GROUP BY p.productid, p.productname<br>)<br>SELECT pr.productid, pr.productname, pr.product_revenue, tr.total_revenue, <br>ROUND((pr.product_revenue / tr.total_revenue) * 100, 2) AS percentage_of_total_revenue<br>FROM product_revenue AS pr <br>JOIN total_revenue AS tr;</pre><p><strong>Alternative Query:</strong></p><pre>WITH total_rev AS (<br>    SELECT SUM(unitprice * quantity) AS rev<br>    FROM cochin_traders.orders_details<br>), <br>product_rev AS (<br>    SELECT p.productname, SUM(od.unitprice * od.quantity) AS product_rev<br>    FROM cochin_traders.products AS p<br>    JOIN cochin_traders.orders_details AS od ON p.productid = od.productid<br>    GROUP BY p.productname<br>)<br>SELECT p.productname, p.product_rev, (p.product_rev / t.rev) * 100 AS percentage_revenue<br>FROM total_rev AS t, product_rev AS p<br>ORDER BY percentage_revenue DESC;</pre><p><strong>Why Use the Alternative Query:</strong> The alternative query simplifies the calculation by avoiding multiple joins and intermediate steps. It performs the calculations in fewer steps, which can lead to better performance for large datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*Vg0BatFbViyw2oF-utVkaw.jpeg" /></figure><h3>Summary of Insights, Recommendations, and Impact</h3><h3>1. Identifying Sales Representatives</h3><p><strong>Insights:</strong></p><ul><li>Provides a list of Sales Representatives, including their hire dates.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Utilize experienced Sales Representatives for mentoring new hires and strategic planning.</li></ul><h3>2. Inventory Reorder Analysis</h3><p><strong>Insights:</strong></p><ul><li>Identifies products below reorder levels, indicating potential stockouts.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Implement a regular review process to ensure timely reordering and avoid stockouts.</li></ul><h3>3. Customer Ordering Patterns</h3><p><strong>Insights:</strong></p><ul><li>Identifies customers who have placed more than 5 orders, highlighting loyal customers.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Develop targeted marketing strategies and loyalty programs for high-value customers.</li></ul><h3>4. Unengaged Customers with Top Employee</h3><p><strong>Insights:</strong></p><ul><li>Reveals customers who have not interacted with top employee Margaret Peacock.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Assign these customers to Margaret Peacock for outreach to improve engagement.</li></ul><h3><strong>5. Best-Selling Products Analysis</strong></h3><p><strong>Insights:</strong></p><ul><li>Identifies the top 5 best-selling products based on quantity ordered.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Promote top-selling products and ensure adequate stock levels to meet demand.</li></ul><h3>6. Monthly Order Count Analysis for 1997</h3><p><strong>Insights:</strong></p><p>Provides a monthly breakdown of order counts for 1997, showing trends and peak periods.</p><p><strong>Recommendations:</strong></p><ul><li>Plan seasonal promotions and adjust staffing levels according to peak periods.</li></ul><h3>7. Monthly Revenue Difference Analysis</h3><p><strong>Insights:</strong></p><ul><li>Calculates month-over-month revenue differences, highlighting trends and changes in sales performance.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Investigate significant revenue changes and adjust strategies to address declines and capitalize on increases.</li></ul><h3>8. Product Revenue Percentage Analysis</h3><p><strong>Insights:</strong></p><ul><li>Shows the percentage of total sales revenue contributed by each product.</li></ul><p><strong>Recommendations:</strong></p><ul><li>Focus marketing and sales efforts on high-revenue products and explore ways to improve the performance of lower-revenue items.</li></ul><h3>Conclusion</h3><p>The presented queries and their optimizations provide a comprehensive view of Cochin Traders’ sales, inventory, and customer behavior.</p><p>By implementing the recommendations from this analysis, Cochin Traders could see a significant increase in annual revenue, optimized inventory management, improved customer engagement, and enhanced marketing and sales strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ef652973f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Advanced Document-Processing and Chatbot Application for Sales Professionals using…]]></title>
            <link>https://medium.com/@madhan.p.m.56/building-an-advanced-document-processing-and-chatbot-application-for-sales-professionals-with-042159f8d828?source=rss-cf0ba6ecf8ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/042159f8d828</guid>
            <dc:creator><![CDATA[Madhan]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 17:42:23 GMT</pubDate>
            <atom:updated>2024-08-09T17:42:57.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Advanced Document-Processing and Chatbot Application for Sales Professionals using LangChain and Groq AI</h3><p>In the dynamic world of sales, professionals constantly seek tools that can enhance efficiency, streamline workflows, and provide actionable insights. One such tool is an advanced document-processing and chatbot application, which leverages cutting-edge technologies like LangChain and Groq AI. This blog explores the motivation behind such an application, its key features, and a detailed guide on building it, including a requirements file and code walkthrough.</p><h3>Motivation Behind the Application</h3><p>Sales professionals are inundated with vast amounts of data, including client documents, communications, and market research. Managing and extracting valuable information from these documents can be time-consuming and challenging. An application that can automate document processing, provide intelligent responses through a chatbot, and maintain a history of interactions can significantly enhance productivity and decision-making. The integration of LangChain for document processing and Groq AI for chatbot functionalities makes this application a robust solution for modern sales challenges.</p><h3>Key Features</h3><ol><li><strong>Document Upload and Processing</strong>: Seamlessly upload and process PDF documents. The application extracts and splits text from PDFs for efficient querying.</li><li><strong>Vector Store Creation</strong>: Convert documents into vector embeddings using HuggingFace embeddings and FAISS, enabling advanced similarity searches.</li><li><strong>AI Chatbot Interaction</strong>: Engage with a Groq AI-powered chatbot that provides intelligent responses based on document content or general queries.</li><li><strong>Chat History Management</strong>: Keep track of conversations, generate summaries, and export chat history to PDF for easy reference and record-keeping.</li></ol><h3>Requirements</h3><p>To build and run this application, you’ll need the following dependencies. Save them in a requirements.txt file:</p><pre>streamlit==1.17.0<br>langchain==0.0.1<br>groq==0.0.3<br>faiss-cpu==1.7.3<br>huggingface-hub==0.8.1<br>python-dotenv==0.21.1<br>fpdf==1.7.2</pre><h3>Step-by-Step Explanation</h3><h4>1. Setup and Imports</h4><p>Start by importing the necessary libraries:</p><pre>import os<br>import time<br>from dotenv import load_dotenv<br>from groq import Groq<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings import HuggingFaceEmbeddings<br>import streamlit as st<br>from fpdf import FPDF</pre><ul><li><strong>os and </strong><strong>time</strong>: For file operations and measuring execution time.</li><li><strong>dotenv</strong>: To load environment variables for API keys.</li><li><strong>Groq and </strong><strong>LangChain</strong>: For AI chat functionalities and document processing.</li><li><strong>FAISS</strong>: For efficient similarity search in vector space.</li><li><strong>HuggingFaceEmbeddings</strong>: To generate embeddings from documents.</li><li><strong>Streamlit</strong>: To create the web interface.</li><li><strong>FPDF</strong>: For generating PDF documents.</li></ul><h4>2. Document Processing</h4><p>The get_docs function handles the uploading and processing of PDF documents:</p><pre>def get_docs(uploaded_file):<br>    start_time = time.time()<br>    with open(&quot;temp.pdf&quot;, &quot;wb&quot;) as f:<br>        f.write(uploaded_file.getbuffer())<br>    loader = PyPDFLoader(&quot;temp.pdf&quot;)<br>    documents = loader.load()<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=100)<br>    final_documents = text_splitter.split_documents(documents)<br>    st.sidebar.write(&#39;Documents Loaded&#39;)<br>    end_time = time.time()<br>    st.sidebar.write(f&quot;Time taken to load documents: {end_time - start_time:.2f} seconds&quot;)<br>    os.remove(&quot;temp.pdf&quot;)  <br>    return final_documents</pre><ul><li><strong>PDF Upload</strong>: Save the uploaded file temporarily.</li><li><strong>Document Loading</strong>: Use PyPDFLoader to load the document.</li><li><strong>Text Splitting</strong>: Split the document into manageable chunks for processing.</li></ul><h4>3. Creating Vector Store</h4><p>Create a vector store to enable similarity searches:</p><pre>def create_vector_store(docs):<br>    start_time = time.time()<br>    embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;, model_kwargs={&quot;trust_remote_code&quot;: True})<br>    vectorstore = FAISS.from_documents(docs, embeddings)<br>    st.sidebar.write(&#39;DB is ready&#39;)<br>    end_time = time.time()<br>    st.sidebar.write(f&quot;Time taken to create DB: {end_time - start_time:.2f} seconds&quot;)<br>    return vectorstore</pre><ul><li><strong>Embeddings</strong>: Convert text chunks into vector embeddings.</li><li><strong>FAISS</strong>: Build a vector store for similarity searches.</li></ul><h4>4. Interacting with Groq AI</h4><p>The chat_groq function interacts with Groq AI to generate responses:</p><pre>def chat_groq(messages):<br>    load_dotenv()<br>    client = Groq(api_key=os.environ.get(&#39;GROQ_API_KEY&#39;))<br>    response_content = &#39;&#39;<br>    stream = client.chat.completions.create(<br>        model=&quot;llama3-70b-8192&quot;,<br>        messages=messages,<br>        max_tokens=1024,<br>        temperature=1.3,<br>        stream=True,<br>    )<br><br>    for chunk in stream:<br>        content = chunk.choices[0].delta.content<br>        if content:<br>            response_content += chunk.choices[0].delta.content<br>    return response_content</pre><ul><li><strong>Groq API</strong>: Utilize Groq’s API for generating chat responses.</li></ul><h4>5. Chat History Management</h4><p>Functions to summarize chat history and generate PDF reports:</p><pre>def summarize_chat_history(chat_history):<br>    chat_history_text = &quot; &quot;.join([f&quot;{chat[&#39;role&#39;]}: {chat[&#39;content&#39;]}&quot; for chat in chat_history])<br>    prompt = f&quot;Summarize the following chat history:\n\n{chat_history_text}&quot;<br>    messages = [{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: &#39;You are very good at summarizing the chat between User and Assistant&#39;}]<br>    messages.append({&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: prompt})<br>    summary = chat_groq(messages)<br>    return summary<br><br>def generate_pdf(chat_history):<br>    pdf = FPDF()<br>    pdf.add_page()<br>    pdf.add_font(&#39;Arial&#39;, &#39;&#39;, &#39;arial.ttf&#39;, uni=True)<br>    pdf.set_font(&#39;Arial&#39;, &#39;&#39;, 10)<br>    pdf.set_left_margin(15)<br>    pdf.set_right_margin(15)<br>    pdf.set_top_margin(15)<br>    pdf.set_font(&#39;Arial&#39;, &#39;B&#39;, 14)<br>    pdf.cell(0, 10, &#39;Chat History&#39;, ln=True, align=&#39;C&#39;)<br>    pdf.ln(10)<br>    pdf.set_font(&#39;Arial&#39;, &#39;&#39;, 10)<br>    page_width = pdf.w - pdf.r_margin - pdf.l_margin<br>    for chat in chat_history:<br>        role = chat[&#39;role&#39;].capitalize()<br>        content = chat[&#39;content&#39;]<br>        text_to_add = f&quot;{role}: {content}&quot;<br>        if pdf.get_string_width(text_to_add) &gt; page_width:<br>            pdf.multi_cell(page_width, 10, text_to_add, border=0, align=&#39;L&#39;)<br>        else:<br>            pdf.cell(0, 10, text_to_add, border=0, align=&#39;L&#39;)<br>        pdf.ln()<br>    pdf_output = &quot;chat_history.pdf&quot;<br>    pdf.output(pdf_output)<br>    return pdf_output</pre><ul><li><strong>Summarization</strong>: Summarize chat history for quick reference.</li><li><strong>PDF Generation</strong>: Create a downloadable PDF of the chat history.</li></ul><h4>6. Building the Streamlit Interface</h4><p>Integrate all components into a Streamlit app:</p><pre>def main():<br>    st.set_page_config(page_title=&#39;Sales Professional Chatbot&#39;)<br>    st.title(&quot;Sales Professional Chatbot&quot;)<br>    with st.expander(&quot;Instructions to upload Text PDF/URL&quot;):<br>        st.write(&quot;1. Pull up the side bar in top left corner.&quot;)<br>        st.write(&quot;2. Upload a PDF or enter a URL to process documents.&quot;)<br>        st.write(&quot;3. Create a vector store to enable AI interaction.&quot;)<br>        st.write(&quot;4. Ask questions and interact with the AI chatbot.&quot;)<br>        st.write(&quot;5. Generate and download chat history summaries.&quot;)<br><br>    st.sidebar.subheader(&quot;Choose document source:&quot;)<br>    option = st.sidebar.radio(&quot;&quot;, (&quot;Upload PDF&quot;,))<br><br>    if &quot;docs&quot; not in st.session_state:<br>        st.session_state.docs = None<br>    if &quot;vectorstore&quot; not in st.session_state:<br>        st.session_state.vectorstore = None<br>    if &quot;chat_history&quot; not in st.session_state:<br>        st.session_state.chat_history = []<br>    if &quot;user_input&quot; not in st.session_state:<br>        st.session_state.user_input = &quot;&quot;<br>    if &quot;current_prompt&quot; not in st.session_state:<br>        st.session_state.current_prompt = &quot;&quot;<br>    if &quot;chat_summary&quot; not in st.session_state:<br>        st.session_state.chat_summary = &quot;&quot;<br><br>    if option == &quot;Upload PDF&quot;:<br>        uploaded_file = st.sidebar.file_uploader(&quot;Upload a PDF file&quot;, type=[&quot;pdf&quot;])<br>        if uploaded_file is not None:<br>            if st.session_state.docs is None:<br>                with st.spinner(&quot;Loading documents...&quot;):<br>                    docs = get_docs(uploaded_file)<br>                st.session_state.docs = docs<br><br>    if st.session_state.docs is not None:<br>        if st.sidebar.button(&#39;Create Vector Store&#39;):<br>            with st.spinner(&quot;Creating vector store...&quot;):<br>                vectorstore = create_vector_store(st.session_state.docs)<br>            st.session_state.vectorstore = vectorstore<br><br>    if st.session_state.vectorstore is not None:<br>        def submit_with_doc():<br>            user_message = st.session_state.user_input<br>            if user_message:<br>                retriever = st.session_state.vectorstore.as_retriever()<br>                docs = retriever.get_relevant_documents(user_message)<br>                messages = [{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: user_message}]<br>                response = chat_groq(messages)<br>                st.session_state.chat_history.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message})<br>                st.session_state.chat_history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response})<br>                st.session_state.user_input = &quot;&quot;<br>        <br>        st.text_input(&quot;Ask a question&quot;, key=&#39;user_input&#39;, on_change=submit_with_doc)<br><br>        if st.session_state.chat_history:<br>            for chat in st.session_state.chat_history:<br>                role = chat[&#39;role&#39;].capitalize()<br>                st.write(f&quot;{role}: {chat[&#39;content&#39;]}&quot;)<br>                <br>            if st.button(&quot;Summarize Chat History&quot;):<br>                summary = summarize_chat_history(st.session_state.chat_history)<br>                st.session_state.chat_summary = summary<br>                st.write(&quot;**Summary**:&quot;)<br>                st.write(st.session_state.chat_summary)<br><br>            if st.button(&quot;Generate PDF&quot;):<br>                pdf_file = generate_pdf(st.session_state.chat_history)<br>                st.write(&quot;Download your chat history PDF:&quot;)<br>                st.markdown(f&quot;[Download PDF]({pdf_file})&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Conclusion</h3><p>This blog provided a comprehensive guide to building an advanced document-processing and chatbot application tailored for sales professionals. By integrating LangChain and Groq AI, you can create a powerful tool that automates document management, enhances interactions, and supports efficient sales workflows. This application not only saves time but also empowers sales professionals with valuable insights and improved communication capabilities.</p><p>Feel free to connect with me through <a href="https://www.linkedin.com/in/madhan-p-m-3a45b6b2/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=042159f8d828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Blog Generator App Using Lama, LangChain, and Streamlit]]></title>
            <link>https://medium.com/@madhan.p.m.56/building-a-blog-generator-app-using-lama-langchain-and-streamlit-b77657046f8d?source=rss-cf0ba6ecf8ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b77657046f8d</guid>
            <dc:creator><![CDATA[Madhan]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 20:00:14 GMT</pubDate>
            <atom:updated>2024-07-05T20:05:05.656Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital age, content creation has become more accessible and dynamic than ever before. With the convergence of AI and natural language processing (NLP) technologies, developers can now automate the generation of engaging blog content tailored to specific topics and styles. In this blog post, we explore the development of a Blog Generator App powered by Lama, LangChain, and Streamlit.</p><h3>Introducing the Blog Generator App</h3><p>The Blog Generator App leverages state-of-the-art language models and frameworks to facilitate the effortless creation of blog content. By integrating Lama and LangChain with Streamlit — a popular Python library for building interactive web applications — the app enables users to generate well-structured and insightful blogs on demand.</p><h3>Key Components of the App</h3><h3>1. Streamlit Integration</h3><p>Streamlit provides the foundation for our user interface, offering a straightforward setup to interactively input parameters and generate blog content seamlessly. With Streamlit’s intuitive interface design, users can easily specify the blog topic, desired word count, and select from predefined writing styles.</p><pre>import streamlit as st<br><br>st.set_page_config(<br>    page_title=&quot;Blog Generation App using Lama&quot;,<br>    page_icon=&#39;☕&#39;,<br>    layout=&#39;centered&#39;,<br>    initial_sidebar_state=&#39;collapsed&#39;<br>)<br><br>st.header(&quot;Blog Generation App ☕&quot;)<br><br># Input fields for topic, word count, and style selection<br>input_text = st.text_input(&quot;Enter the blog topic&quot;)<br><br>col1, col2 = st.columns([5, 5])<br><br>with col1:<br>    no_words = st.text_input(&#39;No of Words&#39;)<br><br>with col2:<br>    blog_style = st.selectbox(<br>        &#39;Writing the blog for&#39;,<br>        (&#39;Researchers&#39;, &#39;Data Scientist&#39;, &#39;Sales Analyst&#39;, &#39;Sales Professional&#39;, &#39;Data Analyst&#39;, &#39;Common People&#39;),<br>        index=0<br>    )<br><br>submit = st.button(&quot;Generate&quot;)</pre><h3>2. Lama and LangChain Integration</h3><p>Behind the scenes, the app utilizes Lama and LangChain frameworks to harness the power of large language models. Lama, specifically LLama 2, is employed for its ability to generate coherent and contextually relevant text based on user-defined prompts. LangChain facilitates seamless integration and management of language model workflows, ensuring efficient and reliable performance.</p><pre>from langchain.prompts import PromptTemplate<br>from langchain.llms import CTransformers<br><br>def getLLamaresponse(input_text, no_words, blog_style):<br>    # Initialize LLama 2 model<br>    llm = CTransformers(<br>        model=&#39;models/llama-2-7b-chat.ggmlv3.q8_0.bin&#39;,<br>        model_type=&#39;llama&#39;,<br>        config={<br>            &#39;max_new_tokens&#39;: 256,<br>            &#39;temperature&#39;: 0.01<br>        }<br>    )<br><br>    # Define prompt template for LLama 2<br>    template = &quot;&quot;&quot;<br>        Write a blog for {blog_style} job profile on {input_text} within {no_words} words.<br>    &quot;&quot;&quot;<br><br>    prompt = PromptTemplate(<br>        input_variables=[&quot;blog_style&quot;, &quot;input_text&quot;, &quot;no_words&quot;],<br>        template=template<br>    )<br><br>    # Generate response from LLama 2 model<br>    response = llm(prompt.format(blog_style=blog_style, input_text=input_text, no_words=no_words))<br>    return response</pre><h3>3. Generating Blog Content</h3><p>Upon clicking the “Generate” button, the app triggers the Lama-powered content generation process based on user inputs. The generated blog content is displayed in real-time, allowing users to review and refine as needed. This streamlined approach enhances productivity and creativity in content creation, catering to diverse writing styles and preferences.</p><pre># Final response display<br>if submit:<br>    generated_content = getLLamaresponse(input_text, no_words, blog_style)<br>    st.write(generated_content)</pre><h3>Conclusion</h3><p>The Blog Generator App exemplifies the synergy between advanced AI models and user-friendly interfaces, empowering users to effortlessly create high-quality blog content. With Lama, LangChain, and Streamlit, developers can innovate in content automation, offering new avenues for digital storytelling and information dissemination.</p><p>Experience the future of content creation with our Blog Generator App today. Harness the power of AI and elevate your writing capabilities effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b77657046f8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>