<?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 Felix Lu on Medium]]></title>
        <description><![CDATA[Stories by Felix Lu on Medium]]></description>
        <link>https://medium.com/@felix.lu07?source=rss-be32f7fe99f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DO5yQdoVmBFM8dTF.jpg</url>
            <title>Stories by Felix Lu on Medium</title>
            <link>https://medium.com/@felix.lu07?source=rss-be32f7fe99f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:05:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@felix.lu07/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[What is Memory Semaphore?]]></title>
            <link>https://medium.com/@felix.lu07/what-is-memory-semaphore-5db5ce7d9912?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5db5ce7d9912</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[types-of-computer-memory]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Thu, 29 May 2025 07:41:54 GMT</pubDate>
            <atom:updated>2025-05-29T07:41:54.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory Semaphore Protection</h3><p>Imagine you have a library with a single copy of a very popular book. Many people want to read this book, but since there’s only one copy, only one person can read it at a time. To manage this, the librarian uses a system of tokens.</p><h4>The Analogy:</h4><ol><li>The Book (Shared Resource): This is like a piece of memory or a resource in a computer that multiple programs (or threads) want to use.</li><li>The Librarian (Operating System): The librarian controls access to the book, just like the operating system controls access to memory.</li><li>Tokens (Semaphores): The librarian gives out a token to a person who wants to read the book. If the book is already being read, the person has to wait until the book is returned and a token is available. This token system ensures that only one person can read the book at a time.</li><li>Readers (Threads/Processes): These are the programs or threads that want to access the shared memory.</li></ol><h4>How It Works:</h4><ul><li>Requesting Access: When a person (thread) wants to read the book (access memory), they ask the librarian (operating system) for a token (semaphore).</li><li>Granting Access: If the book is available (memory is free), the librarian gives the person a token, allowing them to read the book.</li><li>Releasing Access: Once the person is done reading, they return the token to the librarian, making the book available for the next person.</li></ul><h3>Key Points:</h3><ul><li>Mutual Exclusion: Only one person can read the book at a time, ensuring that the book (memory) is not corrupted by simultaneous access.</li><li>Synchronization: The librarian (operating system) synchronizes access to the book (memory) using tokens (semaphores).</li></ul><h3>In Computer Terms:</h3><ul><li>Semaphore: A semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent system such as a multitasking operating system.</li><li>Memory Protection: This ensures that multiple threads or processes do not interfere with each other when accessing shared memory, preventing data corruption and ensuring data consistency.</li></ul><p>By using semaphores, the operating system can effectively manage access to shared resources, ensuring that only one process can use a particular piece of memory at a time, much like the librarian ensures that only one person can read the book at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5db5ce7d9912" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Resource Summary via CLI]]></title>
            <link>https://medium.com/@felix.lu07/aws-resource-summary-via-cli-fc1dcecf5563?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc1dcecf5563</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-certification]]></category>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 07:03:33 GMT</pubDate>
            <atom:updated>2024-09-17T07:05:07.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Utz1LTpZyORCauUc" /><figcaption>Photo by <a href="https://unsplash.com/@rthiemann?utm_source=medium&amp;utm_medium=referral">Robert Thiemann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>How to Clean Up Unused AWS Resources with PowerShell</h3><p>Managing AWS resources can be a daunting task, especially when you have numerous services running simultaneously. Over time, unused or dormant resources can accumulate, leading to unnecessary costs and clutter. In this article, I’ll share a PowerShell script that I developed to help identify and clean up these unused resources. This script has significantly streamlined our AWS account, and I hope it can do the same for you.</p><h3>Why Clean Up AWS Resources?</h3><p>Unused AWS resources can lead to:</p><ul><li>Increased Costs: Even if resources are not actively used, they can still incur charges.</li><li>Cluttered Environment: A cluttered AWS environment can make it difficult to manage and monitor active resources.</li><li>Security Risks: Dormant resources can become potential security vulnerabilities if not properly managed.</li></ul><h3>The Solution: PowerShell Script</h3><p>To address these issues, I wrote a PowerShell script that generates a comprehensive overview of all AWS resources. This script outputs a text file listing all the items created across various AWS services, allowing you to review and clear off unwanted or unused resources.</p><h3>Inline Policy</h3><p>Before running the script, ensure you have the necessary permissions. Below is an example of an inline policy that grants the required permissions:</p><pre>{<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;iam:ListUsers&quot;,<br>    &quot;iam:ListRoles&quot;,<br>    &quot;iam:ListPolicies&quot;,<br>    &quot;elasticloadbalancing:DescribeLoadBalancers&quot;,<br>    &quot;elasticache:DescribeCacheClusters&quot;,<br>    &quot;elasticache:DescribeReplicationGroups&quot;,<br>    &quot;elasticache:DescribeSnapshots&quot;,<br>    &quot;dynamodb:ListTables&quot;,<br>    &quot;dynamodb:DescribeTable&quot;,<br>    &quot;cloudwatch:DescribeAlarms&quot;,<br>    &quot;logs:DescribeLogGroups&quot;,<br>    &quot;ecr:DescribeRepositories&quot;,<br>    &quot;cloudfront:ListDistributions&quot;,<br>    &quot;sns:ListTopics&quot;,<br>    &quot;route53:ListHostedZones&quot;,<br>    &quot;globalaccelerator:ListAccelerators&quot;,<br>    &quot;ecs:ListClusters&quot;,<br>    &quot;ecs:DescribeClusters&quot;,<br>    &quot;ecs:ListTaskDefinitions&quot;,<br>    &quot;ecs:DescribeTaskDefinition&quot;<br>   ],<br>   &quot;Resource&quot;: &quot;*&quot;<br>  }<br> ]<br>}</pre><h3>PowerShell Script</h3><p>The PowerShell script is designed to query various AWS services and compile a list of resources. The output is saved to a text file, providing a clear overview of your AWS environment.</p><pre># Function to run AWS CLI commands and return the output<br>function Run-AWSCommand {<br>    param (<br>        [string]$command,<br>        [string]$subcommand,<br>        [string]$arguments = &quot;&quot;<br>    )<br>    $fullCommand = &quot;aws $command $subcommand $arguments&quot;<br>    $output = Invoke-Expression $fullCommand<br>    return $output | ConvertFrom-Json<br>}<br><br># Function to write output to file with proper indentation<br>function Write-OutputToFile {<br>    param (<br>        [string]$filePath,<br>        [string]$content,<br>        [int]$indentLevel = 0<br>    )<br>    $indent = &quot;    &quot; * $indentLevel<br>    Add-Content -Path $filePath -Value &quot;$indent$content&quot;<br>}<br><br>$outputFile = &quot;aws_resource_inventory.txt&quot;<br># Clear the file if it already exists<br>if (Test-Path $outputFile) {<br>    Clear-Content $outputFile<br>}<br><br># IAM Users<br>Write-OutputToFile $outputFile &quot;IAM Users:&quot;<br>$users = Run-AWSCommand &quot;iam&quot; &quot;list-users&quot;<br>foreach ($user in $users.Users) {<br>    Write-OutputToFile $outputFile &quot;User: $($user.UserName), Created: $($user.CreateDate)&quot; 1<br>}<br><br># IAM Roles<br>Write-OutputToFile $outputFile &quot;`nIAM Roles:&quot;<br>$roles = Run-AWSCommand &quot;iam&quot; &quot;list-roles&quot;<br>foreach ($role in $roles.Roles) {<br>    Write-OutputToFile $outputFile &quot;Role: $($role.RoleName), Created: $($role.CreateDate)&quot; 1<br>}<br><br># IAM Policies<br>Write-OutputToFile $outputFile &quot;`nIAM Policies:&quot;<br>$policies = Run-AWSCommand &quot;iam&quot; &quot;list-policies&quot; &quot;--scope Local&quot;<br>foreach ($policy in $policies.Policies) {<br>    Write-OutputToFile $outputFile &quot;Policy: $($policy.PolicyName), Created: $($policy.CreateDate)&quot; 1<br>}<br><br># Elastic Load Balancers<br>Write-OutputToFile $outputFile &quot;`nElastic Load Balancers:&quot;<br>$elbs = Run-AWSCommand &quot;elbv2&quot; &quot;describe-load-balancers&quot;<br>foreach ($elb in $elbs.LoadBalancers) {<br>    Write-OutputToFile $outputFile &quot;ELB: $($elb.LoadBalancerName), Created: $($elb.CreatedTime)&quot; 1<br>}<br><br># ElastiCache Clusters<br>Write-OutputToFile $outputFile &quot;`nElastiCache Clusters:&quot;<br>$cacheClusters = Run-AWSCommand &quot;elasticache&quot; &quot;describe-cache-clusters&quot;<br>foreach ($cluster in $cacheClusters.CacheClusters) {<br>    Write-OutputToFile $outputFile &quot;Cluster: $($cluster.CacheClusterId), Created: $($cluster.CacheClusterCreateTime)&quot; 1<br>}<br><br># ElastiCache Replication Groups<br>Write-OutputToFile $outputFile &quot;`nElastiCache Replication Groups:&quot;<br>$replicationGroups = Run-AWSCommand &quot;elasticache&quot; &quot;describe-replication-groups&quot;<br>foreach ($group in $replicationGroups.ReplicationGroups) {<br>    Write-OutputToFile $outputFile &quot;Replication Group: $($group.ReplicationGroupId), Created: $($group.MemberClusters[0].CacheClusterCreateTime)&quot; 1<br>}<br><br># ElastiCache Snapshots<br>Write-OutputToFile $outputFile &quot;`nElastiCache Snapshots:&quot;<br>$snapshots = Run-AWSCommand &quot;elasticache&quot; &quot;describe-snapshots&quot;<br>foreach ($snapshot in $snapshots.Snapshots) {<br>    Write-OutputToFile $outputFile &quot;Snapshot: $($snapshot.SnapshotName), Created: $($snapshot.SnapshotCreateTime)&quot; 1<br>}<br><br># Global Accelerators<br>Write-OutputToFile $outputFile &quot;`nGlobal Accelerators:&quot;<br>$accelerators = Run-AWSCommand &quot;globalaccelerator&quot; &quot;list-accelerators&quot;<br>foreach ($accelerator in $accelerators.Accelerators) {<br>    Write-OutputToFile $outputFile &quot;Accelerator: $($accelerator.Name), Created: $($accelerator.CreatedTime)&quot; 1<br>}<br><br># DynamoDB Tables<br>Write-OutputToFile $outputFile &quot;`nDynamoDB Tables:&quot;<br>$tables = Run-AWSCommand &quot;dynamodb&quot; &quot;list-tables&quot;<br>foreach ($table in $tables.TableNames) {<br>    $tableDetails = Run-AWSCommand &quot;dynamodb&quot; &quot;describe-table&quot; &quot;--table-name $table&quot;<br>    Write-OutputToFile $outputFile &quot;Table: $($tableDetails.Table.TableName), Created: $($tableDetails.Table.CreationDateTime)&quot; 1<br>}<br><br># CloudWatch Alarms<br>Write-OutputToFile $outputFile &quot;`nCloudWatch Alarms:&quot;<br>$alarms = Run-AWSCommand &quot;cloudwatch&quot; &quot;describe-alarms&quot;<br>foreach ($alarm in $alarms.MetricAlarms) {<br>    Write-OutputToFile $outputFile &quot;Alarm: $($alarm.AlarmName), Created: $($alarm.AlarmConfigurationUpdatedTimestamp)&quot; 1<br>}<br><br># CloudWatch Log Groups<br>Write-OutputToFile $outputFile &quot;`nCloudWatch Log Groups:&quot;<br>$logGroups = Run-AWSCommand &quot;logs&quot; &quot;describe-log-groups&quot;<br>foreach ($logGroup in $logGroups.logGroups) {<br>    Write-OutputToFile $outputFile &quot;Log Group: $($logGroup.logGroupName), Created: $($logGroup.creationTime)&quot; 1<br>}<br><br># ECR Repositories<br>Write-OutputToFile $outputFile &quot;`nECR Repositories:&quot;<br>$repositories = Run-AWSCommand &quot;ecr&quot; &quot;describe-repositories&quot;<br>foreach ($repository in $repositories.repositories) {<br>    Write-OutputToFile $outputFile &quot;Repository: $($repository.repositoryName), Created: $($repository.createdAt)&quot; 1<br>}<br><br># CloudFront Distributions<br>Write-OutputToFile $outputFile &quot;`nCloudFront Distributions:&quot;<br>$distributions = Run-AWSCommand &quot;cloudfront&quot; &quot;list-distributions&quot;<br>foreach ($distribution in $distributions.DistributionList.Items) {<br>    Write-OutputToFile $outputFile &quot;Distribution: $($distribution.Id), Created: $($distribution.LastModifiedTime)&quot; 1<br>}<br><br># SNS Topics<br>Write-OutputToFile $outputFile &quot;`nSNS Topics:&quot;<br>$topics = Run-AWSCommand &quot;sns&quot; &quot;list-topics&quot;<br>foreach ($topic in $topics.Topics) {<br>    Write-OutputToFile $outputFile &quot;Topic: $($topic.TopicArn)&quot; 1<br>}<br><br># Route53 Hosted Zones<br>Write-OutputToFile $outputFile &quot;`nRoute53 Hosted Zones:&quot;<br>$hostedZones = Run-AWSCommand &quot;route53&quot; &quot;list-hosted-zones&quot;<br>foreach ($zone in $hostedZones.HostedZones) {<br>    Write-OutputToFile $outputFile &quot;Hosted Zone: $($zone.Name), Created: $($zone.Config.PrivateZone)&quot; 1<br>}<br><br># ECS Clusters<br>Write-OutputToFile $outputFile &quot;`nECS Clusters:&quot;<br>$clusters = Run-AWSCommand &quot;ecs&quot; &quot;list-clusters&quot;<br>foreach ($clusterArn in $clusters.clusterArns) {<br>    $cluster = Run-AWSCommand &quot;ecs&quot; &quot;describe-clusters&quot; &quot;--clusters $clusterArn&quot;<br>    Write-OutputToFile $outputFile &quot;Cluster: $($cluster.clusters[0].clusterName), Created: $($cluster.clusters[0].registeredContainerInstancesCount)&quot; 1<br>}<br><br># ECS Task Definitions<br>Write-OutputToFile $outputFile &quot;`nECS Task Definitions:&quot;<br>$activeTaskDefs = Run-AWSCommand &quot;ecs&quot; &quot;list-task-definitions&quot; &quot;--status ACTIVE&quot;<br>Write-OutputToFile $outputFile &quot;Active Task Definitions:&quot; 1<br>foreach ($taskDef in $activeTaskDefs.taskDefinitionArns) {<br>    Write-OutputToFile $outputFile $taskDef 2<br>}<br>$inactiveTaskDefs = Run-AWSCommand &quot;ecs&quot; &quot;list-task-definitions&quot; &quot;--status INACTIVE&quot;<br>Write-OutputToFile $outputFile &quot;Inactive Task Definitions:&quot; 1<br>foreach ($taskDef in $inactiveTaskDefs.taskDefinitionArns) {<br>    Write-OutputToFile $outputFile $taskDef 2<br>}<br><br>Write-Output &quot;AWS resource inventory has been saved to $outputFile&quot;</pre><h3>Benefits of Using This Script</h3><ul><li>Comprehensive Overview: The script provides a detailed list of resources across multiple AWS services.</li><li>Easy Identification: Quickly identify unused or dormant resources.</li><li>Cost Savings: By removing unused resources, you can reduce your AWS costs.</li><li>Improved Management: A cleaner AWS environment is easier to manage and monitor.</li></ul><h3>Conclusion</h3><p>Cleaning up unused AWS resources is crucial for maintaining an efficient and cost-effective cloud environment. This PowerShell script has helped me significantly reduce clutter and costs in our AWS account. I hope it proves useful for you as well. Feel free to modify the script to suit your specific needs and share your experiences in the comments below.</p><p>Happy cleaning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc1dcecf5563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recently, I encountered an issue where my Windows computer was waking up unexpectedly.]]></title>
            <link>https://medium.com/@felix.lu07/recently-i-encountered-an-issue-where-my-windows-computer-was-waking-up-unexpectedly-b01956960ed3?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b01956960ed3</guid>
            <category><![CDATA[windows-cmd]]></category>
            <category><![CDATA[windows-11]]></category>
            <category><![CDATA[usb-device]]></category>
            <category><![CDATA[power-management]]></category>
            <category><![CDATA[power-window]]></category>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 14:44:40 GMT</pubDate>
            <atom:updated>2024-08-18T14:45:08.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Prevent Specific USB Devices from Waking Your Windows Computer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*QfcuBxQClgy-3J1hGUG73g.jpeg" /></figure><p>Recently, I encountered an issue where my Windows computer was waking up unexpectedly. After some investigation, I discovered that a specific USB device was causing the problem. Here’s a step-by-step guide on how I identified and resolved the issue, ensuring only my keyboard can wake the computer.</p><h3>Identifying the Culprit</h3><p>First, I needed to find out which device was waking my computer. I used the powercfg command in the Command Prompt:</p><pre>powercfg -lastwake</pre><p>This command revealed the following:</p><pre>Wake History Count - 1<br>Wake History [0]<br>  Wake Source Count - 1<br>  Wake Source [0]<br>    Type: Device<br>    Instance Path: USB\VID_1B1C&amp;PID_1B5E\5FDD4DA418561486<br>    Friendly Name:<br>    Description: USB Composite Device<br>    Manufacturer: (Standard USB Host Controller)</pre><p>The output indicated that a USB Composite Device was responsible for waking my computer.</p><h3>Listing Wake-Capable Devices</h3><p>Next, I listed all devices capable of waking the computer:</p><pre>powercfg -devicequery wake_armed</pre><p>The output was:</p><pre>HID-compliant mouse (001)<br>HID Keyboard Device<br>HID-compliant mouse (002)<br>Realtek Gaming GbE Family Controller</pre><h3>Disabling Wake for Specific Devices</h3><p>To ensure only my keyboard could wake the computer, I needed to disable wake functionality for all other devices. Here are the exact commands I used:</p><ol><li>Disable Wake for All Devices:</li></ol><ul><li>powercfg -devicedisablewake &quot;HID-compliant mouse (001)&quot;</li><li>powercfg -devicedisablewake &quot;HID-compliant mouse (002)&quot;</li><li>powercfg -devicedisablewake &quot;Realtek Gaming GbE Family Controller&quot;</li></ul><ol><li>Enable Wake for the Keyboard:</li></ol><ul><li>powercfg -deviceenablewake &quot;HID Keyboard Device&quot;</li></ul><h3>Conclusion</h3><p>By following these steps, I successfully prevented unwanted USB devices from waking my computer. Now, only my keyboard can wake it up, providing a more controlled and predictable behavior.</p><p>If you’re experiencing similar issues, I hope this guide helps you resolve them. Feel free to share your experiences or ask questions in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b01956960ed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Use Cases of a Python Script for Image Data Extraction with OpenAI’s GPT-4 Vision…]]></title>
            <link>https://medium.com/@felix.lu07/understanding-and-use-cases-of-a-python-script-for-image-data-extraction-with-openais-gpt-4-vision-f0b5393200e3?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b5393200e3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 11:08:00 GMT</pubDate>
            <atom:updated>2023-11-21T11:11:28.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dMHXfLJSMpFzoZTaUH7LQ.png" /><figcaption>The image is irrelevant. I just added it for fun :)</figcaption></figure><h3>Understanding and Use Cases of a Python Script for Image Data Extraction with OpenAI’s GPT-4 Vision API</h3><p>The pre-requisites are that you should already have an OpenAI API key of course.</p><p>The Python script provided above is a sophisticated example of how to integrate OpenAI’s GPT-4 Vision API into an application to extract textual information from images. This script is designed to encode an image to a base64 data URI, construct a payload for the API request, and handle the communication with the OpenAI API to retrieve and process the response. Let’s break down the script and explore some potential use cases.</p><h3>Script Breakdown</h3><h3>Image Encoding to Base64</h3><p>The function encode_image_to_data_uri takes an image file path as input and reads the image in binary mode. It then encodes the binary data to base64, which is a text-based representation of the image data. This base64 string is concatenated with a prefix that indicates the MIME type (in this case, image/jpeg) to form a data URI. Data URIs are useful for embedding images directly into documents without the need for an external file.</p><h3>Payload Construction</h3><p>The construct_payload function prepares the data needed to make an API request to OpenAI&#39;s GPT-4 Vision API. It includes the API key for authorization, the content type for the request, and the messages that contain the user&#39;s instructions and the image data URI. The payload is structured to tell the model to extract field names from the image and list them in a table format.</p><h3>Sending the Message</h3><p>The send_message function is responsible for making the actual HTTP POST request to the OpenAI API endpoint. It uses the requests library to send the constructed payload and headers. If the request is successful, it returns the JSON response; otherwise, it handles any HTTP or other exceptions that may occur.</p><h3>Main Function</h3><p>The main function serves as the entry point for the script. It calls the other functions in sequence: encoding the image, constructing the payload, sending the message, and then printing the response.</p><pre>import base64<br>import requests<br><br># Function to encode the image to base64<br>def encode_image_to_data_uri(image_path):<br>    with open(image_path, &quot;rb&quot;) as img_file:<br>        base64_image = base64.b64encode(img_file.read()).decode(&quot;utf-8&quot;)<br>        return f&quot;data:image/jpeg;base64,{base64_image}&quot;<br><br># Function to construct the payload<br>def construct_payload(api_key, image_data_uri):<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {api_key}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }<br>    <br>    prompt_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;: &quot;I want to extract out all the field names that are found in the picture and list them out in table form.&quot;<br>                },<br>                {<br>                    &quot;type&quot;: &quot;image_url&quot;,<br>                    &quot;image_url&quot;: image_data_uri<br>                }<br>            ],<br>        },<br>    ]<br><br>    params = {<br>        &quot;model&quot;: &quot;gpt-4-vision-preview&quot;,<br>        &quot;messages&quot;: prompt_messages,<br>        &quot;max_tokens&quot;: 500,<br>    }<br>    <br>    return params, headers<br><br># Function to send the message<br>def send_message(payload, headers):<br>    try:<br>        response = requests.post(&quot;https://api.openai.com/v1/chat/completions&quot;, headers=headers, json=payload)<br>        response.raise_for_status()<br>        return response.json()<br>    except requests.exceptions.HTTPError as http_err:<br>        print(f&quot;HTTP error occurred: {http_err}&quot;)<br>    except Exception as err:<br>        print(f&quot;An error occurred: {err}&quot;)<br><br># Main function to run the script<br>def main():<br>    # Placeholder for your API key<br>    api_key = &quot;YOUR_OPENAI_API_HERE&quot;<br>    <br>    # Image path<br>    image_path = r&quot;ENTER_THE_PATH_TO_YOUR_FILE_HERE&quot;<br>    <br>    # Encode image to data URI<br>    image_data_uri = encode_image_to_data_uri(image_path)<br>    <br>    # Construct the payload<br>    payload, headers = construct_payload(api_key, image_data_uri)<br>    <br>    # Send the message and get the response<br>    response = send_message(payload, headers)<br>    <br>    # Output the &quot;choices&quot; part of the response to the console<br>    if response and &quot;choices&quot; in response:<br>        for choice in response[&quot;choices&quot;]:<br>            print(choice)<br>    else:<br>        print(&quot;No choices in the response or an error occurred.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Use Cases</h3><p>The script can be applied in various scenarios where automated image data extraction is beneficial:</p><h3>Document Digitization</h3><p>For businesses that deal with a large volume of paper-based documents, such as invoices, receipts, or forms, this script can be used to digitize and extract relevant information. This can significantly reduce manual data entry and improve efficiency.</p><h3>Accessibility</h3><p>The script can assist in creating more accessible content by converting images that contain text into actual text that screen readers can interpret for visually impaired users.</p><h3>Content Management</h3><p>In content management systems, this script can be used to automatically tag and categorize images based on the text they contain, improving searchability and organization.</p><h3>Data Analysis</h3><p>Researchers and analysts can use this script to extract data from charts, graphs, or tables in images, which can then be used for further analysis or visualization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b5393200e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Python Script as an Executable in Windows 11]]></title>
            <link>https://medium.com/@felix.lu07/making-a-python-script-as-an-executable-in-windows-11-b5e9eb7227c4?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e9eb7227c4</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 07:37:00 GMT</pubDate>
            <atom:updated>2023-11-13T07:37:00.301Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you have a Python script that you regularly use, and you want it to be accessed at your convenience without having to search through your folders and all. Now you can, by simply converting your python script into a “Windows” executable, that you can run at your convenience from your start bar or Task Bar.</p><p><strong>Create a Shortcut for the Python Script</strong></p><ul><li>Navigate to the folder where your python file is located. For the sake of this example, we shall use run.pyas a sample file name.</li><li>Right-click on run.py and select Send to &gt; Desktop (create shortcut) to create a shortcut on the desktop.</li></ul><p><strong>Convert the Shortcut to an Executable</strong></p><ul><li>Right-click on the new shortcut on the desktop and select Properties.</li><li>In the Shortcut tab, in the Target field, you need to prepend the Python executable path to your script path. It should look something like this:</li></ul><pre>&quot;C:\Path\To\Python\python.exe&quot; &quot;C:\Path\To\Your\Script\run.py&quot;</pre><p>This is basically to tell Windows that you want to use the Python executable, to directly run the script. If you are using a Virtual Environment, then whatever you have to enter into the Targetfield becomes slightly different. This is because you would have to access the Python executable from the venv folder instead, if not you will run into some dependencies issue.</p><pre>&quot;C:\Path\To\YourProject\venv\Scripts\python.exe&quot; &quot;C:\Path\To\Your\Script\run.py&quot;</pre><p>Click OK to save the changes.</p><p><strong>Pin the Shortcut to the Taskbar</strong></p><ul><li>Right-click on the shortcut and select Show more options (or press Shift + F10), then choose Pin to taskbar.</li></ul><figure><img alt="Your script would then effectively be pinned to the taskbar as such, and you can access/run it simply by clicking on it." src="https://cdn-images-1.medium.com/max/228/1*CaukP3ixKI7bbWTb-P_d4Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e9eb7227c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run text embeddings on a PDF and upload to Pinecone Vector Database]]></title>
            <link>https://medium.com/@felix.lu07/how-to-run-text-embeddings-on-a-pdf-and-upload-to-pinecone-vector-database-0c74af2288c8?source=rss-be32f7fe99f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c74af2288c8</guid>
            <dc:creator><![CDATA[Felix Lu]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 06:56:51 GMT</pubDate>
            <atom:updated>2023-10-03T06:56:51.008Z</atom:updated>
            <content:encoded><![CDATA[<pre>import os<br>import re<br>import pdfplumber<br>import openai<br>import pinecone<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br># Initialize OpenAI<br>openai.api_key = OPENAI-KEY<br>MODEL = &quot;text-embedding-ada-002&quot;<br><br># Initialize Pinecone<br>pinecone.init(api_key=PINECONE_API, environment=&#39;gcp-starter&#39;)<br><br># Define the index name<br>index_name = &quot;hs-codes&quot;<br><br># Create the index if it doesn&#39;t exist<br>if index_name not in pinecone.list_indexes():<br>    pinecone.create_index(index_name, dimension=1536)<br><br># Instantiate the index<br>index = pinecone.Index(index_name)<br><br># Define a function to preprocess text<br>def preprocess_text(text):<br>    # Replace consecutive spaces, newlines and tabs<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text)<br>    return text<br><br>def process_pdf(file_path):<br>    # create a loader<br>    loader = PyPDFLoader(file_path)<br>    # load your data<br>    data = loader.load()<br>    # Split your data up into smaller documents with Chunks<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>    documents = text_splitter.split_documents(data)<br>    # Convert Document objects into strings<br>    texts = [str(doc) for doc in documents]<br>    return texts<br><br># Define a function to create embeddings<br>def create_embeddings(texts):<br>    embeddings_list = []<br>    for text in texts:<br>        res = openai.Embedding.create(input=[text], engine=MODEL)<br>        embeddings_list.append(res[&#39;data&#39;][0][&#39;embedding&#39;])<br>    return embeddings_list<br><br># Define a function to upsert embeddings to Pinecone<br>def upsert_embeddings_to_pinecone(index, embeddings, ids):<br>    index.upsert(vectors=[(id, embedding) for id, embedding in zip(ids, embeddings)])<br><br># Process a PDF and create embeddings<br>file_path = &quot;your_pdf_here.pdf&quot;  # Replace with your actual file path<br>texts = process_pdf(file_path)<br>embeddings = create_embeddings(texts)<br><br># Upsert the embeddings to Pinecone<br>upsert_embeddings_to_pinecone(index, embeddings, [file_path])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c74af2288c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>