<?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 Alessandro Amenta on Medium]]></title>
        <description><![CDATA[Stories by Alessandro Amenta on Medium]]></description>
        <link>https://medium.com/@alessandroamenta1?source=rss-f39ff33c76d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eJmL2XsmvUfWxRbTJrfHvQ.png</url>
            <title>Stories by Alessandro Amenta on Medium</title>
            <link>https://medium.com/@alessandroamenta1?source=rss-f39ff33c76d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:56:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alessandroamenta1/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[Job Hunting Is Annoying. Build an AI Assistant to Automate the Application process.]]></title>
            <link>https://levelup.gitconnected.com/job-hunting-is-annoying-build-an-ai-assistant-to-automate-the-application-process-ccac2a6de673?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccac2a6de673</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 19:40:34 GMT</pubDate>
            <atom:updated>2024-04-07T19:40:34.432Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build an AI-Job application assistant with OpenAI and Anthropic</h4><p>Job hunting can be soul-sucking. Scouring job boards, tailoring resumes, crafting cover letters, and reaching out to recruiters — it’s a full-time job on its own, minus the pay. It’s daunting, boring, and to be honest, a bit of an emotional rollercoaster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vtETLAUv-IHCSbtU" /><figcaption>Image generated with DALL-E 3</figcaption></figure><p>I genuinely feel it’s one of the most monotonous tasks ever. These days, whenever I face a boring task, my brain instantly goes: <strong>wait, why not let a language model do it for you?</strong></p><p>So, in an effort to answer that question and inject some efficiency into the job application process, I built a quick AI prototype: a Streamlit app powered by AI to ease the pain of job applications.</p><p>This article is all about how to make job searching a little less painful and faster, and in general, learn how to build a quick prototype to help out with tasks AI can do for you.</p><h4>Why This App?</h4><p>Just applying for a ton of jobs with the same exact resume and not sending a cover letter doesn’t really do much. But tailoring your resume for each application, writing a personalized cover letter, and sending a customized cold email to recruiters are strategies known to increase your chances significantly. But they’re also time-consuming. That’s where this app comes in.</p><p>It uses AI to tailor your resume based on the job description, generates a coherent and relevant cover letter, and outputs a personalized cold email ready to send to recruiters. This pretty much embodies what I believe to be a decent strategy for job applications: tailor the resume to the job description, write a cover letter, apply for the job, then find the email for the recruiter and send a personalized cold email. This is time-consuming, which is why we use AI to make the whole thing a little less painful and a lot faster.</p><h4>What Do You Need?</h4><p>To use the app, you just need a valid OpenAI or Anthropic API key with sufficient funds in your account. Then, you’re all set to check out the app <a href="https://jobbot.streamlit.app/">here</a> and give it a spin by pasting your documents and letting the AI work its magic. ✨</p><p>To build the app, some Python know-how and comfort in connecting APIs are essential. A little familiarity with Streamlit will also go a long way.</p><h4>What does this App do?</h4><p>The core of the app is built around a simple idea: input your resume, the job description of the position you want to apply for, and a bit of personal bio, and let the AI do its thing. The output? Customized resume, cover letter, and cold email are ready for you to use for your application and send to the recruiter.</p><h4>What tech are we using?</h4><p>At its core, the app gives users the flexibility to choose between Anthropic and OpenAI as their chosen AI provider to generate the docs.</p><p>This allows for a more tailored experience, as each provider has its own unique strengths (I personally prefer Anthropic these days).</p><p>To create an intuitive interface, we leverage the simplicity of Streamlit, a Python library that makes it easy to turn scripts into shareable web apps.</p><p>And since I am interested in improving the app based on user feedback, I’ve integrated a Google Sheets backend to collect and store user suggestions.</p><h3>Breaking down the code</h3><p>Let’s dive into the app. We are going to go through the code piece by piece to make sure it’s broken down and easy to follow. We’ll walk through each section, explaining its purpose and how it contributes to the overall functionality of the app.</p><p>First things first: there are just two Python files: generator.py (responsible for generating the content) and app.py (our streamlit user interface)</p><h4>Setting Up the Environment (`generator.py`)</h4><pre>import os<br>import logging<br>from dotenv import load_dotenv<br>import anthropic<br>import openai<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)</pre><p>The initial setup involves importing necessary libraries and configuring logging to help debug and track the app’s performance. `load_dotenv` is used for loading environment variables securely, which includes our API keys for Anthropic and OpenAI, ensuring our app remains secure and functional.</p><h4>Generating Documents</h4><p>Here’s where the real fun begins. We’ve got a function that’s essentially the brain of the operation. You feed it your resume, job description, and a snippet about yourself, and it outputs all the tailored docs you need.</p><pre>def generate_documents(resume, job_description, bio, api_key, ai_provider, formality_level, additional_info):<br>    try:<br>        if not api_key:<br>            logging.error(&quot;API key not provided&quot;)<br>            return None<br>        if ai_provider == &quot;Anthropic&quot;:<br>                    client = anthropic.Anthropic(api_key=api_key)<br>                    logging.info(&quot;Successfully created Anthropic client&quot;)<br>                elif ai_provider == &quot;OpenAI&quot;:<br>                    openai.api_key = api_key<br>                    logging.info(&quot;Successfully set OpenAI API key&quot;)<br>                else:<br>                    logging.error(&quot;Invalid AI provider selected&quot;)<br>                    return None</pre><p>This snippet checks for the API key and decides which AI provider to use based on what the user’s picked in the frontend.</p><h4>Crafting the AI Prompt</h4><p>Next, we add a detailed prompt that guides the AI in generating a tailored resume, cover letter, and cold email. This part is essential for ensuring the outputs are relevant and personalized.</p><pre>system_prompt = (<br>            &quot;You are an expert in early career professional resume crafting, cover letter writing, and cold email composition. &quot;<br>            &quot;Your task is to generate a tailored resume, cover letter, and cold email for a job seeker based on the provided inputs.&quot;<br>        )<br>prompt = (<br>            &quot;Given the following information for the candidate:\n\n&quot;<br>            &quot;Resume:\n{resume}\n\n&quot;<br>            &quot;Job Description:\n{job_description}\n\n&quot;<br>            &quot;Bio/Brief Intro:\n{bio}\n\n&quot;<br>            &quot;Formality Level for the cover letter: {formality_level}\n\n&quot;<br>            &quot;Additional Information: {additional_info}\n\n&quot;<br>            &quot;Please generate the following outputs:\n\n&quot;<br>            &quot;===TAILORED RESUME===\n&quot;<br>            &quot;Tailor the resume to highlight the candidate&#39;s relevant skills and experiences that match the job requirements. &quot;<br>            &quot;Optimize the structure and formatting to make it more visually appealing and ATS-friendly, while maintaining the order of the sections and the exact length as much as possible.\n\n&quot;<br>            &quot;===TAILORED COVER LETTER===\n&quot;<br>            &quot;Craft a personalized cover letter that introduces the candidate, emphasizes their fit for the role, and encourages the recruiter to review the candidate&#39;s resume. &quot;<br>            &quot;Include a brief introduction highlighting the candidate&#39;s interest and fit for the role, specific examples of how their skills and experiences align with the job requirements, &quot;<br>            &quot;and a call-to-action encouraging the recruiter to consider the candidate for the role. Adjust the formality level based on the provided preference.\n\n&quot;<br>            &quot;===CUSTOMIZED COLD EMAIL===\n&quot;<br>            &quot;Generate a customized cold email that greets the recruiter, introduces the candidate, and invites the recruiter to consider the candidate for the role. &quot;<br>            &quot;Adjust the formality level based on the provided preference.\n\n&quot;<br>            &quot;Remember to keep the outputs concise, professional, and tailored to the specific job and candidate details provided. &quot;<br>            &quot;THIS IS VERY IMPORTANT: Ensure that each output section is clearly delineated with the &#39;===SECTION_TITLE===&#39; format.&quot;<br>        ).format(resume=resume, job_description=job_description, bio=bio, formality_level=formality_level, additional_info=additional_info)<br>        logging.info(f&quot;Sending the following prompt to the AI: {prompt}&quot;)<br>        if ai_provider == &quot;Anthropic&quot;:<br>            response = client.messages.create(<br>                model=&quot;claude-3-haiku-20240307&quot;,<br>                max_tokens=4000,<br>                system=system_prompt,<br>                temperature=0.5,<br>                messages=[<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [<br>                            {<br>                                &quot;type&quot;: &quot;text&quot;,<br>                                &quot;text&quot;: prompt<br>                            }<br>                        ]<br>                    }<br>                ]<br>            )<br>            logging.info(&quot;Successfully generated the documents using Anthropic&quot;)<br>            logging.info(f&quot;AI Response: {response.content[0].text.strip()}&quot;)<br>            ai_response = response.content[0].text.strip()<br>        elif ai_provider == &quot;OpenAI&quot;:<br>            response = openai.chat.completions.create(<br>                model=&quot;gpt-4-turbo-preview&quot;,<br>                messages=[<br>                    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt},<br>                ],<br>                temperature=0.5,<br>            )<br>            logging.info(&quot;Successfully generated the documents using OpenAI&quot;)<br>            logging.info(f&quot;AI Response: {response.choices[0].message.content.strip()}&quot;)<br>            ai_response = response.choices[0].message.content.strip()<br>        else:<br>            logging.error(&quot;Invalid AI provider selected&quot;)<br>            return None</pre><p>The prompt is designed to extract the best possible output from the AI, guiding it through the task with specific instructions and inputs. It also helps structure the output in a way that makes it easy for us to extract each document later.</p><h4>Handling the AI Response</h4><p>Once we send the prompt to the chosen AI and receive the output, we need to parse it, splitting it into distinct sections for the resume, cover letter, and email. This parsing is important to then display it properly in the Streamlit UI.</p><pre># Split the AI response into the individual outputs<br>        sections = ai_response.split(&quot;\n\n===&quot;)<br>        outputs = {}<br>        for section in sections:<br>            if section.strip():<br>                section_title = section.strip().split(&quot;\n&quot;)[0].strip(&quot;===&quot;)<br>                section_content = &quot;\n&quot;.join(section.strip().split(&quot;\n&quot;)[1:])<br>                outputs[section_title] = section_content<br>logging.info(f&quot;Outputs: {outputs}&quot;)<br>        return outputs<br>    except Exception as e:<br>        logging.error(f&quot;Error generating documents: {e}&quot;)<br>        return None</pre><p>This section demonstrates how we split the output, organizing it into the 3 documents we will then pass to the frontend.</p><h4>Streamlit Frontend (`app.py`)</h4><p>Now, moving to `app.py`, this is where we create a quick and intuitive interface for users to interact with our app. Streamlit’s straightforward syntax lets us focus on functionality rather than boilerplate code.</p><pre>import streamlit as st<br>from generator import generate_documents<br>import gspread<br>from google.oauth2.service_account import Credentials<br>from google.oauth2 import service_account<br>import toml<br><br>def main():<br>    st.title(&quot;🤖 JobBot: your AI Job Application Sidekick&quot;)<br>    # User input for API key and provider<br>    st.sidebar.title(&quot;API Settings&quot;)<br>    ai_provider_toggle = st.sidebar.toggle(&quot;Select AI Provider&quot;, value=True, key=&quot;ai_provider_toggle&quot;)<br>    if ai_provider_toggle:<br>        ai_provider = &quot;**Anthropic**&quot;<br>        ai_provider_emoji = &quot;🦜&quot;<br>    else:<br>        ai_provider = &quot;**OpenAI**&quot;<br>        ai_provider_emoji = &quot;🤖&quot;<br>    st.sidebar.write(f&quot;You have selected {ai_provider} {ai_provider_emoji}&quot;)<br>    api_key = st.sidebar.text_input(&quot;Enter your API key:&quot;, type=&quot;password&quot;)<br>    if not api_key:<br>        st.sidebar.error(&quot;🚨 Please enter a valid API key to use the app.&quot;)<br>        st.stop()</pre><p>Here, we define our app’s title and proceed to build a form where users can input their resume, job description, and personal bio. This user-friendly interface is the bridge between the user and our AI-powered document generator.</p><h4>User Inputs and Document</h4><p>We guide users through inputting their details and selecting preferences for their application documents. The magic happens when they hit the “Generate Docs” button — our app communicates with the AI, processes the inputs, and generates customized application documents.</p><pre># User inputs<br>    st.subheader(&quot;Paste your resume here 📝&quot;)<br>    resume = st.text_area(&quot;&quot;, height=200, placeholder=&quot;Your resume goes here...&quot;)<br>    st.subheader(&quot;Paste the job description here 📋&quot;)<br>    job_description = st.text_area(&quot;&quot;, height=200, placeholder=&quot;The job description goes here...&quot;)<br>    st.subheader(&quot;Paste your bio/brief intro here 🙋‍♂️&quot;)<br>    bio = st.text_area(&quot;&quot;, height=100, placeholder=&quot;Your bio or brief intro goes here. For example, you can add your LinkedIn summary or a short introduction about yourself.&quot;)<br>    # Additional user inputs<br>    st.sidebar.subheader(&quot;Additional Settings 🔧&quot;)<br>    formality_level = st.sidebar.select_slider(&quot;Formality Level for cover letter and email 📝&quot;, [&quot;Super Casual&quot;, &quot;Casual&quot;, &quot;Neutral&quot;, &quot;Formal&quot;, &quot;Super Formal&quot;], value=&quot;Neutral&quot;)<br>    additional_info = st.sidebar.text_area(&quot;Additional Information 💡&quot;, height=100, placeholder=&quot;Anything else you want the AI to consider or focus on?&quot;)<br>    # Define the output section titles<br>    output_section_titles = {<br>        &quot;Tailored Resume&quot;: &quot;TAILORED RESUME&quot;,<br>        &quot;Tailored Cover Letter&quot;: &quot;TAILORED COVER LETTER&quot;,<br>        &quot;Customized Cold Email&quot;: &quot;CUSTOMIZED COLD EMAIL&quot;<br>    }<br>    if st.button(&quot;✨Generate Docs&quot;):<br>        # Show loader while generating documents<br>        with st.spinner(&quot;🤖AI is cooking up the docs to help with your application, just a few secs! 👨‍🍳&quot;):<br>            # Generate outputs<br>            outputs = generate_documents(resume, job_description, bio, api_key, ai_provider.replace(&quot;**&quot;, &quot;&quot;), formality_level, additional_info)<br>        if outputs:<br>            for section_title, section_key in output_section_titles.items():<br>                if section_key in outputs and outputs[section_key].strip():<br>                    st.subheader(section_title)<br>                    st.code(outputs[section_key], language=&quot;text&quot;)<br>    # How to use section in the sidebar<br>    st.sidebar.subheader(&quot;How to Use 🤖&quot;)<br>    with st.sidebar.expander(&quot;Click here to see a quick guide!&quot;):<br>        st.markdown(&quot;&quot;&quot;<br>        - 📝 Copy and paste your resume<br>        - 📋 Copy and paste the job description you&#39;re applying for<br>        - 🙋‍♂️ Provide a brief bio/intro about yourself<br>        - 🔧 Pick the formality level for the cover letter and email (default works well for most cases)<br>        - 💡 Add any additional information you want the AI to consider (optional)<br>        - 🚀 Click the &quot;Generate Documents&quot; button and let the magic happen!✨<br>        &quot;&quot;&quot;)</pre><p>This section of the code captures user inputs and triggers the document generation process, this is the app’s core functionality.</p><h4>Gathering user feedback (Google Sheets integration)</h4><p>If you are interested in implementing in your app, this is how we gather feedback and store it in a Google Sheet.</p><p>In addition to the core functionality of the app, I included a user feedback form in the sidebar. This allows users to share their thoughts, suggestions, and any features they’d find useful. The feedback is then stored in a Google Sheet, this way we can improve the app based on user input.</p><p>The feedback form is built using Streamlit’s form functionality. Users can simply enter their thoughts in the text area and click the “Submit Feedback” button. Behind the scenes, the app sets up the Google Sheets API using the TOML secrets provided in the Streamlit environment. Once the feedback is submitted, the app appends the user’s input to a dedicated worksheet in the Google Sheet, making it easy to review and keep the app evolving based on user’s inputs.</p><p>Here’s the code:</p><pre># Feedback form in the sidebar<br>    with st.sidebar:<br>        st.subheader(&quot;Got Feedback or features you&#39;d find useful? 📮&quot;)<br>        # Start of the form<br>        with st.form(key=&#39;feedback_form&#39;):<br>            feedback = st.text_area(&quot;Share your thoughts with me here:&quot;)<br>            submit_feedback = st.form_submit_button(label=&#39;Submit Feedback 🙌&#39;)<br>            if submit_feedback:<br>                # Set up the Google Sheets API using TOML secrets<br>                try:<br>                    secrets = {<br>                        &quot;type&quot;: st.secrets[&quot;type&quot;],<br>                        &quot;project_id&quot;: st.secrets[&quot;project_id&quot;],<br>                        &quot;private_key_id&quot;: st.secrets[&quot;private_key_id&quot;],<br>                        &quot;private_key&quot;: st.secrets[&quot;private_key&quot;],<br>                        &quot;client_email&quot;: st.secrets[&quot;client_email&quot;],<br>                        &quot;client_id&quot;: st.secrets[&quot;client_id&quot;],<br>                        &quot;auth_uri&quot;: st.secrets[&quot;auth_uri&quot;],<br>                        &quot;token_uri&quot;: st.secrets[&quot;token_uri&quot;],<br>                        &quot;auth_provider_x509_cert_url&quot;: st.secrets[&quot;auth_provider_x509_cert_url&quot;],<br>                        &quot;client_x509_cert_url&quot;: st.secrets[&quot;client_x509_cert_url&quot;],<br>                        &quot;universe_domain&quot;: st.secrets[&quot;universe_domain&quot;]<br>                    }<br>                    creds = service_account.Credentials.from_service_account_info(<br>                        secrets,<br>                        scopes=[&#39;https://spreadsheets.google.com/feeds&#39;, &#39;https://www.googleapis.com/auth/spreadsheets&#39;, &#39;https://www.googleapis.com/auth/drive&#39;]<br>                    )<br>                    client = gspread.authorize(creds)<br>                    # Open the Google Sheet and append the feedback<br>                    sh = client.open(&#39;prototype_feedback&#39;).worksheet(&#39;Feedback&#39;)<br>                    sh.append_row([feedback])<br>                    st.sidebar.success(&quot;Thanks for your feedback! 🙏&quot;)<br>                except Exception as e:<br>                    st.sidebar.error(f&quot;Error: {e}&quot;)</pre><p>This is what our user interface looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dh2ua8bCogdSOc92tDdEdg.png" /><figcaption>Image from the author — Made with ❤️ and Python.</figcaption></figure><h3>Wrapping up and Trying It Out</h3><p>That’s all for this article! Dive into the code to build your own version by visiting the <a href="https://github.com/alessandroamenta/AIJobKit">GitHub repo</a>. You can also give the app a try <a href="https://jobbot.streamlit.app/">here</a>. Please remember to make sure you have a valid OpenAI or Anthropic API key!</p><p>Excited to hear your feedback or any cool ideas you might have for further enhancements. This is just the starting point, I would love to make the job-hunting process as automated and painless as possible.</p><p>If you found this article useful, consider expressing your appreciation with 50 claps 👏 — your support means a ton.</p><p>Thanks for following along, and happy coding! :)</p><p>All images are by me, the author, unless otherwise noted. Apart from being a user, I have no affiliation with OpenAI, Streamlit, Anthropic or any other organisation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccac2a6de673" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/job-hunting-is-annoying-build-an-ai-assistant-to-automate-the-application-process-ccac2a6de673">Job Hunting Is Annoying. Build an AI Assistant to Automate the Application process.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI-powered Meditation Coach in Just 100 Lines of Code]]></title>
            <link>https://levelup.gitconnected.com/build-an-ai-powered-meditation-coach-in-just-100-lines-of-code-18b7acdfa621?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b7acdfa621</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[calm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 23:22:33 GMT</pubDate>
            <atom:updated>2024-03-05T23:22:33.263Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick experiment with GPT-4 and ElevenLabs TTS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y917CpIrU2a1VytC" /><figcaption>Image generated with DALL-E 3</figcaption></figure><p>It’s always exciting to play around with new tech and test out new idea/products we can create with it. Couple days ago, I decided to challenge myself to see if I could generate a human-like sounding guided meditation experience using just 100 lines of code.</p><p>The goal? Simple: combine the capabilities of GPT-4 and ElevenLabs’ APIs to create a seamless meditation experience.</p><p>This turned into quite a fun experiment. One of the trickier parts was figuring out how to include pauses in the text-to-speech (TTS) output. Since directly pausing TTS isn’t an option, I had to come up with a workaround. After all, what’s a meditation session without those essential moments of silence?</p><h3>The Approach</h3><p>Alright, here’s the plan: First up, we get GPT-4 to create a meditation script for us. We craft a specific prompt that guides GPT-4 to sprinkle ‘ — -PAUSE — -’ markers throughout the script.</p><p>After the script is generated, we then split it into segments automatically, thanks to the pause markers GPT-4 included, following our prompt instructions.</p><p>Next, we use ElevenLabs TTS to give each segment a calm and human-like voice, transforming our text into audio segments.</p><p>Finally, we take all these audio segments, stitch them together, and insert pauses between each one. And that’s it!</p><p>Now, let’s dive into the code!</p><h3>Setup</h3><p>First things first, let’s talk about the tools. For this project, I used OpenAI’s GPT-4 to generate the meditation script and ElevenLabs’ API for the text-to-speech functionality.</p><p>You could also opt for OpenAI TTS models instead of ElevenLabs, but honestly, the voice options feel a bit limited there. Plus, the ElevenLabs voices just sound more real, more human. It kinda makes the whole meditation feel more genuine.</p><p>Here’s a quick setup of our environment, including importing necessary libraries and loading API keys from environment variables:</p><pre>import logging<br>import os<br>from dotenv import load_dotenv<br>from openai import OpenAI<br>from pydub import AudioSegment<br>from elevenlabs import generate, Voice, VoiceSettings<br><br># Setting up logging<br>logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br><br># Loading environment variables<br>load_dotenv()<br>ELEVEN_API_KEY = os.getenv(&#39;ELEVENLABS_API_KEY&#39;)<br>OPENAI_API_KEY = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>client = OpenAI(api_key=OPENAI_API_KEY)<br><br># Initializing final_audio as a silent segment<br>final_audio = AudioSegment.silent(duration=0)</pre><h3>Generating the Meditation Script</h3><p>The heart of our meditation app is, of course, the script. Using GPT-4, we prompt the model to create a meditation script focused on mindfulness and breath control.</p><p>The prompt for GPT-4 to craft the script is important here, we need to make sure to specify the need for ‘ — -PAUSE — -’ markers (or any markers of your choice). These markers enable us to later split the script into segments for a segmented TTS generation. It’s a trick to programmatically insert pauses in the meditation session, making the experience as close to a guided, in-person session as possible.</p><p>Here’s how we do it:</p><pre>logging.info(&quot;Starting meditation script generation...&quot;)<br><br># Detailed prompt for GPT-4 to ensure inclusion of &#39;---PAUSE---&#39; markers<br>prompt = (<br>    &quot;Create a script for a 5-minute cohesive meditation session, with a strict focus on mindfulness and breath control. The script must meticulously adhere to approximately 4000 characters, aligning precisely with the session&#39;s duration. &quot;<br>    &quot;Crucially, it is imperative to include &#39;---PAUSE---&#39; markers at carefully considered transition points, ensuring a seamless flow into periods of silent reflection or focused breathing exercises. &quot;<br>    &quot;Prior to each &#39;---PAUSE---&#39; marker, the script should naturally and gently guide the listener toward the pause, facilitating a smooth transition without any abruptness. For instance, use phrases such as &#39;Let&#39;s now gently turn our attention to our breath, allowing ourselves to fully experience the rhythm of each inhale and exhale,&#39; or &#39;At this moment, let&#39;s simply be with our breath, feeling the calmness with each breath cycle.&#39; &quot;<br>    &quot;These guiding phrases are essential, serving as soft introductions to the &#39;---PAUSE---&#39; markers and are vital for the meditation&#39;s integrity, ensuring participants are thoughtfully led into each pause. &quot;<br>    &quot;The script’s length, closely adhering to the 4000 character guideline, and the strategic, gentle introduction of &#39;---PAUSE---&#39; markers are both crucial. They work together to create a meditation experience that is both impactful and seamlessly executed from start to finish, providing natural intervals for reflection or breathing without sudden interruptions. &quot;<br>    &quot;Please ensure the language used throughout the script is simple, clear, and approachable, making the meditation accessible and engaging for everyone.&quot;<br>)<br><br># Generate the meditation script with GPT-4<br>response = client.chat.completions.create(<br>    model=&quot;gpt-4-turbo-preview&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt},<br>    ],<br>    temperature=0.7,<br>)<br>meditation_script = response.choices[0].message.content<br>logging.info(&quot;Meditation script generated successfully.&quot;)</pre><h3>Putting it all together</h3><p>To create a true meditation experience, pauses are essential. However, ElevenLabs’ TTS does not inherently support pauses. My workaround involved splitting the script at designated ‘ — -PAUSE — -’ markers and inserting silence between audio segments.</p><p>But it’s not just about the pauses. It’s also where we take our written meditation script and turn it into something you can listen to, complete with quiet moments just like in a real-life session. We’re basically stitching together words and silence in a way that feels smooth and natural.</p><p>Here’s the code:</p><pre># Begin audio processing for each script segment<br>logging.info(&quot;Starting audio processing for segments...&quot;)<br># Split the script into segments<br>segments = meditation_script.split(&#39;---PAUSE---&#39;)<br>one_minute_silence = AudioSegment.silent(duration=60000)  # 60 seconds of silence<br><br># Generate and combine segments with pauses<br>for i, segment in enumerate(segments):<br>    # Logging the processing of each segment with TTS<br>    logging.info(f&quot;Processing segment {i+1} with TTS...&quot;)<br><br>    # Generate the audio using ElevenLabs&#39; text-to-speech<br>    audio_response = generate(<br>        api_key=ELEVEN_API_KEY,<br>        text=segment,<br>        voice=Voice(<br>            voice_id=&#39;RrkF2QZOPA1PyW4EamJj&#39;,<br>            settings=VoiceSettings(speaking_rate=0.8, stability=0.71, similarity_boost=0.5, style=0.0, use_speaker_boost=True)<br>        ),<br>        model=&quot;eleven_monolingual_v1&quot;,<br>        output_format=&quot;mp3_44100_128&quot;  # Specify MP3 as the output format<br>    )<br><br>    # Save the audio data to a file, using MP3 format directly<br>    temp_audio_file = f&quot;segment_{i}.mp3&quot;<br>    with open(temp_audio_file, &quot;wb&quot;) as f:<br>        f.write(audio_response)<br><br>    # Load the segment audio and append to the final audio<br>    segment_audio = AudioSegment.from_file(temp_audio_file, format=&quot;mp3&quot;)<br>    final_audio += segment_audio<br><br>    # Add pause after each segment except the last one<br>    if i &lt; len(segments) - 1:<br>        final_audio += one_minute_silence<br><br>    # Clean up the temporary file<br>    os.remove(temp_audio_file)<br><br># Logging the completion of audio processing<br>logging.info(&quot;Audio processing completed successfully.&quot;)<br><br># Export the final audio file<br>final_audio.export(&quot;meditation_sesh_audio.mp3&quot;, format=&quot;mp3&quot;)<br><br># Logging the successful creation of the final audio file<br>logging.info(&quot;Meditation audio with pauses created and exported successfully.&quot;)</pre><h3>The Result</h3><p>Curious to hear an AI-generated meditation session in action? You can listen to the output by visiting this link and clicking “view raw” to download: <a href="https://github.com/alessandroamenta/dora.ai/blob/main/meditation_sesh_audio.mp3">Meditation Session Audio</a>.</p><h3>Wrapping up</h3><p>That’s all for this article! What started as a simple coding challenge turned into a proof of concept for a minimalist, AI-powered meditation app.</p><p>The code in this article is pretty basic, just a starting point, but I’m excited to work at it day by day and see where it can go with more development and community input. Slowly turning it into an actual product.</p><p>If you are curious about the code in this article and how this projuct will evolve you can take a look at the repo on my GitHub: <a href="https://github.com/alessandroamenta/dora.ai">dora.ai</a>.</p><p>If you found this article interesting, consider expressing your appreciation with 50 claps 👏 and following me on Twitter/X <a href="https://twitter.com/ale_amenta">@ale_amenta</a>. I post daily about indie hacking and anything I learn while building new projects in public — your support really means a ton.</p><p>Thanks for following along, and happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b7acdfa621" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-an-ai-powered-meditation-coach-in-just-100-lines-of-code-18b7acdfa621">Build an AI-powered Meditation Coach in Just 100 Lines of Code</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping up with ML Research: A Tool to Navigate the ML Innovation Maze]]></title>
            <link>https://pub.towardsai.net/keeping-up-with-ml-research-a-tool-to-navigate-the-ml-innovation-maze-42c7ba0d3b62?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c7ba0d3b62</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 00:02:02 GMT</pubDate>
            <atom:updated>2024-02-22T00:02:02.368Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cut Through the Clutter of ML Conferences with Semantic Search and Dynamic Visualization.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZCMj30n7c_07dYvK" /><figcaption>Image generated with DALL-E 3</figcaption></figure><p>In the fast-paced world of Machine Learning (ML) research, keeping up with the latest findings is crucial and exciting, but let’s be honest — it’s also a challenge. With a constant stream of advancements and new publications, it’s tough to pinpoint the research that matters to you.</p><p>The typical conference website is filled with fascinating new papers, yet their interfaces leave much to be desired — they’re often clunky and make it hard to zero in on the content that’s relevant and interesting to you. This can make the search for new papers time-intensive and a bit frustrating.</p><p>Enter ML Conference Paper Explorer: your sidekick in navigating the ML paper maze with ease. It’s all about getting you to the papers you need without the hassle.</p><h3>Why We Built This</h3><p>The challenge is real: each ML conference presents a crazy number of papers, usually in the order of thousands, often listed one after the other without a practical way to filter through the noise. Often there is no search at all, it’s literally just a list. In an age where ML is reshaping the future, why is accessing its knowledge still so impractical? Official conference websites, while informative, aren’t exactly user-friendly or conducive to discovery.</p><p>So, that’s why we built this: a streamlined platform that not only aggregates and organizes papers from all the major ML conferences but also makes finding the papers you are interested in a lot more straightforward.</p><h3>What the Project Does and Architecture</h3><p>Overall here’s what the project does: it aggregates all the accepted papers from the latest ML conferences into one database. We use custom built scrapers to collect the papers and turn them into text embeddings to make them searchable and visualize the data.</p><ul><li><strong>Scraping &amp; Fetching:</strong> We’ve developed specialized scrapers and fetchers for each conference, for instance, the Openacess scraper and Arxiv fetcher work together to reel in all the accepted papers from <a href="https://openaccess.thecvf.com/ICCV2023?day=all">ICCV</a>.</li><li><strong>Data Storage: </strong>Important paper details — title, abstract, authors, URL, year, and conference name — are saved in a JSON file in the repo (papers_repo.json), ready for quick keyword searches and filtering.</li><li><strong>Embeddings: </strong>Using OpenAI’s text embeddings (ada 002), we transform paper titles and abstracts into embeddings, which we store in a vector DB (Pinecone). This enables semantic or unified search.</li><li><strong>Interactive Visualization: </strong>Using t-SNE and Bokeh, we plot all of the embeddings in our vectorDB, so that the user can visually navigate through research clusters.</li></ul><h3>A Glimpse into the Code</h3><p>Our scrapers are the backbone of the data collection process. Here’s an insight into their architecture:</p><pre>class Scraper:<br>    def get_publications(self, url):<br>        raise NotImplementedError(&quot;Subclasses must implement this method!&quot;)<br><br>class OpenAccessScraper(Scraper):<br>    def __init__(self, fetcher, num_papers=None):<br>        self.fetcher = fetcher<br>        self.num_papers = num_papers<br>        logger.info(&quot;OpenAccessScraper instance created with fetcher %s and num_papers_to_scrape %s&quot;, fetcher, num_papers)<br><br>    def get_publications(self, url, num_papers=None):<br>        logger.info(&quot;Fetching publications from URL: %s&quot;, url)<br>        try:<br>            response = requests.get(url)<br>            response.raise_for_status()<br>        except requests.exceptions.RequestException as e:<br>            logger.error(&quot;Request failed for URL %s: %s&quot;, url, e)<br>            return []<br><br>        soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br>        papers = []<br><br>        arxiv_anchors = [anchor for anchor in soup.find_all(&#39;a&#39;) if &#39;arXiv&#39; in anchor.text]<br>        logger.debug(&quot;Found %d arXiv anchors&quot;, len(arxiv_anchors))<br><br>        # If num_papers_to_scrape is defined, limit the number of papers<br>        if self.num_papers:<br>            arxiv_anchors = arxiv_anchors[:self.num_papers]<br>            logger.info(&quot;Limiting the number of papers to scrape to %d&quot;, self.num_papers)<br><br>        for anchor in arxiv_anchors:<br>            title = anchor.find_previous(&#39;dt&#39;).text.strip()<br>            link = anchor[&#39;href&#39;]<br>            arxiv_id = link.split(&#39;/&#39;)[-1]<br><br>            abstract, authors = self.fetcher.fetch(arxiv_id)<br>            papers.append({&#39;title&#39;: title, &#39;url&#39;: link, &#39;abstract&#39;: abstract, &#39;authors&#39;: authors})<br><br>        logger.info(&quot;Successfully fetched %d papers&quot;, len(papers))<br>        return papers<br><br>-----------------------------------------------------------------------------<br><br>class PublicationFetcher(metaclass=ABCMeta):<br>    &#39;&#39;&#39;Abstract base class for publication fetchers.&#39;&#39;&#39;<br>    @abstractmethod<br>    def fetch(self, publication_id):<br>        &#39;&#39;&#39;Fetches the publication content from the source and returns it.&#39;&#39;&#39;<br>        raise NotImplementedError(&quot;Subclasses must implement this method!&quot;)<br><br>class ArxivFetcher(PublicationFetcher):<br>    def fetch(self, arxiv_id):<br>        logger.debug(f&quot;Attempting to fetch publication {arxiv_id} from arXiv&quot;)<br>        api_url = f&quot;http://export.arxiv.org/api/query?id_list={arxiv_id}&quot;<br>        headers = {<br>            &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3&#39;<br>        }<br>        <br>        # Implementing retries with exponential backoff<br>        max_retries = 5<br>        retry_delay = 1  # Start with 1 second delay<br>        for attempt in range(max_retries):<br>            try:<br>                response = requests.get(api_url, headers=headers)<br>                response.raise_for_status()  # Check for HTTP request errors<br>                logger.debug(&quot;Successfully fetched the data on attempt #%d&quot;, attempt + 1)<br>                break  # Success, exit retry loop<br>            except requests.exceptions.RequestException as e:<br>                logger.warning(&quot;Attempt #%d failed with error: %s. Retrying in %d seconds...&quot;, attempt + 1, e, retry_delay)<br>                time.sleep(retry_delay)<br>                retry_delay *= 2  # Exponential backoff<br>        else:<br>            # Failed all retries<br>            logger.error(&quot;Failed to fetch publication %s after %d attempts.&quot;, arxiv_id, max_retries)<br>            return None, None<br><br>        soup = BeautifulSoup(response.content, &#39;xml&#39;)<br>        entry = soup.find(&#39;entry&#39;)<br>        abstract = entry.find(&#39;summary&#39;).text.strip()<br>        authors = [author.find(&#39;name&#39;).text for author in entry.find_all(&#39;author&#39;)]<br><br>        logger.info(&quot;Successfully fetched publication %s from arXiv&quot;, arxiv_id)<br>        return abstract, authors</pre><h3>Current Progress and Future Plans</h3><p>This is just the start — version 0 of our project. We’ve already brought together over 10,000 papers from six key conferences. And this is only the beginning; we’re continuously adding and refining features. There’s plenty of room for improvement, and your insights and patience are invaluable to us during this phase of active development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Hctc_q0SArxRyjZbc4lj5A.png" /><figcaption>Image from the author.</figcaption></figure><p>You can give the current version a spin <a href="https://mlpapers.streamlit.app/">here</a>, or dive into the <a href="https://github.com/alessandroamenta/paperEmbeds/tree/feature/embeddings-storage">codebase</a>. We update regularly, so check back often to see the latest updates!</p><h3>Looking Ahead</h3><p>Turning papers into embeddings does more than make them easier to find — it helps us spot the big picture. Which research topics are on the rise? What’s the next big thing in ML? Our platform is built to do more than just find papers quickly. It’s about giving you a clearer view of where ML research is heading. Check back with us every month to see new updates and insights we’ve dug up!</p><p>Here’s a quick look at app.py, where we bring it all together with a simple Streamlit UI:</p><pre>import os<br>import json<br>import pandas as pd<br>import streamlit as st<br>from dotenv import load_dotenv<br>import streamlit.components.v1 as components<br><br>from bokeh.plotting import figure<br>from bokeh.models import HoverTool, ColumnDataSource<br>from bokeh.resources import CDN<br>from bokeh.embed import file_html<br><br>from store import EmbeddingStorage<br><br># Load environment variables<br>load_dotenv()<br><br># Initialize embedding storage with API keys and index name<br>embedding_storage = EmbeddingStorage(<br>        pinecone_api_key=os.getenv(&quot;PINECONE_API_KEY&quot;),<br>        openai_api_key=os.getenv(&quot;OPENAI_API_KEY&quot;),<br>        pinecone_index_name=&quot;ml-conferences&quot;<br>    )<br><br># Configure the page<br>st.set_page_config(page_title=&quot;ML Conference Papers Explorer 🔭&quot;, layout=&quot;wide&quot;)<br><br># Cache and read publications from a JSON file<br>@st.cache_data<br>def read_parsed_publications(filepath):<br>    &quot;&quot;&quot;Read and parse publication data from a JSON file.&quot;&quot;&quot;<br>    try:<br>        with open(filepath, &#39;r&#39;) as f:<br>            data = json.load(f)<br>        # Format authors as a comma-separated string<br>        for item in data:<br>            if isinstance(item.get(&#39;authors&#39;), list):<br>                item[&#39;authors&#39;] = &#39;, &#39;.join(item[&#39;authors&#39;])<br>        return data<br>    except FileNotFoundError:<br>        st.error(&quot;Publication file not found. Please check the file path.&quot;)<br>        return []<br><br># Filter publications based on user query and selections<br>def filter_publications(publications, query, year, conference):<br>    &quot;&quot;&quot;Filter publications by title, authors, year, and conference.&quot;&quot;&quot;<br>    filtered = []<br>    for pub in publications:<br>        if query.lower() in pub[&#39;title&#39;].lower() or query.lower() in pub[&#39;authors&#39;].lower():<br>            if year == &#39;All&#39; or pub[&#39;conference_year&#39;] == year:<br>                if conference == &#39;All&#39; or pub[&#39;conference_name&#39;] == conference:<br>                    filtered.append(pub)<br>    return filtered<br><br># Perform a unified search combining filters and semantic search<br>def unified_search(publications, query, year, conference, top_k=5):<br>    &quot;&quot;&quot;Combine semantic and filter-based search to find relevant papers.&quot;&quot;&quot;<br>    filtered = filter_publications(publications, &quot;&quot;, year, conference)<br>    if query:  # Use semantic search if there&#39;s a query<br>        semantic_results = embedding_storage.semantic_search(query, top_k=top_k)<br>        semantic_ids = [result[&#39;id&#39;] for result in semantic_results[&#39;matches&#39;]]<br>        filtered = [pub for pub in filtered if pub[&#39;title&#39;] in semantic_ids]<br>    return filtered<br><br># Define file paths and load publications<br>PUBLICATIONS_FILE = &#39;papers_repo.json&#39;<br>existing_papers = read_parsed_publications(PUBLICATIONS_FILE)<br><br># Setup sidebar filters for user selection<br>st.sidebar.header(&#39;Filters 🔍&#39;)<br>selected_year = st.sidebar.selectbox(&#39;Year&#39;, [&#39;All&#39;] + sorted({paper[&#39;conference_year&#39;] for paper in existing_papers}, reverse=True))<br>selected_conference = st.sidebar.selectbox(&#39;Conference&#39;, [&#39;All&#39;] + sorted({paper[&#39;conference_name&#39;] for paper in existing_papers}))<br><br># Main search interface<br>search_query = st.text_input(&quot;Enter keywords, topics, or author names to find relevant papers:&quot;, &quot;&quot;)<br>filtered_papers = unified_search(existing_papers, search_query, selected_year, selected_conference, top_k=10)<br><br># Display search results<br>if filtered_papers:<br>    df = pd.DataFrame(filtered_papers)<br>    st.write(f&quot;Found {len(filtered_papers)} matching papers 🔎&quot;, df[[&#39;title&#39;, &#39;authors&#39;, &#39;url&#39;, &#39;conference_name&#39;, &#39;conference_year&#39;]])<br>else:<br>    st.write(&quot;No matching papers found. Try adjusting your search criteria.&quot;)<br><br># t-SNE plot visualization<br>@st.cache_data<br>def read_tsne_data(filepath):<br>    &quot;&quot;&quot;Read t-SNE data from a file.&quot;&quot;&quot;<br>    with open(filepath, &#39;r&#39;) as f:<br>        return json.load(f)<br><br>tsne_data = read_tsne_data(&#39;tsne_results.json&#39;)<br><br># Assign colors to conferences for visualization<br>conference_colors = {<br>    &#39;ICLR&#39;: &#39;blue&#39;,<br>    &#39;ICCV&#39;: &#39;green&#39;,<br>    &#39;NeurIPS&#39;: &#39;red&#39;,<br>    &#39;CVPR&#39;: &#39;orange&#39;,<br>    &#39;EMNLP&#39;: &#39;purple&#39;,<br>    &#39;WACV&#39;: &#39;brown&#39;<br>}<br><br># Prepare data for plotting<br>source = ColumnDataSource({<br>    &#39;x&#39;: [item[&#39;x&#39;] for item in tsne_data],<br>    &#39;y&#39;: [item[&#39;y&#39;] for item in tsne_data],<br>    &#39;title&#39;: [item[&#39;id&#39;] for item in tsne_data],<br>    &#39;conference_name&#39;: [item[&#39;conference_name&#39;] for item in tsne_data],<br>    &#39;color&#39;: [conference_colors.get(item[&#39;conference_name&#39;], &#39;grey&#39;) for item in tsne_data], <br>})<br><br># Setup the plot<br>p = figure(title=&#39;ML Conference Papers Visualization&#39;, x_axis_label=&#39;Dimension 1&#39;, y_axis_label=&#39;Dimension 2&#39;, width=800, tools=&quot;pan,wheel_zoom,reset,save&quot;)<br>hover = HoverTool(tooltips=[(&#39;Title&#39;, &#39;@title&#39;), (&#39;Conference&#39;, &#39;@conference_name&#39;)])<br>p.add_tools(hover)<br>p.circle(&#39;x&#39;, &#39;y&#39;, size=5, source=source, alpha=0.6, color=&#39;color&#39;)<br><br># Render the t-SNE plot<br>html = file_html(p, CDN, &quot;t-SNE Plot&quot;)<br>components.html(html, height=800)<br><br># Add a footer<br>st.markdown(&quot;---&quot;)<br>st.markdown(&quot;🚀 Made by Alessandro Amenta and Cesar Romero, with Python and lots of ❤️ for the ML community.&quot;)</pre><p>Here’s what the Streamlit frontend offers: you can apply filters and do semantic searches across all the papers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrOwYM1yMlcn_zVT8OAthw.png" /><figcaption>Image from the Author.</figcaption></figure><p>And here’s how we display the data: we visualize research paper clusters using t-SNE, making it easy to see how different papers from different conferences are related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuUZoRVeL1FuHNyTB11m3g.png" /><figcaption>Image from the Author.</figcaption></figure><h3><strong>Wrapping up and improvements</strong></h3><p>We’re nearly ready to open up for contributions and we’d welcome your ideas or feedback even before that. If you’ve got suggestions or improvements, let me know. Help make this tool better for everyone in the ML community. Keep an eye out on the <a href="https://github.com/alessandroamenta/paperEmbeds/tree/feature/embeddings-storage">Github repo</a>— we’ll be opening up for contributions in a couple of weeks! 🚀🔍</p><p>Should you find this project useful, consider expressing your appreciation with 50 claps 👏 and giving the repo a star 🌟— your support means a ton.</p><p>Thanks for following along and happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c7ba0d3b62" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/keeping-up-with-ml-research-a-tool-to-navigate-the-ml-innovation-maze-42c7ba0d3b62">Keeping up with ML Research: A Tool to Navigate the ML Innovation Maze</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI-powered LinkedIn profile reviewer: OpenAI Assistants API and Gpt-4-vision]]></title>
            <link>https://levelup.gitconnected.com/build-an-ai-powered-linkedin-profile-reviewer-openai-assistants-api-and-gpt-4-vision-cb8faca91731?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb8faca91731</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 15:57:51 GMT</pubDate>
            <atom:updated>2024-02-13T11:30:29.431Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Deep Dive into experimenting with GPT-4 Vision and Assistants API</h4><p>Many of us have tinkered with building apps using OpenAI’s APIs, and there’s a plethora of articles on Medium about it. However, what I suspect many readers have not yet experimented with — at least at the time of writing this article — is building with the Assistants API. There are good reasons for this: for starters, it’s still in beta; secondly, it doesn’t support streaming, which can be frustrating for impatient users. Despite its quirks, it is definitely worth exploring — it offers built-in support for thread management, features like retrieval, code interpretation, and function calling, enabling developers to create more sophisticated AI assistants with less overhead. So, when the new updates are rolled out, it will be even more advantageous to build your AI apps with it.</p><p>For now, though, considering it’s still quite new and lacking extensive tutorials or documentation, I decided to dive in and build a small prototype myself. That’s what this article is all about.</p><h3>So, What Will We Build?</h3><p>Among the ideas that came to mind, I settled on creating an assistant that focuses on optimizing the user’s LinkedIn profile. This idea stemmed from a conversation with a good friend who has been job-seeking recently and asked for LinkedIn profile tips. Not being an expert myself, I thought, why not build one — an expert? And while at it, why not seize the opportunity to experiment with the Assistants API and have some fun? Thus, a plan was formed, and all I needed to do was bring it all together.</p><p>The outcome, even just as a prototype, is quite impressive — the assistant does a remarkable job advising the user on what to work on, change, improve, and even provides a score for the entire profile.</p><p>Let’s get into it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zTUWQETKXQZ37caL" /><figcaption>Image generated with DALL-E 3</figcaption></figure><h3>How It Works:</h3><h4>The User Experience</h4><p>Users start by inputting their LinkedIn profile URL, and then the magic begins. In the backend, a three-step process unfolds:</p><ol><li><strong>Scraping the LinkedIn Profile:</strong> Extract relevant information from the user’s profile, including the profile image.</li><li><strong>Image Analysis via GPT-4 Vision:</strong> Utilizing function calling, the profile image is analyzed to assess its suitability and effectiveness for a professional LinkedIn presence.</li><li><strong>Comprehensive Profile Review:</strong> The textual data and image analysis are synthesized by the Assistant into a detailed report with actionable suggestions for improvement.</li></ol><p>After displaying the initial analysis, users can continue their conversation with the assistant for further insights.</p><h4>Building It Up and Breaking Down the Code:</h4><p>The app comprises three simple scripts:</p><ul><li><strong>main.py:</strong> Creates the Assistant with a predefined knowledge base and the added ability to analyze profile pictures.</li><li><strong>linkedin_scraper.py:</strong> Scrapes the LinkedIn profile, extracting details and the profile image URL for analysis.</li><li><strong>app.py: </strong>The user interface, built with Streamlit, allows profile submission and displays the AI-generated recommendations.</li></ul><h3>Part 1: Creating the assistant — main.py:</h3><p>The first step involves creating the Assistant, which can be done via the <a href="https://platform.openai.com/playground">OpenAI platform’s playground</a> or directly in the code for local execution (which is what main.py is all about). The Assistants API supports three tools: Code Interpreter, Retrieval, and Function Calling. We will enable the assistant with both data retrieval and function calling:</p><ul><li><strong>Data Retrieval:</strong> By uploading a collection of 6 PDFs containing expert advice on LinkedIn profile improvement, the Assistant can draw upon this knowledge base for analysis.</li><li><strong>Function Calling for Image Analysis:</strong> Although the Assistants API lacks built-in vision capabilities, we can utilize GPT-4 Vision. We need to connect it to the assistant using a custom function that is automatically called when needed. This gives our assistant the capability to visually analyze the user’s profile picture and provide feedback.</li></ul><h4>Workflow of Integrating the Assistants API in main.py</h4><ul><li><strong>Create an Assistant:</strong> Define the assistant’s instructions and select a model (I chose gpt-4-turbo-preview). Enable Retrieval and Function Calling.</li><li><strong>Initiate a Conversation Thread:</strong> Begin a new thread whenever a user starts a conversation with the assistant.</li><li><strong>Add User Queries as Messages:</strong> Populate the thread with messages as the user asks questions.</li><li><strong>Activate the Assistant on the Thread:</strong> The assistant generates responses based on the thread’s content, automatically invoking the relevant tools as needed.</li></ul><p>The create_linkedin_profile_analyzer function contains the logic for initializing our Assistant. This includes uploading the PDF files to form our knowledge base. These documents are uploaded to OpenAI, and their IDs are used to enable the assistant&#39;s retrieval feature, permitting it to leverage this knowledge base when analyzing user profiles. The custom function for image analysis, analyze_profile_picture, is designed to be invoked by the Assistant automatically whenever an image URL is provided, allowing for the assessment of profile pictures against professional standards. Here is the code:</p><pre>import json<br>import os<br>from dotenv import load_dotenv<br><br>from openai import OpenAI<br><br>load_dotenv() <br><br>api_key = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>client = OpenAI(api_key=api_key)<br><br># Define the function for creating the Assistant<br>def create_linkedin_profile_analyzer():<br>    # List of PDF files<br>    pdf_files = [<br>        &quot;file1.pdf&quot;,<br>        &quot;file2.pdf&quot;,<br>        &quot;file3.pdf&quot;,<br>        &quot;file4.pdf&quot;,<br>        &quot;file5.pdf&quot;,<br>        &quot;file6.pdf&quot;<br>    ]<br><br>    # Path to the directory containing the PDFs<br>    pdf_directory = &quot;knowledge&quot;  # Adjust the path as necessary<br><br>    # Upload documents for Retrieval<br>    file_ids = []<br>    for pdf_file in pdf_files:<br>        file_path = os.path.join(pdf_directory, pdf_file)<br>        with open(file_path, &quot;rb&quot;) as file_data:<br>            file = client.files.create(file=file_data, purpose=&quot;assistants&quot;)<br>            file_ids.append(file.id)<br><br>    # Create the Assistant with necessary tools<br>    assistant = client.beta.assistants.create(<br>        name=&quot;LinkedIn Profile Analyzer&quot;,<br>        instructions = (<br>            &quot;You are an expert in LinkedIn profile optimization, tasked with providing a comprehensive analysis &quot;<br>            &quot;of a user&#39;s LinkedIn profile, analyze it thoroughly. Be helpful, &quot;<br>            &quot;and maintain a casual, approachable yet professional tone. Remember to address the user directly and use the first person.\n&quot;<br>            &quot;- analyze_profile_picture, when the image url of the profile is given.&quot;<br>        ),<br>        model=&quot;gpt-4-turbo-preview&quot;,<br>        tools=[<br>            {&quot;type&quot;: &quot;retrieval&quot;, &quot;file_ids&quot;: file_ids},<br>            {&quot;type&quot;: &quot;function&quot;, &quot;function&quot;: function_json}<br>        ]<br>    )<br>    return assistant<br><br># Define the function to create thread and run<br>def create_thread_and_run(assistant_id, user_message):<br>    thread = client.beta.threads.create()<br>    client.beta.threads.messages.create(<br>        thread_id=thread.id, role=&quot;user&quot;, content=user_message<br>    )<br>    return client.beta.threads.runs.create(<br>        thread_id=thread.id,<br>        assistant_id=assistant_id,<br>    )<br><br># Define the custom function for image analysis<br>function_json = {<br>    &quot;name&quot;: &quot;analyze_profile_picture&quot;,<br>    &quot;description&quot;: &quot;Analyze this LinkedIn profile picture provided through the image URL. Examine its appropriateness for a professional LinkedIn profile by focusing on the presentation, expression and body language, composition and setting (including background), and the quality of the image. Ensure your analysis determines whether these aspects meet professional standards and offer specific recommendations for any needed improvements to enhance the profile&#39;s professional image. Overall, describe the image in detail.&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;image_url&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;URL of the profile picture&quot;}<br>        },<br>        &quot;required&quot;: [&quot;image_url&quot;]<br>    }<br>}<br><br><br>def handle_custom_function(run):<br>    if run.status == &#39;requires_action&#39; and run.required_action.type == &#39;submit_tool_outputs&#39;:<br>        for tool_call in run.required_action.submit_tool_outputs.tool_calls:<br>            if tool_call.function.name == &quot;analyze_profile_picture&quot;:<br>                image_url = json.loads(tool_call.function.arguments)[&quot;image_url&quot;]<br>                <br>                # Call GPT-4 Vision API to analyze the image<br>                vision_response = client.chat.completions.create(<br>                    model=&#39;gpt-4-vision-preview&#39;,<br>                    messages=[<br>                        {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [<br>                            {<br>                            &quot;type&quot;: &quot;text&quot;, <br>                            &quot;text&quot;: (<br>                                        &quot;Analyze this LinkedIn profile picture. Provide an analysis focusing on its &quot;<br>                                        &quot;appropriateness and effectiveness for a LinkedIn profile. Consider the following aspects:\n\n&quot;<br>                                        &quot;1. Presentation: Evaluate the subject&#39;s attire and grooming. Does it align with professional standards suitable for &quot;<br>                                        &quot;their industry or field?\n&quot;<br>                                        &quot;2. Expression and Body Language: Assess the subject&#39;s facial expression and body language. Does it project confidence, &quot;<br>                                        &quot;approachability, and professionalism?\n&quot;<br>                                        &quot;3. Composition and Setting: Comment on the composition of the photograph, including the background. Is it distraction-free &quot;<br>                                        &quot;and does it enhance the subject&#39;s professional image?\n&quot;<br>                                        &quot;4. Quality and Lighting: Evaluate the quality of the photograph, including lighting and clarity. Does the image quality &quot;<br>                                        &quot;uphold professional standards?\n\n&quot;<br>                                        &quot;Provide recommendations for improvement if necessary, highlighting aspects that could enhance the subject&#39;s professional &quot;<br>                                        &quot;portrayal on LinkedIn.&quot;<br>                                    )<br>                            },<br>                            {<br>                            &quot;type&quot;: &quot;image_url&quot;,<br>                            &quot;image_url&quot;: {<br>                                &quot;url&quot;: image_url,<br>                            },<br>                            },<br>                        ],<br>                        }<br>                    ],<br>                    max_tokens=400<br>                )<br><br><br>                # Submit the output back to the Assistant<br>                client.beta.threads.runs.submit_tool_outputs(<br>                    thread_id=run.thread_id,<br>                    run_id=run.id,<br>                    tool_outputs=[<br>                        {<br>                            &#39;tool_call_id&#39;: tool_call.id,<br>                            &#39;output&#39;: vision_response.choices[0].message.content<br>                        }<br>                    ]<br>                )<br><br><br># Main function to create the assistant<br>def main():<br>    assistant = create_linkedin_profile_analyzer()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()Part 2. Scraping the profiles — linkedin_scraper.py</pre><h3>Part 3: Scraping the profiles— linkedin_scraper.py:</h3><p>For scraping the Linkedin profiles, this script uses a third-party API found on RapidAPI, which offers 50 free requests — plenty for testing purposes. This is an easy workaround, direct scraping can be challenging due to LinkedIn’s protective measures. While building a custom scraper is an option that affords more control over what data to retrieve, the simplicity of using an established API for a quick prototype like this one, is my preference.</p><p>The linkedin_scraper.py starts by extracting the username from the provided LinkedIn profile URL. With the username in hand, we make a request to the RapidAPI endpoint, retrieving the profile&#39;s data, including personal information, professional experience, education, skills, languages, and certifications. This data is then formatted into a structured format suitable for GPT analysis. This is the <a href="https://rapidapi.com/rockapis-rockapis-default/api/linkedin-api8">API I used</a>. Here is the code:</p><pre>import os<br>import requests<br>import argparse<br>import logging<br>from dotenv import load_dotenv<br><br># Set up basic configuration for logging<br>logging.basicConfig(level=logging.DEBUG, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br><br>load_dotenv()<br>rapidapi_key = os.getenv(&#39;RAPIDAPI_KEY&#39;)<br><br>def main(profile_url):<br>    formatted_text, profile_image_url = scrape_linkedin_profile(profile_url)<br>    if formatted_text:  # Just check if formatted_text is not None or empty<br>        logging.info(&quot;Profile Data Scraped Successfully:&quot;)<br>        logging.info(formatted_text)<br>        if profile_image_url:<br>            logging.info(f&quot;Profile Image URL: {profile_image_url}&quot;)<br>        else:<br>            logging.info(&quot;No Profile Image URL found.&quot;)<br>    else:<br>        logging.error(&quot;Failed to scrape profile data or profile is incomplete/private.&quot;)<br><br>def scrape_linkedin_profile(profile_url):<br>    username = extract_username(profile_url)<br>    if not rapidapi_key:<br>        logging.error(&quot;RapidAPI key not found. Please set the RAPIDAPI_KEY environment variable.&quot;)<br>        return None, None<br><br>    url = &quot;https://linkedin-api8.p.rapidapi.com/&quot;<br>    querystring = {&quot;username&quot;: username}<br><br>    headers = {<br>        &quot;X-RapidAPI-Key&quot;: rapidapi_key,<br>        &quot;X-RapidAPI-Host&quot;: &quot;linkedin-api8.p.rapidapi.com&quot;<br>    }<br><br>    try:<br>        response = requests.get(url, headers=headers, params=querystring)<br>        if response.status_code == 200:<br>            profile_data = response.json()<br>            logging.debug(f&quot;API Response: {profile_data}&quot;)<br>            formatted_text, profile_image_url = format_data_for_gpt(profile_data)<br>            # Additional logging to confirm data formatting<br>            logging.debug(f&quot;Formatted Text: {formatted_text[:500]}&quot;)<br>            logging.debug(f&quot;Profile Image URL: {profile_image_url}&quot;)<br>            return formatted_text, profile_image_url<br>        else:<br>            logging.error(f&quot;Failed to fetch profile data. Status Code: {response.status_code}&quot;)<br>            return None, None<br>    except Exception as e:<br>        logging.exception(&quot;An error occurred while fetching the profile data.&quot;)<br>        return None, None<br><br>def extract_username(linkedin_url):<br>    username = linkedin_url.split(&#39;/&#39;)[-1] if linkedin_url.split(&#39;/&#39;)[-1] else linkedin_url.split(&#39;/&#39;)[-2]<br>    return username.strip()<br><br>import logging<br><br>def safe_get_list(data, key):<br>    &quot;&quot;&quot;<br>    Safely get a list value from a dictionary. Returns an empty list if the key is not found or the value is None.<br>    &quot;&quot;&quot;<br>    value = data.get(key)<br>    return [] if value is None else value<br><br>def safe_get_value(data, key, default=&#39;&#39;):<br>    &quot;&quot;&quot;Safely get a single value from a dictionary. Returns a default value if the key is not found or the value is None.&quot;&quot;&quot;<br>    return data.get(key) if data.get(key) is not None else default<br><br>def format_data_for_gpt(profile_data):<br>    try:<br>        # Extract the profile image URL safely<br>        profile_image_url = safe_get_value(profile_data, &#39;profilePicture&#39;, &#39;&#39;)<br><br>        # Personal Information with safe retrieval<br>        firstName = safe_get_value(profile_data, &#39;firstName&#39;, &#39;No first name&#39;)<br>        lastName = safe_get_value(profile_data, &#39;lastName&#39;, &#39;No last name&#39;)<br>        fullName = f&quot;{firstName} {lastName}&quot;<br>        headline = safe_get_value(profile_data, &#39;headline&#39;, &#39;No headline provided&#39;)<br>        summary = safe_get_value(profile_data, &#39;summary&#39;, &#39;No summary provided&#39;)<br>        location = safe_get_value(profile_data.get(&#39;geo&#39;, {}), &#39;full&#39;, &#39;No location provided&#39;)<br><br>        formatted_text = f&quot;Name: {fullName}\nHeadline: {headline}\nLocation: {location}\nSummary: {summary}\n&quot;<br><br>        # Professional Experience<br>        formatted_text += &quot;Experience:\n&quot;<br>        for position in safe_get_list(profile_data, &#39;position&#39;):<br>            company = position.get(&#39;companyName&#39;, &#39;No company name&#39;)<br>            title = position.get(&#39;title&#39;, &#39;No title&#39;)<br>            jobLocation = position.get(&#39;location&#39;, &#39;No location&#39;)<br>            jobDescription = position.get(&#39;description&#39;, &#39;No description&#39;).replace(&#39;\n&#39;, &#39; &#39;)<br>            formatted_text += f&quot;- {title} at {company}, {jobLocation}. {jobDescription}\n&quot;<br><br>        # Education<br>        formatted_text += &quot;Education:\n&quot;<br>        for education in safe_get_list(profile_data, &#39;educations&#39;):<br>            school = education.get(&#39;schoolName&#39;, &#39;No school name&#39;)<br>            degree = education.get(&#39;degree&#39;, &#39;No degree&#39;)<br>            field = education.get(&#39;fieldOfStudy&#39;, &#39;No field of study&#39;)<br>            grade = education.get(&#39;grade&#39;, &#39;No grade&#39;)<br>            eduDescription = education.get(&#39;description&#39;, &#39;No description&#39;).replace(&#39;\n&#39;, &#39; &#39;)<br>            formatted_text += f&quot;- {degree} in {field} from {school}, Grade: {grade}. {eduDescription}\n&quot;<br><br>        # Skills<br>        formatted_text += &quot;Skills:\n&quot;<br>        for skill in safe_get_list(profile_data, &#39;skills&#39;):<br>            skillName = skill.get(&#39;name&#39;, &#39;No skill name&#39;)<br>            formatted_text += f&quot;- {skillName}\n&quot;<br><br>        # Languages<br>        formatted_text += &quot;Languages:\n&quot;<br>        languages = safe_get_list(profile_data, &#39;languages&#39;)<br>        if languages:<br>            for language in languages:<br>                langName = language.get(&#39;name&#39;, &#39;No language name&#39;)<br>                proficiency = language.get(&#39;proficiency&#39;, &#39;No proficiency level&#39;)<br>                formatted_text += f&quot;- {langName} ({proficiency})\n&quot;<br>        else:<br>            formatted_text += &quot;- No languages provided\n&quot;<br><br>        # Certifications<br>        formatted_text += &quot;Certifications:\n&quot;<br>        for certification in safe_get_list(profile_data, &#39;certifications&#39;):<br>            certName = certification.get(&#39;name&#39;, &#39;No certification name&#39;)<br>            formatted_text += f&quot;- {certName}\n&quot;<br><br>        return formatted_text, profile_image_url<br><br>    except Exception as e:<br>        logging.exception(&quot;An error occurred during data formatting.&quot;)<br>        return None, None<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parser = argparse.ArgumentParser(description=&quot;Scrape LinkedIn profile data.&quot;)<br>    parser.add_argument(&quot;profile_url&quot;, help=&quot;LinkedIn profile URL to scrape.&quot;)<br>    args = parser.parse_args()<br><br>    main(args.profile_url)</pre><h3>Part 3: Putting it all together — app.py:</h3><p><strong>The final piece of the puzzle: The User Interface.</strong> I picked Streamlit for its simplicity and efficiency in turning scripts into shareable web apps — pure python, no frontend fuss.</p><h4>The Workflow:</h4><p>The script begins by loading the necessary environment variables, including ASSISTANT_ID, which is crucial for interactions with the OpenAI Assistant we&#39;ve created. This can be retrieved from the Assistants page on the <a href="https://platform.openai.com/assistants">OpenAI platform.</a></p><p>Streamlit’s session state is used to manage the state of our application, tracking whether the chat has started, the analysis requested, and if it’s been completed.</p><h4>Building the UI:</h4><p>The sidebar acts as the primary interaction point, where users enter their OpenAI API key and LinkedIn profile URL. The option to input job preferences is available and encourages a more customized analysis.</p><p>Initiating the analysis triggers the creation of a conversation thread with the Assistant through a button.</p><h4>Processing the LinkedIn Profile:</h4><p>Once the analysis button is triggered, the script uses the previously mentioned scrape_linkedin_profile function to extract and format data from the LinkedIn profile, including the profile image. This data is then forwarded to the Assistant for processing.</p><h4>Handling Custom Function Calls:</h4><p>A core part of the workflow is the handle_custom_function. This function is invoked when the Assistant needs to analyze the profile picture, calling the GPT-4 Vision API, submitting the image URL, and processing the returned analysis. This step illustrates the extension of the Assistant&#39;s capabilities, enabling it to &quot;see&quot; and provide feedback on images and visual elements.</p><h4>Displaying Analysis Results:</h4><p>The results of the analysis are displayed within the main application interface. Users can also ask additional questions and keep conversing.</p><p><strong>Quick Heads-up:</strong> I put a good chunk of effort into the Streamlit UI to make it easy on the eyes, which means the code might look a bit long at first glance. But don’t worry, the underlying logic is pretty straightforward and user-friendly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzC-Moa4opb7Ya3Aw-LLAg.png" /><figcaption>Image from the author</figcaption></figure><p>Here’s the code:</p><pre>import json<br>import os<br>import time<br>from dotenv import load_dotenv<br><br>import openai<br>import streamlit as st<br><br>from linkedin_scraper import scrape_linkedin_profile<br><br># Load environment variables from .env file<br>load_dotenv()<br><br>assistant_id = os.getenv(&quot;ASSISTANT_ID&quot;)<br><br># Initialize Streamlit session state variables<br>if &quot;start_chat&quot; not in st.session_state:<br>    st.session_state.start_chat = False<br>if &quot;thread_id&quot; not in st.session_state:<br>    st.session_state.thread_id = None<br>if &quot;openai_api_key&quot; not in st.session_state:<br>    st.session_state.openai_api_key = &quot;&quot;<br># Add a new session state variable for analysis completion tracking<br>if &quot;analysis_completed&quot; not in st.session_state:<br>    st.session_state.analysis_completed = False<br><br># Configure the Streamlit page<br>st.set_page_config(page_title=&quot;ReviewIn&quot;, page_icon=&quot;:computer:&quot;)<br><br>with st.sidebar:<br>    st.markdown(&quot;&lt;h1 style=&#39;display: flex; align-items: center;&#39;&gt;ReviewIn &lt;img src=&#39;https://www.pagetraffic.com/blog/wp-content/uploads/2022/09/linkedin-blue-logo-icon.png&#39; alt=&#39;LinkedIn Logo&#39; width=&#39;40&#39; height=&#39;40&#39;&gt;&lt;/h1&gt;&quot;, unsafe_allow_html=True)<br>    #bullet points<br>    with st.expander(&quot;🚀 Features and Tips&quot;):<br>        st.markdown(&quot;&quot;&quot;<br>            - 🧐 **LinkedIn Profile Review:** Personalized, actionable advice for enhancing your profile.<br>            - 📚 **Specialized Knowledge:** Draws on a custom knowledge base tailored for LinkedIn profile improvements.<br>            - 💡 **Powered by OpenAI:** Leverages the Assistant&#39;s API with GPT-4 Turbo for analysis and conversation.<br>            - 🖼 **Vision Insights:** GPT-4 Vision for detailed feedback on profile pictures.<br>            - 🔥 **Tip:** For better analysis, set your profile to public. The more complete and public your profile, the better our insights.<br>            - ⚠️ **Note:** Assistants API is in beta and doesn&#39;t yet support streaming - full response is generated before being sent. Your patience is appreciated! 🙂<br>        &quot;&quot;&quot;, unsafe_allow_html=True)<br><br><br>    st.session_state[&#39;openai_api_key&#39;] = st.text_input(&quot;🔑 OpenAI API Key:&quot;, type=&quot;password&quot;)<br>    with st.expander(&quot;🎯 Job Preferences &amp; Context (optional)&quot;):<br>        job_preferences = st.text_area(&quot;Got any specific job-seeking goals? Let us know here!&quot;,<br>        placeholder=&quot;e.g., &#39;Software Engineer, entry-level, Tech industry and interested in AI.&#39;&quot;)<br>    profile_url = st.text_input(&quot;🌐 Enter LinkedIn Profile URL:&quot;)<br><br>    # Check if both OpenAI API Key and LinkedIn Profile URL are provided<br>    if st.session_state[&#39;openai_api_key&#39;] and profile_url:<br>        if st.button(&quot;Analyze&quot;):<br>            st.session_state.start_chat = True<br>            openai.api_key = st.session_state.openai_api_key<br>            thread = openai.beta.threads.create()<br>            st.session_state.thread_id = thread.id<br>            st.session_state.analysis_requested = True<br>    else:<br>        # Optionally, display a message prompting the user to fill in all required fields<br>        st.warning(&quot;Friendly reminder - add your OpenAI API Key and LinkedIn Profile URL to kick things off!😎&quot;)<br><br># Initialize or reset session state on page load<br>if &#39;init&#39; not in st.session_state:<br>    st.session_state[&#39;init&#39;] = True<br>    st.session_state.start_chat = False<br>    st.session_state.messages = []<br>    st.session_state.thread_id = None<br>    st.session_state.analysis_requested = False<br><br>def handle_custom_function(run, job_preferences=&quot;&quot;):<br>    if run.status == &#39;requires_action&#39; and run.required_action.type == &#39;submit_tool_outputs&#39;:<br>        for tool_call in run.required_action.submit_tool_outputs.tool_calls:<br>            if tool_call.function.name == &quot;analyze_profile_picture&quot;:<br>                image_url = json.loads(tool_call.function.arguments)[&quot;image_url&quot;]<br>                print(f&quot;Analyzing image at URL: {image_url}&quot;)<br>                additional_context = &quot;&quot;<br>                if job_preferences:<br>                    additional_context += f&quot;\n\n**ADDITIONAL** - If relevant for your analysis, please consider the following context about the user&#39;s job preferences: {job_preferences}&quot;<br>                <br>                # Call GPT-4 Vision API to analyze the image<br>                vision_response = openai.chat.completions.create(<br>                    model=&#39;gpt-4-vision-preview&#39;,<br>                    messages=[<br>                        {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [<br>                            {<br>                            &quot;type&quot;: &quot;text&quot;, <br>                            &quot;text&quot;: (<br>                                        &quot;Analyze this LinkedIn profile picture. Provide an analysis focusing on its &quot;<br>                                        &quot;appropriateness and effectiveness for a LinkedIn profile. Consider the following aspects:\n\n&quot;<br>                                        &quot;1. Presentation: Evaluate the subject&#39;s attire and grooming. Does it align with professional standards suitable for &quot;<br>                                        &quot;their industry or field?\n&quot;<br>                                        &quot;2. Expression and Body Language: Assess the subject&#39;s facial expression and body language. Does it project confidence, &quot;<br>                                        &quot;approachability, and professionalism?\n&quot;<br>                                        &quot;3. Composition and Setting: Comment on the composition of the photograph, including the background. Is it distraction-free &quot;<br>                                        &quot;and does it enhance the subject&#39;s professional image?\n&quot;<br>                                        &quot;4. Quality and Lighting: Evaluate the quality of the photograph, including lighting and clarity. Does the image quality &quot;<br>                                        &quot;uphold professional standards?\n\n&quot;<br>                                        &quot;Provide recommendations for improvement if necessary, highlighting aspects that could enhance the subject&#39;s professional &quot;<br>                                        &quot;portrayal on LinkedIn. {additional_context}&quot;<br>                                    )<br>                            },<br>                            {<br>                            &quot;type&quot;: &quot;image_url&quot;,<br>                            &quot;image_url&quot;: {<br>                                &quot;url&quot;: image_url,<br>                            },<br>                            },<br>                        ],<br>                        }<br>                    ],<br>                    max_tokens=400<br>                )<br>                vision_content = vision_response.choices[0].message.content<br>                print(f&quot;Vision API response: {vision_content}&quot;)<br><br>                # Submit the output back to the Assistant<br>                openai.beta.threads.runs.submit_tool_outputs(<br>                    thread_id=run.thread_id,<br>                    run_id=run.id,<br>                    tool_outputs=[<br>                        {<br>                            &#39;tool_call_id&#39;: tool_call.id,<br>                            &#39;output&#39;: vision_response.choices[0].message.content<br>                        }<br>                    ]<br>                )<br>                print(f&quot;Submitted vision analysis back to the assistant: {vision_content}&quot;)<br><br># Main interaction logic<br>if st.session_state.start_chat:<br>    if &quot;messages&quot; not in st.session_state:<br>        st.session_state.messages = []<br>    <br>    for message in st.session_state.messages:<br>        with st.chat_message(message[&quot;role&quot;]):<br>            st.markdown(message[&quot;content&quot;])<br><br>    if st.session_state.analysis_requested:<br>        with st.spinner(&#39;⏳🔍 Crunching the numbers - going to take a sec chief!😊&#39;):<br>            # Process the LinkedIn profile URL<br>            formatted_text, image_url = scrape_linkedin_profile(profile_url)<br>            time.sleep(3)<br>            if formatted_text:<br>                # Instructions for analysis<br>                instructions = &quot;&quot;&quot;<br>                                Provide an analysis/report of my LinkedIn profile below. Approach this task with professionalism and friendliness, ensure your recommendations is are both helpful and actionable. Provide detailed feedback for improvement. You can follow this structure:<br><br>                                1. **Profile Picture**: Begin with the profile picture. Assess its alignment. Suggest specific changes to enhance the first impression it makes, if needed.<br>                                2. **Headline and Summary**: Evaluate the clarity and impact of the headline and summary. How well do they communicate the individual&#39;s professional narrative and unique value proposition? Provide actionable advice to refine these elements, enhancing their appeal and coherence.<br>                                3. **Work Experience and Skills**: Delve into the work experience and skills sections. Identify the strengths and pinpoint areas that can benefit from greater detail or stronger examples of achievements. Recommend strategies to showcase expertise/skills more effectively.<br>                                4. **Educational Background and Volunteer Experience**: Analyze the education section and provide recommendations, if needed. Do the same for the Volunteer experience, if present. Advise on optimizing these areas to support the professional identity and narrative.<br>                                Each section should receive an assessment that contributes to an overall profile rating. Conclude with:<br>                                5. **Overall Quality Evaluation and Potential**: Rate the profile&#39;s current state out of 100, based on the coherence, presentation, and effectiveness of all sections combined - be as objective as you can, refrain from giving overly high ratings, unless the profile really is amazing, you can be critical, but still friendly. Then, estimate the potential score increase achievable by implementing your recommendations. Highlight the transformative impact of suggested changes, not just incrementally but in terms of elevating the profile&#39;s professional stature and networking potential.<br><br>                                Remember, your analysis should be comprehensive and nuanced, leveraging your expertise and any relevant external information from the files, where relevant. Address me directly and use the first person for a personal touch Let&#39;s evaluate this LinkedIn profile:<br>                            &quot;&quot;&quot;<br>                # Prepare the analysis request content<br>                analysis_request = f&quot;{instructions}\n\n**HERE IS THE CONTENT FOR ANALYSIS**:\n- **Profile Text**: {formatted_text}\n&quot;<br>                if image_url:  # Conditionally include image URL if available<br>                    analysis_request += f&quot;- **Profile Image URL**: {image_url}&quot;<br><br>                # Add job preferences to the analysis request if any<br>                if job_preferences:<br>                    analysis_request += f&quot;\n\n**ADDITIONAL** - If relevant, please incorporate the following context about the job preferences of the user to tailor the recommendations: {job_preferences}&quot;<br>                <br>                print(analysis_request)<br>            <br>                openai.beta.threads.messages.create(<br>                    thread_id=st.session_state.thread_id,<br>                    role=&quot;user&quot;,<br>                    content=analysis_request<br>                )<br>                    <br>                # Wait for the analysis to complete<br>                run = openai.beta.threads.runs.create(<br>                    thread_id=st.session_state.thread_id,<br>                    assistant_id=assistant_id,<br>                    instructions=&quot;Address me directly and use first person for a personal touch. Be helpful and approachable.&quot;<br>                )<br>                    <br>                while run.status != &#39;completed&#39;:<br>                    time.sleep(1)<br>                    run = openai.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)<br>                    if run.status == &#39;requires_action&#39;:<br>                        print(&quot;Function Calling&quot;)<br>                        handle_custom_function(run)<br><br>                # Fetch and display the analysis results<br>                messages = openai.beta.threads.messages.list(<br>                    thread_id=st.session_state.thread_id<br>                )<br><br>                # Filter and display messages for the current run<br>                for message in messages.data:<br>                    if message.run_id == run.id and message.role == &quot;assistant&quot;:<br>                        st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: message.content[0].text.value})<br>                        with st.chat_message(&quot;assistant&quot;):<br>                            st.markdown(message.content[0].text.value)<br>                    <br>                # Mark the analysis as completed and ready for user follow-up<br>                st.session_state.analysis_requested = False<br>                st.session_state.analysis_completed = True<br><br><br>    # After completing the initial analysis, enable follow-up conversations<br>    if st.session_state.analysis_completed:<br>        user_input = st.chat_input(&quot;Ask me anything about improving your LinkedIn profile!&quot;)<br>        if user_input:  # If there&#39;s user input, process it<br>            # Append user input to messages for display<br>            st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input})<br>            with st.chat_message(&quot;user&quot;):<br>                st.markdown(user_input)<br><br>            # Send the user input to OpenAI API as a new message in the thread<br>            openai.beta.threads.messages.create(<br>                thread_id=st.session_state.thread_id,<br>                role=&quot;user&quot;,<br>                content=user_input<br>            )<br><br>            # Wait for response<br>            run = openai.beta.threads.runs.create(<br>                thread_id=st.session_state.thread_id,<br>                assistant_id=assistant_id,<br>                instructions=&quot;Be helpful and approachable.&quot;<br>            )<br>                <br>            while run.status != &#39;completed&#39;:<br>                time.sleep(1)<br>                run = openai.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)<br><br>            # Fetch and display the analysis results<br>            messages = openai.beta.threads.messages.list(<br>                thread_id=st.session_state.thread_id<br>            )<br><br>            # Filter and display messages for the current run<br>            for message in messages.data:<br>                if message.run_id == run.id and message.role == &quot;assistant&quot;:<br>                    st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: message.content[0].text.value})<br>                    with st.chat_message(&quot;assistant&quot;):<br>                        st.markdown(message.content[0].text.value)<br><br><br># Display if chat not yet started<br>if not st.session_state.start_chat:<br>    st.markdown(<br>        &quot;&quot;&quot;<br>        &lt;h2 style=&#39;text-align: center;&#39;&gt;<br>            🚀 Ready to enhance your LinkedIn profile? &lt;br&gt;<br>            Drop your &lt;img src=&#39;https://upcdn.io/FW25bBB/image/content/app_logos/485244ee-9158-4685-8f1e-d349e97b35e1.png?f=webp&amp;w=1920&amp;q=85&amp;fit=shrink-cover&#39; alt=&#39;LinkedIn Logo&#39; width=&#39;45&#39; height=&#39;45&#39; style=&#39;border-radius: 15%&#39;&gt; API key and &lt;img src=&#39;https://www.pagetraffic.com/blog/wp-content/uploads/2022/09/linkedin-blue-logo-icon.png&#39; alt=&#39;LinkedIn Logo&#39; width=&#39;40&#39; height=&#39;40&#39;&gt; profile URL in the sidebar and let&#39;s dive in!<br>        &lt;/h2&gt;<br>        &quot;&quot;&quot;,<br>        unsafe_allow_html=True<br>    )<br>    st.image(&quot;dalle.png&quot;, use_column_width=True)</pre><p>And here’s what the end result looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OnypEuk7zmFNHJt7GeqbA.png" /><figcaption>Image from the author — Made with ❤️ and Python.</figcaption></figure><h3>Wrapping up</h3><p>That’s all for this article! Dive into the code to build your own version by visiting the <a href="https://github.com/alessandroamenta/RateIn">GitHub repo</a>.</p><p>Excited to hear your feedback and see what you build with the Assistants API.</p><p>Should you find this article enlightening, consider expressing your appreciation with 50 claps 👏 — your support means a ton.</p><p>Thanks for following along and happy coding! :)</p><p>All images are by me, the author, unless otherwise noted. Apart from being a user, I have no affiliation with OpenAI, Streamlit, Rapid API or any other organisation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb8faca91731" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-an-ai-powered-linkedin-profile-reviewer-openai-assistants-api-and-gpt-4-vision-cb8faca91731">Build an AI-powered LinkedIn profile reviewer: OpenAI Assistants API and Gpt-4-vision</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI at Scale: Automating Tasks through Bulk Prompt Processing]]></title>
            <link>https://levelup.gitconnected.com/ai-at-scale-automating-tasks-through-bulk-prompt-processing-0e8f420a2898?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e8f420a2898</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 20:23:52 GMT</pubDate>
            <atom:updated>2024-01-28T20:23:52.840Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simultaneously Handle Hundreds of Prompts</h4><p>Have you ever felt limited by the one-query-at-a-time approach of AI interactions, especially when dealing with tasks like translations, copywriting, or other repetitive tasks?</p><p>It’s like having a super-fast car but being stuck in the slow lane. Well, let’s build a solution for that! In this article we build a small project that lets you fire up to 300 prompts at once and zips the answers straight to your Dropbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6h6RuBpNxi8m0njQ" /><figcaption>Source: Unsplash</figcaption></figure><h3>What’s This Project All About?</h3><p>At core this project is the ability to handle a high volume of prompts in an efficient and automated manner. Ideal for tasks that thrive on automation, the setup is simple: feed your prompts through an Excel file or Google Sheet, and receive the outputs in a similar format, ready and automatically uploaded to your Dropbox. That’s it.</p><p>Let’s dive into the technical side: the app’s interface is powered by Streamlit, with FastAPI handling the backend. We use OpenAI models, integrate Dropbox API for file management, use Redis for advanced caching, and deploy it all on Render’s free tier. This project’s all about breaking free from the one-at-a-time AI chat trap. This article here is to make handling a bunch of AI prompts as easy as a piece of cake. 🍰</p><p>Ok, let’s get into the code!</p><h3>The Streamlit Interface</h3><p>Streamlit is our project’s interface. Let’s break down the key components:</p><pre>import streamlit as st<br>import pandas as pd<br>from io import BytesIO<br>import base64<br>import logging<br>import requests<br>import time<br>import dropbox</pre><p>These imports lay the foundation for our project. streamlit powers the app, pandas handles data manipulation, BytesIO and base64 assist with file handling, while logging, requests, time, and dropbox manage various functionalities like logging, API requests, timing, and Dropbox integration, respectively.</p><h3>Dropbox Upload Function</h3><pre># Dropbox Upload Function<br>def upload_to_dropbox(file_bytes, dropbox_folder, file_name):<br>    # Request new access token from backend<br>    response = requests.get(f&quot;{FASTAPI_BASE_URL}/refresh_token&quot;)<br>    if response.status_code == 200:<br>        access_token = response.json().get(&quot;access_token&quot;)<br>        dbx = dropbox.Dropbox(access_token)<br>        dropbox_path = f&#39;/{dropbox_folder}/{file_name}&#39;<br>        try:<br>            dbx.files_upload(file_bytes, dropbox_path, mode=dropbox.files.WriteMode.overwrite)<br>            return True<br>        except Exception as e:<br>            print(f&quot;Error uploading to Dropbox: {e}&quot;)<br>            return False<br>    else:<br>        print(&quot;Failed to refresh Dropbox token&quot;)<br>        return False</pre><p>This function manages the upload of files to Dropbox. It requests a new access token, initializes a Dropbox session, and uploads the file. Error handling is crucial to ensure smooth uploads.</p><h3>Dropbox Authentication Check</h3><pre>def check_dropbox_authentication():<br>    response = requests.get(f&quot;{FASTAPI_BASE_URL}/check_authentication&quot;)<br>    if response.status_code == 200:<br>        st.session_state[&#39;dropbox_authenticated&#39;] = response.json().get(&quot;authenticated&quot;, False)<br>        st.session_state[&#39;dropbox_token&#39;] = response.json().get(&quot;access_token&quot;, None)<br>    else:<br>        st.session_state[&#39;dropbox_authenticated&#39;] = False<br>        st.session_state[&#39;dropbox_token&#39;] = None</pre><p>This function verifies whether the user is authenticated with Dropbox and updates the Streamlit session state accordingly.</p><pre>def fetch_task_status(task_id):<br>    &quot;&quot;&quot;Function to check the status of a task&quot;&quot;&quot;<br>    try:<br>        check_response = requests.get(f&quot;{FASTAPI_BASE_URL}/status/{task_id}&quot;)<br>        if check_response.status_code == 200:<br>            logging.info(f&quot;Status response for task {task_id}: {check_response.json()}&quot;)<br>            return check_response.json()<br>        else:<br>            return None<br>    except requests.RequestException as e:<br>        logging.error(f&quot;Error checking task status: {e}&quot;)<br>        return None</pre><p>A crucial function that checks the status of a task using its ID, ensuring the user stays informed about the processing state.</p><h3>Task Processor</h3><pre>def process_task(data, results_placeholder, dropbox_folder, output_file_name):<br>    &quot;&quot;&quot;Function to process the task and handle UI updates&quot;&quot;&quot;<br>    response = requests.post(f&quot;{FASTAPI_BASE_URL}/process/&quot;, json=data)<br>    if response.status_code == 200:<br>        task_id = response.json().get(&quot;task_id&quot;)<br>        st.session_state[&#39;task_id&#39;] = task_id  # Store task_id in session state<br>        st.success(f&quot;Processing started for task {task_id}. Please wait...&quot;)<br><br>        while True:<br>            task_info = fetch_task_status(task_id)<br>            if task_info and task_info.get(&quot;status&quot;) == &quot;completed&quot;:<br>                response_data = task_info<br>                answers = response_data[&quot;results&quot;].get(&quot;results&quot;, [])<br>                try:<br>                    df = pd.DataFrame({&#39;Prompts&#39;: prompts, &#39;Answers&#39;: answers})<br>                    results_placeholder.write(df)<br>                    <br>                    # Convert DataFrame to Excel<br>                    output = BytesIO()<br>                    with pd.ExcelWriter(output, engine=&#39;xlsxwriter&#39;) as writer:<br>                        df.to_excel(writer, index=False)<br>                    excel_data = output.getvalue()<br>                    b64 = base64.b64encode(excel_data).decode(&#39;utf-8&#39;)<br><br>                    # Provide download link<br>                    download_link = f&#39;&lt;a href=&quot;data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,{b64}&quot; download=&quot;{output_file_name}&quot;&gt;Download Excel File&lt;/a&gt;&#39;<br><br>                    st.markdown(download_link, unsafe_allow_html=True)<br>                    st.success(&quot;🎉 Answers generated successfully!&quot;)<br>                    autoplay_audio(&#39;notification.mp3&#39;)<br><br>                    # Upload to Dropbox if authenticated<br>                    if dropbox_folder and &#39;dropbox_token&#39; in st.session_state and st.session_state[&#39;dropbox_token&#39;]:<br>                        if upload_to_dropbox(excel_data, dropbox_folder, output_file_name):<br>                            st.success(f&quot;File uploaded to Dropbox successfully at /{dropbox_folder}/{output_file_name}!&quot;)<br>                        else:<br>                            st.error(&quot;Failed to upload the file to Dropbox.&quot;)<br>                    break  # Exit loop after successful processing<br>                except Exception as e:<br>                    st.error(f&quot;Error creating DataFrame: {e}&quot;)<br>                    break<br>            else:<br>                task_progress = task_info.get(&quot;progress&quot;)<br>                progress_message = &quot;GPT is processing your request. Hang tight!&quot; if task_progress is None else f&quot;GPT is whipping up your answers, hang tight! - {task_progress} 😎&quot;<br>                results_placeholder.info(progress_message)<br>                time.sleep(3)  # Adjust as needed<br>    else:<br>        st.error(&quot;Failed to start processing. Please try again.&quot;)</pre><p>Here, the task is processed, and UI updates are managed. It starts the task, monitors its status, generates a DataFrame of results, and provides a download link when complete (on top of automatically uploading the results to the user’s Dropbox).</p><h3>Initialization and Configuration</h3><pre># Ensure Dropbox authentication check is performed on every page load<br>check_dropbox_authentication()<br><br># Sidebar configuration<br>st.sidebar.title(&quot;🛠️ Settings&quot;)<br>API_KEY = st.sidebar.text_input(&quot;🔑 OpenAI API Key&quot;, value=&#39;&#39;, type=&#39;password&#39;)<br><br># Dropbox Integration<br>if &#39;dropbox_authenticated&#39; not in st.session_state:<br>    st.session_state[&#39;dropbox_authenticated&#39;] = check_dropbox_authentication()<br><br>if st.session_state[&#39;dropbox_authenticated&#39;]:<br>    st.sidebar.success(&quot;✅ Authenticated with Dropbox&quot;)<br>    dropbox_folder = st.sidebar.text_input(&quot;Dropbox Folder&quot;, value=&#39;bulk&#39;)<br><br>    # Add Log Out button here<br>    if st.sidebar.button(&quot;Log Out from Dropbox&quot;):<br>        response = requests.get(f&quot;{FASTAPI_BASE_URL}/clear_authentication&quot;)<br>        if response.status_code == 200:<br>            st.session_state.pop(&#39;dropbox_authenticated&#39;, None)<br>            st.session_state.pop(&#39;dropbox_token&#39;, None)<br>            st.sidebar.success(&quot;Logged out from Dropbox&quot;)<br>        else:<br>            st.sidebar.error(&quot;Failed to log out from Dropbox&quot;)<br>else:<br>    if st.sidebar.button(&quot;Connect to Dropbox&quot;):<br>        st.sidebar.markdown(f&quot;[Authenticate with Dropbox]({FASTAPI_BASE_URL}/auth/redirect)&quot;, unsafe_allow_html=True)<br><br># Input for custom output file name<br>custom_output_name = st.sidebar.text_input(&quot;Name Output File (without extension - optional!)&quot;)<br><br>ai_model_choice = st.sidebar.selectbox(&quot;🤖 Choose model:&quot;, [&quot;gpt-3.5-turbo-16k&quot;, &quot;gpt-4&quot;, &quot;gpt-4-1106-preview&quot;])<br>temperature = st.sidebar.slider(&quot;🌡️ Temperature&quot;, min_value=0.0, max_value=1.0, value=0.2, step=0.01)<br>seed = 12345  # Fixed seed value<br>processing_mode = st.sidebar.selectbox(&quot;Select Processing Mode:&quot;, [&quot;Quick Mode&quot;, &quot;High Accuracy Mode&quot;], index=1)<br>batch_size_options = [1] + list(range(5, 51, 5))<br>if processing_mode == &quot;Quick Mode&quot;:<br>    batch_size = st.sidebar.select_slider(&quot;Batch Size for Processing&quot;, options=batch_size_options, value=10)<br>with st.sidebar.expander(&quot;📝 Custom Instructions&quot;):<br>    common_instructions = st.text_area(&quot;Enter instructions to apply to all prompts&quot;, &#39;&#39;)</pre><p>The app initializes the Dropbox authentication check and sets up the Streamlit sidebar, allowing users to configure settings like the OpenAI API key, Dropbox folder, and processing parameters.</p><h3>Main Application</h3><pre># Main App<br>st.title(&quot;🧠 GPT Answer Generator&quot;)<br>st.write(&quot;Generate answers for a bulk of prompts using OpenAI.&quot;)<br>st.warning(&quot;⚠️ Dropbox Notes:\n&quot;<br>            &quot;- File Overwriting: If a file with the same name already exists in your specified Dropbox folder, it will be overwritten.\n&quot;<br>            &quot;- Folder Creation: If the specified folder doesn&#39;t exist, Dropbox will automatically create it during the file upload.&quot;)<br><br># Input method selection<br>input_method = st.selectbox(&quot;📥 Choose input method:&quot;, [&quot;Text Box&quot;, &quot;File Upload&quot;])<br>if input_method == &quot;Text Box&quot;:<br>    user_input = st.text_area(&quot;Enter prompts:&quot;, height=300)<br>    prompts = user_input.split(&#39;\n\n&#39;)<br>    default_output_file_name = &quot;answers.xlsx&quot;<br>elif input_method == &quot;File Upload&quot;:<br>    uploaded_file = st.file_uploader(&quot;📂 Upload a CSV or Excel file&quot;, type=[&quot;csv&quot;, &quot;xlsx&quot;])<br>    if uploaded_file:<br>        df = pd.read_csv(uploaded_file) if uploaded_file.name.endswith(&#39;.csv&#39;) else pd.read_excel(uploaded_file)<br>        prompts = df.iloc[:, 0].tolist()<br>        default_output_file_name = uploaded_file.name<br>    else:<br>        prompts = []<br>        default_output_file_name = &quot;answers.xlsx&quot;<br><br># Button to start processing<br>results_placeholder = st.empty()<br>if st.button(&quot;🚀 Generate Answers&quot;):<br>    if not API_KEY:<br>        st.warning(&quot;Please enter your OpenAI API Key to proceed.&quot;)<br>    else:<br>        output_file_name = f&quot;{custom_output_name}.xlsx&quot; if custom_output_name else default_output_file_name<br>        data = {<br>            &quot;prompts&quot;: prompts, <br>            &quot;ai_model_choice&quot;: ai_model_choice, <br>            &quot;common_instructions&quot;: common_instructions, <br>            &quot;api_key&quot;: API_KEY, <br>            &quot;temperature&quot;: temperature, <br>            &quot;seed&quot;: seed, <br>            &quot;processing_mode&quot;: processing_mode<br>        }    <br>    if processing_mode == &quot;Quick Mode&quot;:<br>        data[&quot;batch_size&quot;] = batch_size<br>            # Determine the output file name based on user input or default logic<br>    if custom_output_name:<br>        output_file_name = f&quot;{custom_output_name}.xlsx&quot;<br>    else:<br>        output_file_name = uploaded_file.name if input_method == &quot;File Upload&quot; and uploaded_file is not None else &quot;answers.xlsx&quot;<br><br>    # Call process_task with the determined file name<br>    process_task(data, results_placeholder, dropbox_folder, output_file_name)</pre><p>The core of the app where users input their prompts and trigger the answer generation process. It handles different input methods and starts the task processing upon button click.</p><h3>Task Status Check on Reload</h3><pre># Check if a task is already in progress when the page is loaded/refreshed<br>if &#39;task_id&#39; in st.session_state:<br>    process_task(None, results_placeholder, dropbox_folder, default_output_file_name) </pre><p>This section ensures that the app checks the status of a task if it’s already in progress, especially useful when the page is reloaded.</p><h3>The FastAPI Backend</h3><p>We now use FastAPI, my go-to framework for building APIs. The backend is responsible for authenticating with Dropbox, handling tokens, processing prompts by communicating with the OpenAI API, and managing task statuses.</p><h3>Main App Setup and CORS Configuration</h3><pre>from fastapi import FastAPI, BackgroundTasks, HTTPException, Request, Depends<br>from fastapi.responses import RedirectResponse, JSONResponse, HTMLResponse<br>from pydantic import BaseModel<br>from quick import get_answers as get_answers_async<br>from sync import get_answers as get_answers_sync<br>import uuid<br>from fastapi.exceptions import RequestValidationError<br>from fastapi.responses import JSONResponse<br>import logging<br>from typing import Optional<br>from fastapi.middleware.cors import CORSMiddleware<br>import httpx<br>import redis<br><br>logging.basicConfig(level=logging.INFO)<br><br>app = FastAPI()</pre><p>Here, the FastAPI app is initialized.</p><h3>Dropbox Authentication Endpoints</h3><pre>@app.get(&quot;/auth/redirect&quot;)<br>async def auth_redirect():<br>    return RedirectResponse(<br>        url=f&quot;https://www.dropbox.com/oauth2/authorize?client_id={DROPBOX_APP_KEY}&amp;response_type=code&amp;redirect_uri={REDIRECT_URI}&amp;token_access_type=offline&quot;<br>    )<br><br>@app.get(&quot;/auth&quot;)<br>async def auth(request: Request):<br>    code = request.query_params.get(&quot;code&quot;)<br>    if code:<br>        async with httpx.AsyncClient() as client:<br>            response = await client.post(<br>                &quot;https://api.dropbox.com/oauth2/token&quot;,<br>                data={<br>                    &quot;code&quot;: code,<br>                    &quot;grant_type&quot;: &quot;authorization_code&quot;,<br>                    &quot;client_id&quot;: DROPBOX_APP_KEY,<br>                    &quot;client_secret&quot;: DROPBOX_APP_SECRET,<br>                    &quot;redirect_uri&quot;: REDIRECT_URI,<br>                },<br>            )<br>        if response.status_code == 200:<br>            token_data = response.json()<br>            # Store tokens in Redis<br>            redis_client.set(&quot;dropbox_refresh_token&quot;, token_data[&quot;refresh_token&quot;])<br>            redis_client.set(&quot;dropbox_access_token&quot;, token_data[&quot;access_token&quot;])<br>            # Return an HTML response indicating successful authentication<br>            html_content = &quot;&quot;&quot;<br>            &lt;html&gt;<br>                &lt;head&gt;<br>                    &lt;style&gt;<br>                        body {<br>                            font-family: Arial, sans-serif;<br>                            background-color: #f4f4f4;<br>                            text-align: center;<br>                            padding: 50px;<br>                        }<br>                        h2 {<br>                            color: #4CAF50;<br>                        }<br>                        p {<br>                            color: #555;<br>                        }<br>                    &lt;/style&gt;<br>                &lt;/head&gt;<br>                &lt;body&gt;<br>                    &lt;h2&gt;Authentication Successful!&lt;/h2&gt;<br>                    &lt;p&gt;Please return to the app and refresh the page once to use Dropbox.&lt;/p&gt;<br>                &lt;/body&gt;<br>            &lt;/html&gt;<br>            &quot;&quot;&quot;<br>            return HTMLResponse(content=html_content)<br>        else:<br>            return JSONResponse(status_code=400, content={&quot;message&quot;: &quot;Failed to authenticate&quot;})<br>    else:<br>        raise HTTPException(status_code=400, detail=&quot;Missing authorization code&quot;)</pre><p>These endpoints manage the OAuth flow for Dropbox, redirecting to the authentication page and handling the authentication process.</p><h3>Token Refresh and Authentication Check</h3><pre>@app.get(&quot;/refresh_token&quot;)<br>async def refresh_token():<br>    refresh_token = redis_client.get(&quot;dropbox_refresh_token&quot;).decode(&quot;utf-8&quot;) if redis_client.get(&quot;dropbox_refresh_token&quot;) else None<br>    if refresh_token:<br>        async with httpx.AsyncClient() as client:<br>            response = await client.post(<br>                &quot;https://api.dropbox.com/oauth2/token&quot;,<br>                data={<br>                    &quot;grant_type&quot;: &quot;refresh_token&quot;,<br>                    &quot;refresh_token&quot;: refresh_token,<br>                    &quot;client_id&quot;: DROPBOX_APP_KEY,<br>                    &quot;client_secret&quot;: DROPBOX_APP_SECRET,<br>                },<br>            )<br>        if response.status_code == 200:<br>            new_tokens = response.json()<br>            redis_client.set(&quot;dropbox_access_token&quot;, new_tokens[&quot;access_token&quot;])<br>            return {&quot;access_token&quot;: new_tokens[&quot;access_token&quot;]}<br>        else:<br>            raise HTTPException(status_code=response.status_code, detail=&quot;Failed to refresh token&quot;)<br>    else:<br>        raise HTTPException(status_code=400, detail=&quot;Refresh token not available&quot;)<br><br>@app.get(&quot;/check_authentication&quot;)<br>async def check_authentication():<br>    access_token = redis_client.get(&quot;dropbox_access_token&quot;).decode(&quot;utf-8&quot;) if redis_client.get(&quot;dropbox_access_token&quot;) else None<br>    if access_token:<br>        return {&quot;authenticated&quot;: True, &quot;access_token&quot;: access_token}<br>    else:<br>        return {&quot;authenticated&quot;: False}</pre><p>These functions handle the refresh of Dropbox tokens and check whether the user is authenticated.</p><h3>Endpoint for Clearing Authentication</h3><pre>@app.get(&quot;/clear_authentication&quot;)<br>async def clear_authentication():<br>    redis_client.delete(&quot;dropbox_refresh_token&quot;)<br>    redis_client.delete(&quot;dropbox_access_token&quot;)<br>    return {&quot;message&quot;: &quot;Dropbox authentication cleared&quot;}</pre><p>A simple yet essential endpoint to clear Dropbox authentication, effectively logging the user out.</p><h3>Request Validation and Task Storage</h3><pre>@app.exception_handler(RequestValidationError)<br>async def validation_exception_handler(request: Request, exc: RequestValidationError):<br>    body = await request.body()<br>    logging.error(f&quot;Validation error for request body: {body.decode(&#39;utf-8&#39;)}, errors: {exc.errors()}&quot;)<br>    return JSONResponse(<br>        status_code=422,<br>        content={&quot;detail&quot;: exc.errors(), &quot;body&quot;: body.decode(&quot;utf-8&quot;)},<br>    )<br><br>tasks = {}  # Dictionary to store task status and results</pre><p>The backend stores task statuses and results in a dictionary and includes a handler for request validation errors.</p><h3>Processing Endpoints</h3><pre>@app.post(&quot;/process/&quot;)<br>async def process_prompts(request: PromptRequest, background_tasks: BackgroundTasks):<br>    print(f&quot;Received request: {request}&quot;)<br>    logging.info(f&quot;Received request: {request}&quot;)<br>    task_id = str(uuid.uuid4())  # Generate a unique task ID<br>    tasks[task_id] = {&quot;status&quot;: &quot;processing&quot;}<br><br>    if request.processing_mode == &quot;Quick Mode&quot;:<br>        background_tasks.add_task(process_prompts_async, request, task_id, tasks)<br>    else:<br>        background_tasks.add_task(process_prompts_sync, request, task_id, tasks)<br><br>    return {&quot;message&quot;: &quot;Processing started&quot;, &quot;task_id&quot;: task_id}<br><br>@app.get(&quot;/status/{task_id}&quot;)<br>async def check_status(task_id: str):<br>    task = tasks.get(task_id)<br>    if task:<br>        logging.info(f&quot;Returning status for task {task_id}: {task[&#39;status&#39;]}&quot;)<br>        return task<br>    raise HTTPException(status_code=404, detail=&quot;Task not found&quot;)</pre><p>These endpoints start the processing of prompts and check the status of a task based on its unique ID.</p><h3>Synchronous and Asynchronous Processing Functions</h3><pre>def process_prompts_sync(request: PromptRequest, task_id: str, tasks):<br>    logging.info(&quot;Received request in process_prompts&quot;)<br>    try:<br>        logging.info(f&quot;Starting synchronous processing for task {task_id}&quot;)<br>        results = get_answers_sync(request.prompts, request.ai_model_choice, request.common_instructions, request.api_key, request.temperature, request.seed, task_id, tasks)<br>        tasks[task_id] = {&quot;status&quot;: &quot;completed&quot;, &quot;results&quot;: results}<br>        logging.info(f&quot;Task {task_id} completed successfully&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Error in synchronous processing for task {task_id}: {e}&quot;)<br>        tasks[task_id] = {&quot;status&quot;: &quot;failed&quot;, &quot;error&quot;: str(e)}<br><br>async def process_prompts_async(request: PromptRequest, task_id: str, tasks):<br>    try:<br>        logging.info(f&quot;Starting async processing for task {task_id} with {len(request.prompts)} prompts.&quot;)<br>        results = await get_answers_async(request.prompts, request.ai_model_choice, request.common_instructions, request.api_key, request.temperature, request.seed, request.batch_size, task_id, tasks)<br>        tasks[task_id] = {&quot;status&quot;: &quot;completed&quot;, &quot;results&quot;: results}<br>        logging.info(f&quot;Task {task_id} completed successfully&quot;)<br>        logging.info(f&quot;Async processing completed for task {task_id}.&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Error in asynchronous processing for task {task_id}: {e}&quot;)<br>        tasks[task_id] = {&quot;status&quot;: &quot;failed&quot;, &quot;error&quot;: str(e)}</pre><p>The backend can handle prompt processing in both synchronous and asynchronous modes, depending on how complex your prompts are and your OpenAI rate limits, you can pick either one. Async is a lot quicker, here’s the code for the async version:</p><pre>import aiohttp<br>import asyncio<br>import logging<br><br>API_URL = &quot;https://api.openai.com/v1/chat/completions&quot;<br><br>logging.basicConfig(level=logging.INFO)<br><br><br>async def get_answer(session, prompt, ai_model_choice, common_instructions, api_key, temperature, seed): <br>    full_prompt = f&quot;{common_instructions}\n{prompt}&quot; if common_instructions else prompt<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {api_key}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;User-Agent&quot;: &quot;OpenAI Python v0.27.3&quot;<br>    }<br>    data = {<br>        &quot;model&quot;: ai_model_choice,<br>        &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: full_prompt}],<br>        &quot;temperature&quot;: temperature,<br>        &quot;top_p&quot;: 1,<br>        &quot;seed&quot;: seed <br>    }<br>    <br>    logging.info(f&quot;Sending request for prompt: {prompt[:50]}&quot;)<br>    retry_delay = 10  # Initial delay before retrying in seconds<br>    max_retries = 3  # Maximum number of retries<br>    timeout_duration = 1000  # Timeout duration in seconds<br><br>    for attempt in range(max_retries):<br>        try:<br>            async with session.post(API_URL, headers=headers, json=data, timeout=timeout_duration) as response:<br>                if response.status == 429:<br>                    logging.error(&quot;Rate limit exceeded. Retrying after a delay.&quot;)<br>                    await asyncio.sleep(retry_delay)<br>                    retry_delay *= 2  # Increase delay for next retry<br>                    continue  # Retry the request<br><br>                if response.status != 200:<br>                    response_text = await response.text()<br>                    logging.error(f&quot;Non-200 response received: {response.status}\nResponse text: {response_text}&quot;)<br>                    return None<br><br>                response_data = await response.json()<br>                return response_data.get(&#39;choices&#39;, [{}])[0].get(&#39;message&#39;, {}).get(&#39;content&#39;, &#39;&#39;)<br><br>        except aiohttp.ClientError as client_error:<br>            logging.error(f&quot;Client error occurred: {client_error}&quot;)<br>            if attempt &lt; max_retries - 1:<br>                await asyncio.sleep(retry_delay)<br>                retry_delay *= 2<br>            else:<br>                return None<br><br>        except asyncio.TimeoutError:<br>            logging.error(&quot;Request timed out. Retrying.&quot;)<br>            if attempt &lt; max_retries - 1:<br>                await asyncio.sleep(retry_delay)<br>                retry_delay *= 2<br>            else:<br>                return None<br><br>        except Exception as e:<br>            logging.error(f&quot;Unexpected exception occurred: {e}&quot;)<br>            if attempt &lt; max_retries - 1:<br>                await asyncio.sleep(retry_delay)<br>                retry_delay *= 2<br>            else:<br>                return None<br><br>    logging.error(&quot;Maximum retry attempts reached.&quot;)<br>    return None<br><br><br>async def get_answers(prompts, ai_model_choice, common_instructions, api_key, temperature, seed, batch_size, task_id, tasks):<br>    results = []<br>    total = len(prompts)<br>    # Use a context manager to ensure the session is closed after use<br>    async with aiohttp.ClientSession() as session:<br>        for i in range(0, len(prompts), batch_size):<br>            batch_prompts = prompts[i:i+batch_size]<br>            tasks_list = [get_answer(session, prompt, ai_model_choice, common_instructions, api_key, temperature, seed) for prompt in batch_prompts]<br>            batch_results = await asyncio.gather(*tasks_list)<br>            logging.info(f&quot;Batch {i // batch_size + 1}/{(total + batch_size - 1) // batch_size} processed.&quot;)<br>            results.extend(batch_results)<br><br>            # Update progress<br>            progress = f&quot;Processing prompt {min(i + batch_size, total)} of {total}&quot;<br>            tasks[task_id][&#39;progress&#39;] = progress<br><br>            # Check if we need to wait before the next batch<br>            if i + batch_size &lt; total:<br>                await asyncio.sleep(3)  # Adjust the delay as needed<br><br>    # Update the task status in the global dictionary<br>    tasks[task_id] = {&quot;status&quot;: &quot;completed&quot;, &quot;results&quot;: results}<br>    return {&quot;status&quot;: &quot;completed&quot;, &quot;results&quot;: results}</pre><p>What the end result of our app looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgKRA51j1VsdVFU8JOecpA.png" /><figcaption>image from the Author</figcaption></figure><h3>Wrapping up</h3><p>So there you have it! We’ve built a pretty cool tool. Think of this as just the starting point. There’s a lot of ways this project can be expanded — like hooking this up with an assistant API, or perhaps integrating some automation with Zapier for Dropbox into a custom GPT.</p><p>Build it, give it a try and feel free to leave any feedback.</p><p>Thanks for following along and happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e8f420a2898" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/ai-at-scale-automating-tasks-through-bulk-prompt-processing-0e8f420a2898">AI at Scale: Automating Tasks through Bulk Prompt Processing</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your AI Podcast Assistant]]></title>
            <link>https://levelup.gitconnected.com/building-your-ai-podcast-assistant-4944d7262f26?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4944d7262f26</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[podcast]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 20:48:46 GMT</pubDate>
            <atom:updated>2023-12-06T08:00:28.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Transform hours of listening into instant insights</h4><p>As a podcast enthusiast, especially ones on health or business, I often find myself overwhelmed with too many episodes and not enough time. Many podcasts, like the Huberman Lab, can stretch to three or four hours. It’s not just about finding the time; often, I’m only interested in certain parts of the conversation. That’s why I created a straightforward app using OpenAI models, LangChain, and Streamlit. It lets me paste a YouTube podcast link (like Huberman Lab or The Diary of a CEO), and quickly provides a summary of the conversation. Then, I can ask specific questions and get instant answers. This way, I get straight to the information I need without watching the entire episode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufQUvhwoMxEGDdbQTRaQyA.png" /><figcaption>Generated with DALL·E 3.</figcaption></figure><h4>Understanding RAG</h4><p>Before diving into the code, let’s briefly discuss RAG. It’s a method that combines the text-generation ability of models like GPT-4 with information retrieval to provide precise, context-relevant information. LLMs might not always have access to specific data we need. RAG lets us input relevant data (like our podcast transcripts), so the model can deliver pertinent answers.</p><p>Here’s the simple process: We load our data (like podcast transcripts), break it into smaller segments, embed these, and store them in a vector database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5F8H92vt23206Fd.png" /><figcaption>image from LangChain</figcaption></figure><p>When we query, the model compares our question to these data segments. The most relevant texts are retrieved and fed to the LLM along with our question, generating an accurate answer. In essence, RAG retrieves relevant information and uses it to answer our queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CARghQ88pXRfH37S.png" /><figcaption>image from LangChain</figcaption></figure><p>That’s it, at a high level, this is what RAG does. It retrieves the pieces of information that are relevant to your query, and then uses both to generate an answer.</p><h4>How the App Works</h4><p>The app is user-friendly: paste a YouTube podcast URL into the Streamlit interface, enter your OpenAI key, and voilà! In moments, you’ll have a summary of the podcast. You can then ask specific questions like, “What books were recommended?” or “What are the top sleep tips mentioned?”.</p><p>The code is split into three main parts: fetching data from YouTube, generating summaries and answers, and the Streamlit frontend. There’s an optional fourth part for advanced RAG usage, but the basic version works quite well. Let’s dive into the code!</p><h3>Part 1: Interacting with YouTube</h3><p>To start, our app connects to YouTube, retrieving video titles and captions — key to understanding the podcast’s content.</p><p><strong>Function 1: Fetching Video Titles</strong></p><p>This function grabs a YouTube video’s title using its URL. It sends a web request, parses the HTML to find the title tag, and returns the title. It’s our first step to knowing what each video is about.</p><pre>import requests<br>from bs4 import BeautifulSoup<br><br>def get_youtube_video_title(video_url):<br>    response = requests.get(video_url)<br>    soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br>    title = soup.find(&#39;meta&#39;, property=&#39;og:title&#39;)<br>    return title[&#39;content&#39;] if title else &quot;Title not found&quot;</pre><p><strong>Function 2: Gathering Captions</strong></p><p>Next, we fetch the video’s captions. We use the title-fetching function and employ the YoutubeLoader from LangChain to load captions. These transcripts will feed into our RAG system for generating relevant responses.</p><pre>from langchain.document_loaders import YoutubeLoader<br>from langchain.schema import Document<br><br>def fetch_youtube_captions(video_url):<br>    title = get_youtube_video_title(video_url)<br>    loader = YoutubeLoader.from_youtube_url(https://medium.com/video_url)<br>    docs = loader.load()<br>    if docs and len(docs) &gt; 0:<br>        intro_sentence = &quot;This is the title of the video/transcription/conversation: &quot;<br>        title_content = intro_sentence + title<br>        docs[0] = Document(page_content=title_content + &quot;\n\n&quot; + docs[0].page_content)<br>    return docs</pre><h3>Part 2: Data Processing and AI Integration</h3><h4>Core App Logic: Turning Conversations into Data</h4><p>This is where the magic happens. We’ll break down the podcast into digestible pieces, transform them for our AI, and store them for easy retrieval and summary generation.</p><p><strong>Environment Setup and Global Variables</strong></p><p>We begin by setting up our coding environment and defining global variables. This includes initializing a database and a memory system for our conversations.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br>from sklearn.cluster import KMeans<br>from langchain.chat_models import ChatOpenAI<br>from langchain.chains.summarize import load_summarize_chain<br>from langchain.schema import Document<br>import numpy as np<br>from langchain.chains import ConversationalRetrievalChain<br>import logging<br>from langchain.prompts import PromptTemplate<br>from langchain.memory import ConversationBufferMemory<br><br><br>logging.basicConfig(level=logging.INFO) <br># Initialize global variables<br>global_chromadb = None<br>global_documents = None<br>global_short_documents = None</pre><p><strong>Functions for Data Management</strong></p><p>These functions are crucial for managing your application’s data. reset_globals resets the global variables, init_chromadb initializes a database with the processed data.</p><pre># Initialize the memory outside the function so it persists across different calls<br>conversation_memory = ConversationBufferMemory(<br>    memory_key=&quot;chat_history&quot;,<br>    max_len=50,<br>    input_key=&quot;question&quot;,<br>    output_key=&quot;answer&quot;,<br>    return_messages=True,<br>)<br><br># Function to reset global variables<br>def reset_globals():<br>    global global_chromadb, global_documents, global_short_documents<br>    global_chromadb = None<br>    global_documents = None<br>    global_short_documents = None<br>    # Reset the conversation memory<br>    if conversation_memory:<br>        conversation_memory.clear()<br><br>def init_chromadb(openai_api_key):<br>    global global_chromadb, global_short_documents<br>    if global_chromadb is None and global_short_documents is not None:<br>        global_chromadb = Chroma.from_documents(documents=global_short_documents, embedding=OpenAIEmbeddings(openai_api_key=openai_api_key))</pre><h4><strong>Processing Captions and Generating Summaries</strong></h4><p>process_and_cluster_captions: Here, we process the YouTube captions, preparing them for analysis and response generation. Here’s the process:</p><ol><li><strong>Initial Data Check:</strong> We begin by verifying the format of the captions, ensuring they’re suitable for processing.</li><li><strong>Dividing Captions:</strong> The captions are divided into smaller segments for two purposes: one set for summarization and another for question-answering. This division is crucial for handling specific tasks efficiently.</li><li><strong>Clustering for Relevance:</strong> We use the KMeans algorithm to cluster the summary segments. This is a strategic move to filter out redundant content and focus only on the most representative parts of the podcast. By selecting one segment from each cluster, we ensure that the AI receives diverse yet concise information, perfect for creating a meaningful summary.</li><li><strong>Global Accessibility:</strong> The segmented captions are stored globally, allowing easy access for both summarization and answering queries.</li></ol><pre>def process_and_cluster_captions(captions, openai_api_key, num_clusters=12):<br>    global global_documents, global_short_documents <br>    logging.info(&quot;Processing and clustering captions&quot;)<br>    <br>    # Log the first 500 characters of the captions to check their format<br>    logging.info(f&quot;Captions received (first 500 characters): {captions[0].page_content[:500]}&quot;)<br>    caption_content = captions[0].page_content<br><br>    # Ensure captions is a string before processing<br>    if not isinstance(caption_content, str):<br>        logging.error(&quot;Captions are not in the expected string format&quot;)<br>        return []<br>    <br>    # Create longer chunks for summary<br>    summary_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0, separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;])<br>    summary_docs = summary_splitter.create_documents([caption_content])<br><br>    # Create shorter chunks for QA<br>    qa_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=0, separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;])<br>    qa_docs = qa_splitter.create_documents([caption_content])<br>    <br>    # Process for summary<br>    summary_embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key).embed_documents([x.page_content for x in summary_docs])<br>    kmeans = KMeans(n_clusters=num_clusters, random_state=42).fit(summary_embeddings)<br>    closest_indices = [np.argmin(np.linalg.norm(summary_embeddings - center, axis=1)) for center in kmeans.cluster_centers_]<br>    representative_docs = [summary_docs[i] for i in closest_indices]<br><br>    # Store documents globally<br>    global_documents = summary_docs  # For summary<br>    global_short_documents = qa_docs  # For QA<br><br>    init_chromadb(openai_api_key)  # Initialize database with longer chunks<br>    return representative_docs</pre><p>generate_summary: This function takes the processed captions and generates a clear, concise summary of the video, leveraging an AI model from OpenAI. Here’s how:</p><ol><li><strong>Combining Key Segments: </strong>We amalgamate the chosen segments from the clustering process to form a continuous narrative. This ensures that the summary covers different aspects of the podcast.</li><li><strong>Guided AI Summary:</strong> Using a custom prompt, we instruct the AI to focus on creating a concise and informative summary. This step is crucial for directing the AI’s attention to the overarching themes and important points, avoiding unnecessary details.</li><li><strong>Executing Summary Chain:</strong> The AI then processes this combined text and generates a summary, offering users a quick understanding of the podcast’s core content.</li></ol><p>This method ensures the generation of a summary that is both comprehensive and to the point, capturing the essence of the podcast.</p><pre>def generate_summary(representative_docs, openai_api_key, model_name):<br>    logging.info(&quot;Generating summary&quot;)<br>    llm4 = ChatOpenAI(model_name=model_name, temperature=0.2, openai_api_key=openai_api_key)<br><br>    # Concatenate texts for summary<br>    summary_text = &quot;\n&quot;.join([doc.page_content for doc in representative_docs])<br><br>    summary_prompt_template = PromptTemplate(<br>        template=(<br>            &quot;Create a concise summary of a podcast conversation based on the text provided below. The text consists of selected, representative sections from different parts of the conversation. &quot;<br>            &quot;Your task is to synthesize these sections into a single cohesive and concise summary. Focus on the overarching themes and main points discussed throughout the podcast. &quot;<br>            &quot;The summary should give a clear and complete understanding of the conversation&#39;s key topics and insights, while omitting any extraneous details. It should be engaging and easy to read, ideally in one or two paragraphs. Keep it short where possible&quot;<br>            &quot;\n\nSelected Podcast Sections:\n{text}\n\nSummary:&quot;<br>        ),<br>        input_variables=[&quot;text&quot;]<br>    )<br>    # Load summarizer chain<br>    summarize_chain = load_summarize_chain(llm=llm4, chain_type=&quot;stuff&quot;, prompt=summary_prompt_template)<br><br>    # Run the summarizer chain<br>    summary = summarize_chain.run([Document(page_content=summary_text)])<br><br>    logging.info(&quot;Summary generation completed&quot;)<br>    return summarypythonCopy code</pre><h4><strong>Answering User Questions</strong></h4><p><strong>answer_question</strong>: The heart of our RAG system. This function uses the processed data to answer specific user queries, showcasing the power of retrieval-augmented generation.</p><ol><li><strong>Database Initialization:</strong> It first checks if the database, containing the processed segments, is ready. If not, it initializes the database for efficient retrieval.</li><li><strong>Retrieval and Response Generation: </strong>The function then combines the user’s query with the relevant data retrieved from our database. This retrieval is tailored to find the most pertinent context for the question, ensuring that the AI’s response is accurate and relevant.</li><li><strong>Generating Context-Aware Answers: </strong>The AI, equipped with the question and the best-matched context, crafts an answer that is succinct and directly addresses the user’s query.</li></ol><p>Through this process, users receive targeted, informed responses, enhancing their interaction with the podcast content.</p><pre>def answer_question(question, openai_api_key, model_name):<br>    llm4 = ChatOpenAI(model_name=model_name, temperature=0, openai_api_key=openai_api_key)<br>    global global_chromadb, global_short_documents<br><br>    if global_chromadb is None and global_short_documents is not None:<br>        init_chromadb(openai_api_key, documents=global_short_documents)<br>    <br>    logging.info(f&quot;Answering question: {question}&quot;)<br>    chatTemplate = &quot;&quot;&quot;<br>    You are an AI assistant tasked with answering questions based on context from a podcast conversation. Use the provided context and relevant chat messages to answer. If unsure, say so. Keep your answer to three sentences or less, focusing on the most relevant information.<br>    Chat Messages (if relevant): {chat_history}<br>    Question: {question} <br>    Context from Podcast: {context} <br>    Answer:&quot;&quot;&quot;<br>    QA_CHAIN_PROMPT = PromptTemplate(input_variables=[&quot;context&quot;, &quot;question&quot;, &quot;chat_history&quot;],template=chatTemplate)<br>    qa_chain = ConversationalRetrievalChain.from_llm(<br>        llm=llm4, <br>        chain_type=&quot;stuff&quot;, <br>        retriever=global_chromadb.as_retriever(search_type=&quot;mmr&quot;, search_kwargs={&quot;k&quot;:12}),<br>        memory=conversation_memory,<br>        #return_source_documents=True,<br>        combine_docs_chain_kwargs={&#39;prompt&#39;: QA_CHAIN_PROMPT},<br>    )<br>    # Log the current chat history<br>    current_chat_history = conversation_memory.load_memory_variables({})<br>    logging.info(f&quot;Current Chat History: {current_chat_history}&quot;)<br>    response = qa_chain({&quot;question&quot;: question}) <br>    logging.info(f&quot;this is the result: {response}&quot;)<br>    output = response[&#39;answer&#39;]    <br><br>    return output</pre><h3>Part 3: Streamlit User Interface</h3><h4>Bringing the App to Life</h4><p>Finally, we use Streamlit to create an interactive web app to bring it all together. Users can input YouTube links, ask questions, and get AI-generated summaries and answers. The code below is my own version of the interface, feel free to use mine or customize it to your preference.</p><pre>import streamlit as st<br>from youtuber import fetch_youtube_captions<br>from agent import process_and_cluster_captions, generate_summary, answer_question, reset_globals<br><br># Set Streamlit page configuration with custom tab title<br>st.set_page_config(page_title=&quot;🏄GPTpod&quot;, page_icon=&quot;🏄&quot;, layout=&quot;wide&quot;)<br><br>def user_query(question, openai_api_key, model_name):<br>    &quot;&quot;&quot;Process and display the query response.&quot;&quot;&quot;<br>    # Add the user&#39;s question to the conversation<br>    st.session_state.conversation.append((f&quot;{question}&quot;, &quot;user-message&quot;))<br><br>    # Check if this query has been processed before<br>    if question not in st.session_state.processed_questions:<br>        # Process the query<br>        answer = answer_question(question, openai_api_key, model_name)<br>        if isinstance(answer, str):<br>            st.session_state.conversation.append((f&quot;{answer}&quot;, &quot;grimoire-message&quot;))<br>        else:<br>            st.session_state.conversation.append((&quot;Could not find a proper answer.&quot;, &quot;grimoire-message&quot;))<br>        <br>        st.rerun()<br><br>        # Mark this question as processed<br>        st.session_state.processed_questions.add(question)<br><br><br># Initialize session state<br>if &#39;conversation&#39; not in st.session_state:<br>    st.session_state.conversation = []<br>    st.session_state.asked_questions = set()<br>    st.session_state.processed_questions = set()<br><br># Sidebar for input and operations<br>with st.sidebar:<br>    st.title(&quot;GPT Podcast Surfer🌊🏄🏼&quot;)<br>    st.image(&quot;img.png&quot;) <br><br>    # Expandable Instructions<br>    with st.expander(&quot;🔍 How to use:&quot;, expanded=False):<br>        st.markdown(&quot;&quot;&quot;<br>            - 🔐 **Enter your OpenAI API Key.**<br>            - 📺 **Paste a YouTube URL.**<br>            - 🏃‍♂️ **Click &#39;Run it&#39; to process.**<br>            - 🕵️‍♂️ **Ask questions in the chat.**<br>        &quot;&quot;&quot;)<br><br>    # Model selection in the sidebar<br>    model_choice = st.sidebar.selectbox(&quot;Choose Model:&quot;, <br>                                        (&quot;GPT-4 Turbo&quot;, &quot;GPT-3.5 Turbo&quot;), <br>                                        index=0)  # Default to GPT-4 Turbo<br><br>    # Map friendly names to actual model names<br>    model_name_mapping = {<br>        &quot;GPT-4 Turbo&quot;: &quot;gpt-4-1106-preview&quot;,<br>        &quot;GPT-3.5 Turbo&quot;: &quot;gpt-3.5-turbo&quot;<br>    }<br><br>    selected_model = model_name_mapping[model_choice]<br>    st.session_state[&#39;selected_model&#39;] = model_name_mapping[model_choice]<br><br><br>    # Input for OpenAI API Key<br>    openai_api_key = st.text_input(&quot;Enter your OpenAI API Key:&quot;, type=&quot;password&quot;)<br><br>    # Save the API key in session state if it&#39;s entered<br>    if openai_api_key:<br>        st.session_state[&#39;openai_api_key&#39;] = openai_api_key<br><br>    youtube_url = st.text_input(&quot;Enter YouTube URL:&quot;)<br><br>    # Button to trigger processing<br>    if st.button(&quot;🚀Run it&quot;):<br>        if openai_api_key:<br>            if youtube_url and &#39;processed_data&#39; not in st.session_state:<br>                reset_globals()<br>                with st.spinner(&#39;👩‍🍳 GPT is cooking up your podcast... hang tight for a few secs🍳&#39;):<br>                    captions = fetch_youtube_captions(youtube_url)<br>                    if captions:<br>                        representative_docs = process_and_cluster_captions(captions, st.session_state[&#39;openai_api_key&#39;])<br>                        summary = generate_summary(representative_docs, st.session_state[&#39;openai_api_key&#39;], selected_model)<br>                        st.session_state.processed_data = (representative_docs, summary)<br>                        if &#39;summary_displayed&#39; not in st.session_state:<br>                            st.session_state.conversation.append((f&quot;Here&#39;s a rundown of the conversation: {summary}&quot;, &quot;summary-message&quot;))<br>                            guiding_message = &quot;Feel free to ask me anything else about it! :)&quot;<br>                            st.session_state.conversation.append((guiding_message, &quot;grimoire-message&quot;))<br>                            st.session_state[&#39;summary_displayed&#39;] = True<br>                    else:<br>                        st.error(&quot;Failed to fetch captions.&quot;)<br>        else:<br>            st.warning(&quot;Please add the OpenAI API key first.&quot;)<br><br><br># Main app logic<br>for message, css_class in st.session_state.conversation:<br>    role = &quot;assistant&quot; if css_class in [&quot;grimoire-message&quot;, &quot;summary-message&quot;, &quot;suggestion-message&quot;] else &quot;user&quot;<br>    with st.chat_message(role):<br>        st.markdown(message)<br><br><br># Chat input field<br>if prompt := st.chat_input(&quot;Ask me anything about the podcast...&quot;):<br>    user_query(prompt, st.session_state.get(&#39;openai_api_key&#39;, &#39;&#39;), st.session_state.get(&#39;selected_model&#39;, &#39;gpt-4-1106-preview&#39;))</pre><p>Here’s what the frontend looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAly8xZoEJ6jyETnDUBygg.png" /><figcaption>image from the author</figcaption></figure><h3>Part 4: Optional RAG-Fusion for Enhanced Results</h3><p><strong>The Concept of RAG-Fusion</strong></p><p>RAG-Fusion is an experimental feature I added for a bit of an upgrade. While it’s not necessary, it offers improved results at the cost of slightly more code and a bit of speed. The idea is to refine the AI’s understanding and response accuracy.</p><h4><strong>Why RAG-Fusion?</strong></h4><ul><li><strong>Filling the Gaps:</strong> It overcomes some limitations of standard RAG by generating and reevaluating multiple versions of a user’s query. This ensures a broader and more accurate search.</li><li><strong>Better Search Results:</strong> It combines Reciprocal Rank Fusion and custom vector scoring, leading to more comprehensive and precise answers.</li></ul><p>RAG-Fusion aims to decode not just what users ask but also what they mean to ask, digging deeper to uncover insights that are often missed.</p><h4>RAG-Fusion’s Workflow</h4><ol><li><strong>Transforming Queries</strong>: We start by translating the original user query into several similar yet distinct questions using a language model. This multi-perspective approach is crucial for a thorough search.</li><li><strong>Enhanced Vector Searches: </strong>Each of these new queries undergoes a vector search, gathering diverse results.</li><li><strong>Smart Reranking:</strong> Using reciprocal rank fusion, we reorganize all these results, prioritizing the most relevant ones.</li><li><strong>Crafted Final Output:</strong> The top results, along with the new queries, guide the language model to generate a response that’s informed by a wider context.</li></ol><h4>Key Functions in RAG-Fusion</h4><ul><li><strong>reciprocal_rank_fusion:</strong> This function reshuffles the search results based on their relevance scores, ensuring that the best answers are considered first.</li><li><strong>generate_multiple_queries:</strong> It creates several variations of the initial query, expanding the search scope.</li><li><strong>answer_question: </strong>This is where everything comes together. The function first generates multiple queries, retrieves documents for each, and applies reciprocal rank fusion. It then uses a custom database with these refined results to guide the AI in crafting a more informed and accurate response.</li></ul><pre>def reciprocal_rank_fusion(results: list[list], k=60):<br>    fused_scores = {}<br>    for docs in results:<br>        # the docs are returned in sorted order of relevance<br>        for rank, doc in enumerate(docs):<br>            doc_str = dumps(doc)<br>            logging.info(f&quot;Serialized Document: {doc_str}&quot;)<br>            if doc_str not in fused_scores:<br>                fused_scores[doc_str] = 0<br>            previous_score = fused_scores[doc_str]<br>            fused_scores[doc_str] += 1 / (rank + k)<br><br>    reranked_results = [<br>        loads(doc)<br>        for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)<br>    ]<br>    logging.info(f&quot;Reciprocal Rank Fusion applied. Reranked Results: {reranked_results[:10]}&quot;)  # Log top 10 results<br>    return reranked_results<br><br><br>def generate_multiple_queries(question, llm):<br>    prompt = PromptTemplate(<br>    input_variables=[&quot;question&quot;],<br>    template=&quot;&quot;&quot;You are an AI language model assistant. Your task is to OUTPUT 4 <br>    different versions of the given user question to retrieve relevant documents from a vector <br>    database. By generating multiple perspectives on the user question, your goal is to help<br>    the user overcome some of the limitations of the distance-based similarity search. <br>    Provide these alternative questions separated by newlines.<br>    Original question: {question}&quot;&quot;&quot;,<br>)<br>    # Create a chain with the language model and the prompt<br>    llm_chain = LLMChain(llm=llm, prompt=prompt, output_parser=StrOutputParser())<br><br>    # Run the chain<br>    response = llm_chain.run({&quot;question&quot;: question})<br>    queries = response.split(&quot;\n&quot;)<br>    <br>    logging.info(f&quot;Generated Queries: {queries}&quot;)<br>    return queries<br><br><br>def answer_question(question, openai_api_key, model_name):<br>    llm4 = ChatOpenAI(model_name=model_name, temperature=0.1, openai_api_key=openai_api_key)<br>    global global_chromadb, global_short_documents<br><br>    if global_chromadb is None and global_short_documents is not None:<br>        init_chromadb(openai_api_key, documents=global_short_documents)<br>    <br>    logging.info(f&quot;Answering question: {question}&quot;)<br>    # Generate multiple queries<br>    queries = generate_multiple_queries(question, llm4)<br><br>    # Retrieve documents for each query<br>    results = []<br>    for query in queries:<br>        retrieved_docs_with_scores = global_chromadb.similarity_search_with_score(query, k=8)<br>        # Log the number of documents retrieved for each query and the first 3 docs<br>        logging.info(f&quot;Retrieved {len(retrieved_docs_with_scores)} documents for query &#39;{query}&#39;: {retrieved_docs_with_scores[:3]}&quot;)<br>        results.append(retrieved_docs_with_scores)<br><br>    # Apply reciprocal rank fusion<br>    reranked_results = reciprocal_rank_fusion(results)<br>    logging.info(f&quot;Number of reranked documents: {len(reranked_results)}&quot;)<br><br>    #extract the Document object only<br>    reranked_documents = [doc for doc, _ in reranked_results]<br><br>    # Create a new Chroma instance with reranked results<br>    custom_chromadb = Chroma.from_documents(documents=reranked_documents, embedding=OpenAIEmbeddings(openai_api_key=openai_api_key))<br><br>    chatTemplate = &quot;&quot;&quot;<br>    You are an AI assistant tasked with answering questions based on context from a podcast conversation.<br>    Use the provided context and relevant chat messages to answer. If unsure, say so. Keep your answer to four sentences or less, focusing on the most relevant information.<br>    Chat Messages (if relevant): {chat_history}<br>    Question: {question} <br>    Context from Podcast: {context} <br>    Answer:&quot;&quot;&quot;<br>    QA_CHAIN_PROMPT = PromptTemplate(input_variables=[&quot;context&quot;, &quot;question&quot;, &quot;chat_history&quot;],template=chatTemplate)<br>    qa_chain = ConversationalRetrievalChain.from_llm(<br>        llm=llm4, <br>        chain_type=&quot;stuff&quot;, <br>        retriever=custom_chromadb.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;:10}),<br>        memory=conversation_memory,<br>        return_source_documents=True,<br>        combine_docs_chain_kwargs={&#39;prompt&#39;: QA_CHAIN_PROMPT},<br>    )<br>    # Log the current chat history<br>    current_chat_history = conversation_memory.load_memory_variables({})<br>    logging.info(f&quot;Current Chat History: {current_chat_history}&quot;)<br>    response = qa_chain({&quot;question&quot;: question}) <br>    logging.info(f&quot;Final response: {response}&quot;)<br>    output = response[&#39;answer&#39;]   <br><br>    return output</pre><h4>Wrapping up</h4><p>And there you have it! A step-by-step guide to creating an interactive, AI-powered podcast app. Give it a try <a href="https://gptpod.streamlit.app/">here</a> and feel free to leave any feedback.</p><p>Thanks for following along and happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4944d7262f26" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-your-ai-podcast-assistant-4944d7262f26">Building Your AI Podcast Assistant</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI Tool to Summarize Books Instantly]]></title>
            <link>https://levelup.gitconnected.com/build-an-ai-tool-to-summarize-books-instantly-828680c1ceb4?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/828680c1ceb4</guid>
            <category><![CDATA[books]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 16:31:05 GMT</pubDate>
            <atom:updated>2023-11-07T16:31:05.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get the gist of any book without reading it cover to cover.</h4><p>In this article, we’ll build a simple yet powerful book summarizer using Python, Langchain and OpenAI embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFqc1P6PnOZ8S95puZqSEg.png" /><figcaption>Generated with DALL·E 3.</figcaption></figure><h3>The Challenge</h3><p>AI models like GPT-3 and GPT-4 are incredibly powerful, but they have their limitations. One significant limitation is the context window, which restricts the amount of text the model can consider at any one time. This means you can’t just feed an entire book into the model and expect a coherent summary. Moreover, processing large texts can be costly.</p><h3>The Solution</h3><p>To overcome these challenges, we’ve devised a method that is both cost-effective and efficient. Here’s the process:</p><h3>The Process Simplified</h3><p>Here’s how we transform a full-length book into a concise summary:</p><ol><li><strong>Splitting &amp; Embeddings</strong>: We break down the book into smaller chunks and convert them into embeddings. This step is surprisingly affordable.</li><li><strong>Clustering:</strong> Next, we cluster these embeddings to find the most representative sections of the book.</li><li><strong>Summarization:</strong> We then summarize these key sections using the more cost-effective GPT-3.5 model.</li><li><strong>Combining Summaries: </strong>Finally, we use GPT-4 to stitch these summaries into one fluid narrative.</li></ol><p>By using GPT-4 only in the final step, we manage to keep our costs low.</p><p>Now, let’s break down the code and the rationale behind each step.Building the Summarizer</p><p>Let’s dive into the code and build our summarizer step by step.</p><h3>Step 1: Load the Book</h3><p>First, we need to read the book’s content. We’ll support PDF and EPUB formats.</p><pre>import os<br>import tempfile<br>from langchain.document_loaders import PyPDFLoader, UnstructuredEPubLoader<br><br>def load_book(file_obj, file_extension):<br>    &quot;&quot;&quot;Load the content of a book based on its file type.&quot;&quot;&quot;<br>    text = &quot;&quot;<br>    with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:<br>        temp_file.write(file_obj.read())<br>        if file_extension == &quot;.pdf&quot;:<br>            loader = PyPDFLoader(temp_file.name)<br>            pages = loader.load()<br>            text = &quot;&quot;.join(page.page_content for page in pages)<br>        elif file_extension == &quot;.epub&quot;:<br>            loader = UnstructuredEPubLoader(temp_file.name)<br>            data = loader.load()<br>            text = &quot;\n&quot;.join(element.page_content for element in data)<br>        else:<br>            raise ValueError(f&quot;Unsupported file extension: {file_extension}&quot;)<br>        os.remove(temp_file.name)<br>    text = text.replace(&#39;\t&#39;, &#39; &#39;)<br>    return text</pre><h3>Step 2: Split and Embed the Text</h3><p>AI models have a token limit, which means they can’t process a whole book at once. By splitting the text into chunks, we ensure that each section is digestible for the AI.</p><p>We’ll split the text into chunks and convert them into embeddings. Embeddings convert text into a compact numerical form quickly and with minimal computation, making the process both fast and cost-effective.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import OpenAIEmbeddings<br><br>def split_and_embed(text, openai_api_key):<br>    text_splitter = RecursiveCharacterTextSplitter(separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;\t&quot;], chunk_size=10000, chunk_overlap=3000)<br>    docs = text_splitter.create_documents([text])<br>    embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)<br>    vectors = embeddings.embed_documents([x.page_content for x in docs])<br>    return docs, vectors</pre><h3>Step 3: Cluster the Embeddings</h3><p>We use KMeans clustering to group similar chunks. In my version, as you can see below, I found 11 as the number of clusters to work quite well for most books. But you can tweak that for your use case.</p><p>Here, after we’ve turned the whole book into chunks and then into embeddings. These embeddings are grouped based on their similarity. For each group, we pick the most representative embedding and map it back to its corresponding text chunk.</p><pre>from sklearn.cluster import KMeans<br>import numpy as np<br><br>def cluster_embeddings(vectors, num_clusters):<br>    kmeans = KMeans(n_clusters=num_clusters, random_state=42).fit(vectors)<br>    closest_indices = [np.argmin(np.linalg.norm(vectors - center, axis=1)) for center in kmeans.cluster_centers_]<br>    return sorted(closest_indices)</pre><h3>Step 4: Summarize the Representative Chunks</h3><p>We’ll summarize only the selected chunks using GPT-3.5.</p><pre>from langchain.chains.summarize import load_summarize_chain<br>from langchain.prompts import PromptTemplate<br><br>def summarize_chunks(docs, selected_indices, openai_api_key):<br>    llm3_turbo = ChatOpenAI(temperature=0, openai_api_key=openai_api_key, max_tokens=1000, model=&#39;gpt-3.5-turbo-16k&#39;)<br>    map_prompt = &quot;&quot;&quot;<br>    You are provided with a passage from a book. Your task is to produce a comprehensive summary of this passage. Ensure accuracy and avoid adding any interpretations or extra details not present in the original text. The summary should be at least three paragraphs long and fully capture the essence of the passage.<br>    ```{text}```<br>    SUMMARY:<br>    &quot;&quot;&quot;<br>    map_prompt_template = PromptTemplate(template=map_prompt, input_variables=[&quot;text&quot;])<br>    selected_docs = [docs[i] for i in selected_indices]<br>    summary_list = []<br><br>    for doc in selected_docs:<br>        chunk_summary = load_summarize_chain(llm=llm3_turbo, chain_type=&quot;stuff&quot;, prompt=map_prompt_template).run([doc])<br>        summary_list.append(chunk_summary)<br>    <br>    return &quot;\n&quot;.join(summary_list)</pre><h3>Step 5: Create the Final Summary</h3><p>We combine the individual summaries into one final, cohesive summary using GPT-4.</p><pre>from langchain.schema import Document<br>from langchain.chat_models import ChatOpenAI<br><br>def create_final_summary(summaries, openai_api_key):<br>    llm4 = ChatOpenAI(temperature=0, openai_api_key=openai_api_key, max_tokens=3000, model=&#39;gpt-4&#39;, request_timeout=120)<br>    combine_prompt = &quot;&quot;&quot;<br>    You are given a series of summarized sections from a book. Your task is to weave these summaries into a single, cohesive, and verbose summary. The reader should be able to understand the main events or points of the book from your summary. Ensure you retain the accuracy of the content and present it in a clear and engaging manner.<br>    ```{text}```<br>    COHESIVE SUMMARY:<br>    &quot;&quot;&quot;<br>    combine_prompt_template = PromptTemplate(template=combine_prompt, input_variables=[&quot;text&quot;])<br>    reduce_chain = load_summarize_chain(llm=llm4, chain_type=&quot;stuff&quot;, prompt=combine_prompt_template)<br>    final_summary = reduce_chain.run([Document(page_content=summaries)])<br>    return final_summary</pre><h3>Bringing It All Together</h3><p>Now, we combine all the steps into a single function that takes an uploaded file and generates a summary.</p><pre># ... (previous code for imports and functions)<br><br>def generate_summary(uploaded_file, openai_api_key, num_clusters=11, verbose=False):<br>    file_extension = os.path.splitext(uploaded_file.name)[1].lower()<br>    text = load_book(uploaded_file, file_extension)<br>    docs, vectors = split_and_embed(text, openai_api_key)<br>    selected_indices = cluster_embeddings(vectors, num_clusters)<br>    summaries = summarize_chunks(docs, selected_indices, openai_api_key)<br>    final_summary = create_final_summary(summaries, openai_api_key)<br>    return final_summary</pre><h3>Testing the Summarizer</h3><p>Finally, we can test our summarizer with a book file.</p><pre># Testing the summarizer<br>if __name__ == &#39;__main__&#39;:<br>    load_dotenv()<br>    openai_api_key = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>    book_path = &quot;path_to_your_book.epub&quot;<br>    with open(book_path, &#39;rb&#39;) as uploaded_file:<br>        summary = generate_summary(uploaded_file, openai_api_key, verbose=True)<br>        print(summary)</pre><h3>Wrapping up</h3><p>This tool can help you quickly understand the key points of any book quickly. The approach we’ve taken is not only cheap but also works for books of any length.</p><p>Remember, the quality of the summary depends on the clustering and the summarization prompts, so feel free to tweak those to your needs.</p><p>You can try out the Streamlit app and see the summarizer here: <a href="https://gptsummarizer.streamlit.app/">GPT Summarizer App</a>.</p><p>I hope this article has been helpful. If you have any questions or feedback, please leave a comment or reach out.</p><p>Happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=828680c1ceb4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-an-ai-tool-to-summarize-books-instantly-828680c1ceb4">Build an AI Tool to Summarize Books Instantly</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of DALL-E 3]]></title>
            <link>https://medium.com/@alessandroamenta1/making-sense-of-dall-e-3s-magic-08ce61845041?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/08ce61845041</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 17:58:48 GMT</pubDate>
            <atom:updated>2023-11-15T23:53:19.037Z</atom:updated>
            <content:encoded><![CDATA[<p>DALL-E 3 recently came out this month, and I absolutely love playing with it. I know diffusion models have been around for a minute, but I’m genuinely blown away by how good they’ve become. This one below is the first image I generated with DALL-E 3 a couple days ago, with a super simple prompt: “create a painting of a father and son looking at the sunset in Van Gogh style”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QzvjvYfWwhARTPsv.png" /><figcaption>Courtesy of DALL-E 3</figcaption></figure><p>It’s crazy how just some text can translate into such a detailed image, the image is probably better than what I could’ve imagined in my head. So yeah, since I’m super into this I find it even more fascinating to explore how these models work. How do we go from a line of text, to an image that really captures the essence of our prompt?</p><h3>The Basics</h3><p>Before we dive in, it’s worth spending a short paragraph on neural nets in general. If you’re kinda new to the whole machine learning or deep learning scene, no problem. And even if you’re familiar with it, here’s a simple way I like to think about neural nets:</p><p>You just feed them some inputs, define a loss function and the kind of outputs you’re looking for, and that’s it! They get to work and figure it out for you. One of the coolest things about deep learning.</p><p>Picture this:</p><p>Human: “Man, I have no idea how to solve this!”<br>Neural Network: “Chill! Just tell me what you have and what you want, and I’ll sort it out.”</p><p>What’s crazy to me is that so much of what we dive into in deep learning, even the really fancy models, boils down to this basic idea.</p><p>Now, on to diffusion models…</p><h3>Diffusion Models: A Quick Overview</h3><p>At their core, diffusion models work in stages or a “pipeline” — basically a few different models working together to get to the finished artwork. Think of it as making a sculpture. You start with a rough block of raw material and refine it step-by-step until you get the finished piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2M8lnHEJCI-oKHGe.png" /></figure><p>source <a href="https://learnopencv.com/author/sovit/">Sovit Rath</a></p><p>There are three main components to latent diffusion models:</p><ol><li>A <a href="https://arxiv.org/abs/1505.04597">U-Net</a>. Works with noisy images and refines them. The U-Net’s main task is to, given a noisy image, figure out what’s noise and what’s not.</li><li>An Autoencoder (<a href="https://arxiv.org/abs/1906.02691">VAE</a>). It’s main job is to compress high-definition images so that we can train the U-Net using those.</li><li>A text-encoder, <em>e.g.</em> <a href="https://arxiv.org/abs/2103.00020">CLIP’s Text Encoder</a>. It understands text, its responsible for providing guidance to our U-Net during training and interpret our text prompt at inference time. A blueprint for what the U-Net should create.</li></ol><h3>Diving Deeper:</h3><p><strong>1. U-Net and Noise:<br></strong>U-Net’s main responsibility is to differentiate noise from content within images. This iterative refining process takes out unwanted noise from the images. The challenge here is the computational cost during training — it’s expensive to deal with high-definition images.</p><p><strong>2. VAE: The Art of Compression:<br></strong>VAEs, or Variational Autoencoders, are made up of an encoder, which compresses an image into a lower-dimensional representation (latents), and a decoder, which reconstructs the image from these latents. This makes it faster and a lot cheaper to train our model — we use these latents to train our U-Net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2aqM1bsB9em7dK6C.png" /><figcaption>Autoencoder architecture</figcaption></figure><p><strong>3. CLIP: Bridging Text and Image:<br></strong>Going from a textual prompt to a relevant image representing it requires a deep understanding of the text. That’s where CLIP comes in: with two encoders — one for text and another for images — it uses contrastive learning to align text with its visual counterpart. Essentially, CLIP ensures related text-image pairs share similar embeddings. For example, a prompt about a “golden retriever playing in the park” will be matched with a fitting image, distinguishing it from unrelated/dissimilar visuals. If text and image embeddings are similar, they end up close to each other in the embedding space.</p><p><strong>4. Training U-Net with CLIP Embeddings:<br></strong>Now that we have the textual understanding of CLIP and the noisy latents from the VAE, we have all we need to train the U-Net. Once trained the U-Net can spit out denoised latents that are incredibly good at representing the textual prompt we provided.</p><p><strong>5. Generating the Art:<br></strong>That’s about it. Feed a textual prompt and some pure noise into the system, and watch as the combined might of CLIP, U-Net, and VAE create a high-definition image that matches the essence of the provided prompt.</p><h3>The Final Picture</h3><p>Here’s how it all comes together at inference time:</p><ul><li>Text Understanding with CLIP: Decipher the text prompt to provide a coherent blueprint for the U-Net.</li><li>Image Creation with U-Net: Guided by the text embedding from CLIP and initialized with noise, U-Net creates a smaller version of the image.</li><li>High-Definition Conversion with VAE decoder: U-Net’s output now gets converted into a high-definition image.</li></ul><p>So, to break it down: this is how the three components work together to generate amazing images from text. It’s like magic, but with algorithms.</p><p>If you enjoyed this article, consider following me for more. Your thoughts and ideas are important to me — to make sharing your feedback with me even easier, I’ve created a quick form which you can access <a href="https://tally.so/r/3XrZAY">here</a>. Your input is appreciated! Don’t hesitate to reach out — your engagement is what makes this community thrive.</p><p>Thanks for reading and happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08ce61845041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeing the Magic: Visualizing Neural Network Embeddings]]></title>
            <link>https://levelup.gitconnected.com/seeing-the-magic-visualizing-neural-network-embeddings-23c10b2642f2?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c10b2642f2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 03:13:52 GMT</pubDate>
            <atom:updated>2023-10-09T16:03:51.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>How about a sneak peek into the ‘brain’ of ML models?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCPTYI41pGt7qsY1Xi8y4g.png" /><figcaption>Source Unsplash</figcaption></figure><p>Sometimes, what ML models can do can really feel like magic, and it can be pretty hard to actually get a sense of how they learn from the data we feed them. But what if we could take a peek inside their “brain” to see how neural nets actually make sense of things? Well, that’s what this article is all about! By the end, you’ll be able to visualize what the network “understood” about the data it was fed.</p><p>While our project focuses on image embeddings, you can easily tweak this for a pre-trained NLP model. Let’s dive in!</p><h3>1. Setting Up the Environment</h3><p>Before we start, we need a few packages.</p><ul><li>torchvision: Gives us popular datasets and models for computer vision.</li><li>bokeh: Useful for creating interactive visualizations.</li><li>matplotlib: A must-have for general visualizations.</li></ul><pre>!pip install torchvision<br>!pip install bokeh<br>!pip install matplotlib</pre><h3>2. Importing the Essentials</h3><p>A bunch of libraries help us visualize, train, and analyze our data:</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import torch<br>import torchvision.models as models<br>import torchvision.transforms as transforms<br>from torchvision.datasets import CIFAR10<br>from torchvision.utils import make_grid<br>import torch.nn as nn<br>from sklearn.manifold import TSNE<br>from bokeh.plotting import figure, show, output_notebook<br>from bokeh.models import HoverTool, ColumnDataSource<br>from bokeh.palettes import d3</pre><h3>3. Prepping Our Model and Data</h3><p>We’re working with CIFAR10. Think tiny images of cars, cats, and more. We’ll also use ResNet18 as our pre-trained model (this model and dataset we use for fine-tuning works well for our task here, but you can pick any other model/data you like!):</p><pre># Let&#39;s make sure we use the GPU if its available<br>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>class_names = [&quot;airplane&quot;, &quot;automobile&quot;, &quot;bird&quot;, &quot;cat&quot;, &quot;deer&quot;, &quot;dog&quot;, &quot;frog&quot;, &quot;horse&quot;, &quot;ship&quot;, &quot;truck&quot;]<br># Load a pretrained ResNet18 model<br>model = models.resnet18(pretrained=True)<br># Modify the model&#39;s final layer to match CIFAR10&#39;s 10 classes<br>model.fc = nn.Linear(model.fc.in_features, 10)<br>model = model.to(device)</pre><p>Now, let’s load and preprocess our CIFAR10 dataset:</p><pre>transform = transforms.Compose(<br>    [transforms.ToTensor(),<br>     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])<br><br>full_trainset = CIFAR10(root=&#39;./data&#39;, train=True, download=True, transform=transform)<br><br># Choose a random subset of 10000 images - or you can use the whole thing if you like, its just a little slower<br>subset_indices = torch.randperm(len(full_trainset))[:10000]<br>trainset = torch.utils.data.Subset(full_trainset, subset_indices)<br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=100, shuffle=True)<br><br>testset = CIFAR10(root=&#39;./data&#39;, train=False, download=True, transform=transform)<br>testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False)</pre><p>Let’s take a sneak peek at our dataset to see whats in it:</p><pre># Display a few images from the dataset for visualization <br>def imshow(img):<br>    img = img / 2 + 0.5     # unnormalize<br>    npimg = img.numpy()<br>    plt.imshow(np.transpose(npimg, (1, 2, 0)))<br>    plt.show()<br>dataiter = iter(trainloader)<br>images, labels = dataiter.next()<br>imshow(make_grid(images[:4])) # Displaying 4 images<br>print(&#39; &#39;.join(&#39;%5s&#39; % full_trainset.classes[labels[j]] for j in range(4)))</pre><p>Not the best quality images in this dataset, but good enough for our goal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*rWE2uiednUy_EjJYtv5ZHA.png" /></figure><h3>4. Fine-Tuning the Model</h3><p>We’re now going to fine-tune our pre-trained model on CIFAR10:</p><pre># Define loss function and optimizer<br>criterion = nn.CrossEntropyLoss()<br>optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)<br><br># Let&#39;s train for 3 epochs<br>epochs = 3<br>for epoch in range(epochs):<br>    running_loss = 0.0<br>    for i, data in enumerate(trainloader, 0):<br>        inputs, labels = data[0].to(device), data[1].to(device)<br>        optimizer.zero_grad()<br>        outputs = model(inputs)<br>        loss = criterion(outputs, labels)<br>        loss.backward()<br>        optimizer.step()<br>        running_loss += loss.item()<br>    print(f&quot;Epoch {epoch+1}, Loss: {running_loss / len(trainloader)}&quot;)</pre><p>Let’s take a peak at the architecture to understand its layers and parameters:</p><pre># In jupyter/colab running this has the effect of showing the architecture<br>model</pre><p>Our pre-trained model represents data in 512 dimensions — which is crazy for us to even picture. For simplicity and visualization, we’ll later reduce this to just 2 dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDELGYIf2HTpIBWlAXcZyg.png" /></figure><h3>5. Extracting Image Embeddings</h3><p>Now, the fun stuff. Ever wondered how our model ‘sees’ an image? We’re about to find out by checking its internal image representations (aka embeddings).</p><pre>#Setting the final layer to identity to directly output the embeddings<br>model.fc = nn.Identity()<br># Extract embeddings from the test dataset<br>embeddings = []<br>labels = []<br># Let&#39;s set the model to evaluation mode<br>model.eval()<br>with torch.no_grad():<br>    for data in testloader:<br>        inputs, label = data[0].to(device), data[1]<br>        output = model(inputs)<br>        embeddings.append(output.cpu())<br>        labels.extend(label)<br>embeddings = torch.cat(embeddings).numpy()</pre><h3>6. Dimensionality Reduction with t-SNE</h3><p>“But these embeddings have so many dimensions!” yep, you’re right. To make them easy to visualize, we use t-SNE. Think of t-SNE as a wizard that takes a cloud of data and magically projects it onto a 2D map, while trying its best to keep similar data points together.</p><pre># Reduce dimensionality from 512 to 2<br>tsne = TSNE(n_components=2, random_state=42)<br>reduced_embeddings = tsne.fit_transform(embeddings)</pre><h3>7. The Fun Part: Visualizing with Bokeh!</h3><p>We’ll use Bokeh to make an interactive plot to visualize the embeddings. beautiful. Hover over the points, and voilà, you’ll see the actual images they represent!</p><pre>output_notebook()<br><br># Define colors for each of our 10 classes class<br>n_categories = 10<br>colors = d3[&#39;Category10&#39;][n_categories]<br>colormap = {i: colors[i] for i in range(n_categories)}<br># Create a Bokeh plot with hover-over image display<br>source = ColumnDataSource(data=dict(<br>    x=reduced_embeddings[:, 0],<br>    y=reduced_embeddings[:, 1],<br>    desc=[int(l) for l in labels],<br>    imgs=base64_images,<br>    colors=[colormap[int(l)] for l in labels]<br>))<br><br>hover = HoverTool(tooltips=&quot;&quot;&quot;<br>    &lt;div&gt;<br>        &lt;div&gt;<br>            &lt;img<br>                src=&quot;data:image/png;base64,@imgs&quot; height=&quot;42&quot; alt=&quot;@imgs&quot; width=&quot;42&quot;<br>                style=&quot;float: left; margin: 0px 15px 15px 0px;&quot;<br>                border=&quot;2&quot;<br>            &gt;&lt;/img&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;span style=&quot;font-size: 17px; font-weight: bold;&quot;&gt;@desc&lt;/span&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&quot;&quot;&quot;)<br>p = figure(width=800, height=800, tools=[hover], title=&quot;Embeddings Visualized with t-SNE&quot;)<br>p.circle(&#39;x&#39;, &#39;y&#39;, size=6, source=source, color=&#39;colors&#39;, legend_field=&#39;desc&#39;)<br>show(p, notebook_handle=True)</pre><p>Now, take a look at the result. Notice how similar items cluster? Give it a try and hover around to explore the images in your own notebook — you should now see a visualization of how the neural network “sees” the CIFAR10 images!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gP4fCscrVzlPTVdvAt2TA.png" /></figure><p>In this article, we’ve fine-tuned a pre-trained model. However, if your primary goal is to visualize the embeddings, there’s a more streamlined approach. Instead of fine-tuning, you can directly load the pre-trained model, extract its embeddings, and then visualize them using tools like Bokeh or matplotlib.</p><p>We’ve taken a closer look inside neural networks, turning abstract data into clear visualizations. With the right tools and approach, understanding ML models becomes more accessible. Keep exploring and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c10b2642f2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/seeing-the-magic-visualizing-neural-network-embeddings-23c10b2642f2">Seeing the Magic: Visualizing Neural Network Embeddings</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding backprop]]></title>
            <link>https://levelup.gitconnected.com/understanding-backprop-30f3421fbb6?source=rss-f39ff33c76d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f3421fbb6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alessandro Amenta]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 01:17:12 GMT</pubDate>
            <atom:updated>2023-10-02T06:48:46.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ever wondered what really happens when you call .backward in PyTorch?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v9na8LAEHGc9f-7T.jpg" /><figcaption>source Google DeepMind</figcaption></figure><p>Over the last few months, I’ve been learning more and more about deep learning. The more I learn, practice, build, and tweak models, the more I realize not only the power of neural nets but how elegant they are as a machine learning algorithm. They can pretty much approximate any function, given sufficient data and complexity, thanks to the Universal Approximation Theorem.</p><p>What’s more is that I’ve noticed that the more you use frameworks like PyTorch to build or fine-tune models, the more you realize that while these are incredibly useful, they also abstract away so much of the stuff that ends up being done under the hood. Even though these frameworks are great to do things efficiently, I do think there’s a lot of value in going back to the basics and really understanding how the core pieces work, especially if you plan on developing lots of models or just troubleshooting effectively.</p><p>In PyTorch, we just call .backward on the loss function. But here I want to talk about what it actually is and how it works.</p><h3>What’s Backprop?</h3><p>Backpropagation, or backprop for short, is a method used in training artificial neural networks. It’s like the brain of the network, helping it to learn from the errors it makes and improve its performance over time. It’s a form of supervised learning where the network learns by adjusting its weights based on the error of its predictions.</p><h3>Breaking Down the Math</h3><p>To understand backpropagation, we need to understand a few key concepts: the loss function, gradient descent, and chain rule. Don’t worry, I’ll keep it simple and straightforward!</p><h4>Loss Function</h4><p>The loss function quantifies how far off our predictions are from the actual targets. It’s like a measure of the network’s “mistake”. The goal is to minimize this mistake during training.</p><h4>Gradient Descent</h4><p>Gradient descent is an optimization algorithm used to minimize the error by adjusting all the weights in the network. It’s like a guide, pointing in the direction we should go to reduce the error. Specifically, the gradient points in the direction of the steepest increase of the loss function, and that’s why we update the weights in the opposite direction to minimize the loss.</p><h4>Chain Rule</h4><p>Think of the chain rule as a handy tool from calculus that helps us figure out how changing one thing (like the weights in our network) affects another thing (like our loss). It’s essentially the backbone of backpropagation, the process that helps our network learn and improve.</p><p>In simpler terms, the chain rule helps us answer the question, “If we tweak the weights a little, how does it change our loss?” It does this by letting us multiply a series of ‘change rates’ or derivatives together.</p><p>For example, if we have a function that is a combination of other functions, say <em>f</em>(<em>g</em>(<em>h</em>(<em>x</em>))), and we want to know how a small change in <em>x</em> affects <em>f</em>, we would multiply together three things: how <em>f</em> changes with <em>g</em>(<em>h</em>(<em>x</em>)), how <em>g</em> changes with <em>h</em>(<em>x</em>), and how <em>h</em> changes with <em>x</em>. This way, we can see the ripple effect of a small change in <em>x</em> all the way through to <em>f</em>!</p><h3>The Process of Backpropagation</h3><ol><li>Forward Pass:</li></ol><ul><li>The input is passed through the network.</li><li>Each neuron applies a weighted sum of its input, adds a bias and then passes it through an activation function.</li><li>The final output is compared to the target using the loss function.</li></ul><p>2. Compute the Gradient:</p><ul><li>The gradient of the loss function with respect to each weight is computed. It represents the slope of the loss function at the current point, i.e., how much the loss would increase or decrease if the weight were adjusted.</li></ul><p>3. Update the Weights:</p><ul><li>The weights are then adjusted in the opposite direction to the gradient. This is done to minimize the loss.</li></ul><h3>The Math Behind Backpropagation</h3><p>Let’s break down the math in a simple way. Suppose we have a simple network with one hidden layer and one output layer. Let’s denote:</p><pre>x: Input<br>W1: Weights of the hidden layer<br>b1: Bias of the hidden layer<br>a1: Activation of the hidden layer<br>W2: Weights of the output layer<br>b2: Bias of the output layer<br>a2: Output of the network<br>L: Loss</pre><p>The forward pass:</p><pre>a1 = σ(W1x + b1)<br>a2 = σ(W2a1 + b2)<br>L = Loss(a2, target)</pre><p>Here, σ represents the activation function, and the Loss function compares the output a2 to the target.</p><p>Backpropagation:</p><p>We compute the gradient of the loss with respect to each parameter using the chain rule. Think of the chain rule as a set of dominoes — each one affects the next. It lets us see how tweaking one variable, like our parameters, impacts another, like the loss function, which we’re aiming to minimize. In simpler terms, the chain rule, coupled with backpropagation, guides us on how much to adjust each weight to get our predictions closer to the real deal. So, the gradient of the loss L with respect to a weight W1 can be computed as:</p><pre>∂L/∂W1 = ∂L/∂a2 * ∂a2/∂a1 * ∂a1/∂W1</pre><p>Once we have the gradients, we can update the weights and biases in the direction that minimizes the loss. This is typically done using a learning rate η, which determines the size of the step we take in the direction of the gradient:</p><pre>W1 = W1 - η * ∂L/∂W1</pre><h3>Conclusion</h3><p>Backpropagation is a simple yet powerful algorithm that enables neural networks to learn from their mistakes. It’s the mechanism by which the network adjusts its weights to minimize the error between its predictions and the actual targets. Understanding the basics and the math behind backpropagation not only demystifies what happens under the hood of deep learning frameworks but also provides insights into the learning process of the network.</p><p>By diving deep into the core components like backpropagation, we can appreciate the elegance and power of neural networks and gain a better understanding of the intricate dance of weights and biases that enable them to learn and make predictions. So next time you call .backward in PyTorch, you’ll have a clearer picture of the elegant process unfolding behind the scenes! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f3421fbb6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-backprop-30f3421fbb6">Understanding backprop</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>