<?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 Assel Kashkenbayeva, PhD on Medium]]></title>
        <description><![CDATA[Stories by Assel Kashkenbayeva, PhD on Medium]]></description>
        <link>https://medium.com/@assel.kash?source=rss-60daae96d369------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ARCKHE4u98ZdLld3cgFnPw.jpeg</url>
            <title>Stories by Assel Kashkenbayeva, PhD on Medium</title>
            <link>https://medium.com/@assel.kash?source=rss-60daae96d369------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:14:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@assel.kash/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[Sovereign From What?]]></title>
            <link>https://medium.com/@assel.kash/sovereign-from-what-6491cc8de55b?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/6491cc8de55b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sovereignty]]></category>
            <category><![CDATA[open-weight-model]]></category>
            <category><![CDATA[enterprise]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-09-30T07:01:02.919Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>An enterprise guide to AI sovereignty, and what it really takes to make an open-weight model perform</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pvbV2JdGctpdzE2eV9GKQ.png" /><figcaption>Buy or rent?</figcaption></figure><p>Sovereignty is not a word I would often use in my lexicon, but over the last few months it has become a recurring theme. Discussions around sovereign AI have become more frequent with our enterprise clients at <a href="https://towardsai.com/">TowardsAI</a> and in my own day-to-day work.</p><p>It is not an entirely new theme for me. Last year, curious to see whether DeepSeek lived up to the hype, I wrote <a href="https://medium.com/@assel.kash/creating-a-private-custom-distilled-deepseek-r1-model-on-your-local-machine-using-it-within-an-9606ff37bb87">a guide to running a private, distilled DeepSeek-R1 model</a> on a local machine, so that no data ever leaves it. Enterprises are now asking the same question about systems that serve thousands of people.</p><p>“Should we be sovereign?” is a deceptively simple question. It usually hides one of three worries. Could we leave our AI provider if we had to? Could its next update quietly change a process we have signed off? Who sets the price as our usage grows? All three are about control, and each needs a different answer.</p><p>And almost every time, I end up unpicking the same assumption: that downloading an open-weight model gets you your own ChatGPT. It does not, and understanding why matters more than any other part of the decision.</p><h3>1. “What do we actually mean by sovereign?”</h3><p>Sovereignty, the ability to be self-governed, does not only apply to AI models but to the infrastructure, data and people that support them. The definition I use with clients: the degree of control you keep over your AI capability. Who can see it, change it, or take it away?</p><p>The simplified way I like to think about it is renting versus owning a home. Using a model through an API is like renting a furnished flat: someone else fixes the boiler, but they can also change the furniture, raise the rent or end the lease. Running your own open-weight model is closer to owning. Nobody can change the locks on you, but when the boiler breaks at 3am, it is your problem.</p><p>In practice there are five levels between renting and owning:</p><blockquote>• <strong>Level 0.</strong> Public AI tools on default terms.</blockquote><blockquote>• <strong>Level 1.</strong> An enterprise API with contractual controls, such as zero data retention and regional processing.</blockquote><blockquote>• <strong>Level 2.</strong> A provider’s model in your own cloud tenancy and region; the provider still decides when it changes or retires.</blockquote><blockquote>• <strong>Level 3.</strong> An open-weight model you host on infrastructure you control, so you decide when anything changes.</blockquote><blockquote>• <strong>Level 4.</strong> An open-weight or self-trained model under your own jurisdiction: on premises, in a sovereign cloud, or air-gapped.</blockquote><p>Sovereignty is a portfolio decision, made workload by workload. For most organisations, only a minority of workloads need Level 3 or 4; the rest can stay on APIs. A marketing copy assistant, for example, works with public information and benefits from the most capable model available, so an enterprise API at Level 1 is usually enough. A system summarising patient notes handles some of the most sensitive data there is, sits inside a regulated process and must not change without warning, which points to Level 3 or 4.</p><p>A rule of thumb before going further: separate the model from the harness around it, meaning the instructions, tools and connections that turn a model into a working assistant. Together, a frontier model and its harness make an excellent generalist, and more and more of the enterprise automation I see runs inside products like ChatGPT, Claude and Gemini. If most of a workflow’s value comes from that harness, accept less sovereignty for it; rebuilding it around an open-weight model is rarely worth the effort. Sovereignty earns its place in narrower, more sensitive work. I come back to the harness in section three.</p><h3>2. “Why would we do this, and what happens if we don’t?”</h3><p>Three drivers come up repeatedly, and each is also a risk you carry if you stay fully dependent on external providers. The first is the most tangible, because it disrupts day-to-day operations. The other two are more strategic.</p><blockquote><strong>Change control.</strong> With an API model, the provider decides when the model changes or retires, on its own deprecation schedule and sometimes with only a couple of months’ notice. I have seen first hand that this is where closed models cause the most pain.</blockquote><blockquote>When a provider retires a model that a workflow was validated on, the first hit is to the workflow itself: a process that was already signed off has to be re-validated on someone else’s timetable, and quality can dip before anyone notices. The second hit is operational. A migration nobody budgeted for suddenly needs money, people and the technical skills to test and switch models, often in the middle of a budget cycle, and other work stalls while the team makes the switch. With open weights, the model you validated is the model you run, until you choose to change it.</blockquote><blockquote>The lesson I took away is that having evaluations is not enough. If your architecture cannot run them automatically against a new model, testing a replacement becomes slow and manual, and problems slip through. Evaluations take the sting out of a forced switch only when you can run them at the push of a button. I touch on this below and will cover it properly in a future article.</blockquote><blockquote><strong>Data control.</strong> Enterprise contracts can promise zero data retention, but some data should never leave your control at all, from patient records to privileged legal material.</blockquote><blockquote><strong>Resilience and exit.</strong> Regulators increasingly treat dependence on a few providers as a risk in itself. Since July 2026, AWS, Google Cloud, Microsoft and Oracle have been designated critical third parties to the UK financial sector, and DORA already requires EU financial firms to have tested exit strategies for critical technology services.</blockquote><h3>3. “Can’t we just download a model and have our own ChatGPT?”</h3><p>As I mentioned earlier, when you open ChatGPT, Claude or Gemini, you are not talking to a model. You are using a product, and the model is only one layer of it. Around it sits the harness: everything that turns raw capability into a reliable assistant. To stretch the flat analogy, the chat apps are serviced apartments. An open-weight model is a well-built shell, and the kitchen, plumbing and wiring are a fit-out project.</p><h3>What sits in the harness</h3><p>The harness has six layers:</p><blockquote>• <strong>Instructions.</strong> Chat apps start every conversation with a long system prompt that sets tone, format and safety behaviour, and even tells the model today’s date. The one Anthropic publishes for the Claude apps runs to thousands of words and does not apply when you call the same model through the API. An open-weight model arrives with none of it.</blockquote><blockquote>• <strong>Reasoning control.</strong> How long the model thinks before it answers, which the chat apps manage for you. More on this below.</blockquote><blockquote>• <strong>Tools.</strong> Web search, code execution, reading files, connections to your systems. Each is built, secured and tested, and called in exactly the format the model was trained on.</blockquote><blockquote>• <strong>Knowledge and memory.</strong> Retrieval over your documents, memory between conversations, and what fits into the model’s working memory.</blockquote><blockquote>• <strong>Safety layers.</strong> Filters and classifiers around the model, and monitoring for misuse.</blockquote><blockquote>• <strong>Measurement.</strong> The labs test changes against large evaluation suites before they ship. You need your own.</blockquote><p>This is why a raw open-weight model often disappoints on day one. In my experience, much of the gap between a downloaded model and the assistant people use every day comes from the harness, not the weights.</p><h3>Reasoning is a dial, and it has a price</h3><p>Reasoning is the least understood layer. Models that think step by step do better on hard problems, but thinking produces extra tokens, and tokens are time and money; Google’s Gemini documentation bills thinking tokens alongside the answer.</p><p>Who turns the dial depends on how you use the model. In a chat product, the vendor turns it for you. When OpenAI launched GPT-5 in 2025, it described a fast model, a deeper reasoning model and a real-time router deciding between them, and it keeps refining how that router decides. Through an API, you usually get the dial yourself, on a model version you can pin. With an open-weight model, you are the router: OpenAI’s gpt-oss offers low, medium and high reasoning effort, set with one line in the system prompt, and Qwen3 models can switch thinking on and off between messages. Nobody changes the setting but you.</p><p>Pulling fields out of an invoice needs very little thinking; reviewing a complex credit memo may need a lot. In an open-weight deployment, finding the right setting for each task takes real experimentation and evaluation, because it moves quality, speed and cost at the same time.</p><h3>Getting it to perform: the customisation ladder</h3><p>When a model underperforms, the instinct is to fine-tune. It is usually the wrong first step. Simpler, cheaper options often get you further. Here is the ladder, from the cheapest rung to the most expensive:</p><blockquote>1. <strong>Instructions and examples.</strong> Clear system prompts and worked examples. Days of effort, and often the biggest gains.</blockquote><blockquote>2. <strong>Reasoning settings.</strong> Matching thinking effort to each task.</blockquote><blockquote>3. <strong>Retrieval.</strong> Connecting the model to your documents. Only as good as the data behind it.</blockquote><blockquote>4. <strong>Tools and workflows.</strong> Letting the model look things up, calculate, draft and check. Integration and security work concentrates here.</blockquote><blockquote>5. <strong>Fine-tuning.</strong> Training on your own examples. Powerful for narrow, high-volume tasks, but it needs curated data and creates a new model to govern.</blockquote><p>Your evaluations tell you how far up the ladder you need to climb.</p><h3>Evaluation is the experimental protocol</h3><p>Coming from a science background, I think of evaluation as the experimental protocol for your AI: a few hundred real examples, each with an agreed good answer, against which every change is tested. Without it, you cannot tell whether a new prompt, setting or model made things better or worse.</p><p>It also defines what you release. In production, “the model” is really a bundle of weights, instructions, reasoning settings, tools and safety configuration. Change any one and behaviour can shift without a single error message, so the bundle is versioned, tested and released together, with a way to roll back. This is where the details matter and the tolerance for error is low.</p><p>None of this is a side project for one talented engineer. It needs platform engineering, security, licence checks and domain experts who own the evaluation sets. <strong>That is why the evaluation suite ends up being the most sovereign thing you own.</strong></p><h3>4. “What will it really cost, and how do we compare?”</h3><p>The most common mistake I see is comparing an API price per token with a GPU price per hour. They are not comparable until you add utilisation and people.</p><blockquote><strong>API costs are variable:</strong> tokens multiplied by a price someone else sets, from cents to tens of dollars per million output tokens depending on the model tier.</blockquote><blockquote><strong>Self-hosted costs are mostly fixed:</strong> GPU capacity, redundancy, test environments and, usually the largest line, the team. Renting a single H100 GPU currently costs roughly $3 to $7 an hour.</blockquote><blockquote><strong>Utilisation is the hinge.</strong> Imagine renting an eight-GPU node for $30 an hour that sustains 3,000 output tokens per second on your workload. Running flat out, it produces 10.8 million tokens an hour, about $2.80 per million. If your traffic keeps it busy only 20% of the time, the effective price is five times higher, around $14 per million. Same hardware, same model, five times the cost.</blockquote><p>At, say, $100,000 a month for a lean, redundant service, you would need around 20 billion tokens a month before self-hosting beats an API at $5 per million. For many enterprises, cost alone will not justify self-hosting a large model.</p><p>Finally, measure cost per successful task: a cheaper model that needs more retries or human review is not cheaper. And price in the risk you are avoiding, from a forced re-validation to a week of downtime.</p><h3>So, should you go sovereign?</h3><p>My answer in most cases is to be sovereign where it matters and portable everywhere else. The path we usually recommend has five steps:</p><blockquote>1. <strong>Build the evaluation suite first.</strong> It pays off whatever you decide.</blockquote><blockquote>2. <strong>Route everything through a gateway,</strong> a single internal entry point to your models, so switching is a configuration change, not a rewrite.</blockquote><blockquote>3. <strong>Classify your workloads,</strong> and move only the ones that need it to a self-hosted open-weight model.</blockquote><blockquote>4. <strong>Budget for the harness,</strong> not just the model.</blockquote><blockquote>5. <strong>Review the portfolio every quarter,</strong> because models, prices and regulations keep moving.</blockquote><p>Over my career, the question has moved from how do we build, to how do we deploy, and now to how do we transform. Sovereignty touches all three: what you build determines what you can deploy, and how you deploy determines how far you can transform.</p><p>In conclusion, sovereignty is less about owning everything and more about making sure nobody else can change, see or switch off the parts of your AI capability that your business cannot do without.</p><p><em>At </em><a href="https://towardsai.com/"><em>TowardsAI</em></a><em>, our work is turning AI from something teams experiment with into a capability they rely on, and increasingly, a capability you rely on is one you need to control. If these are questions your organisation is wrestling with, we’d love to talk.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6491cc8de55b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Environments]]></title>
            <link>https://medium.com/@assel.kash/virtual-environments-8994617f71f1?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/8994617f71f1</guid>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[package-management]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 15:21:06 GMT</pubDate>
            <atom:updated>2025-04-22T15:22:16.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*-my67ZDSaMQh36fGa0jxqQ.png" /><figcaption>Virtual envrioments &amp; package management.</figcaption></figure><p>As a follow on to my recent article on how to <a href="https://medium.com/@assel.kash/basics-of-setting-up-python-vscode-with-homebrew-on-your-macbook-m1-machine-478dd494fc7e">set up a dev environment</a> on your local machine, I would like to discuss the topic of virtual environments in more depth, what they are, why they are needed, how to practically get up and running with virtual environments on your machine and finally how to use them with Jupyter Notebooks in VSCode.</p><p><strong>What is a virtual Environment?</strong></p><p>Virtual environments- known as venv for short; is a way of managing Python dependencies within an isolated, containerised space on your machine. The simplified way that I like to think of venv’s are spaces (like folders) on your machine in which you can configure your resources that apply only to that space rather than the whole machine. So, as an example the default setting on your machine could be to always preferentially use the latest version of Python whereas in a new venv you set up, you might want it running on Python3.9. The concept is simple, but the more pressing questions is why would you want to do this and why are venv’s so important.</p><p><strong>Why do you need a virtual Environment?</strong></p><p>One of the great advantages of Python as a programming language is the rich ecosystem of libraries which can be readily utilised by users without the need to build every little thing from scratch. These libraries are often themselves built using other libraries- and these interoperable chains are known as dependencies. To provide a concrete example, the popular ML library Scipy extends the functionality of Numpy therefore when downloading Scipy through pip (the most popular package manager for Python that takes out all the heavy lifting) you might notice any packages that library is dependent on will be downloaded alongside the install if they do not exist on your system.</p><p>Since libraries and even Python itself is an evolving utility; over time new versions of packages are released which might have different functionalities to its previous versions. Where the system runs into problems when dependencies meet versioning. Each package is unique and might have specific version dependencies which clash with other specific version requirements for other libraries. This is where virtual environments come into their own- to be able to have parallel isolated spaces the specific needs of various packages without interfering with each other.</p><p><strong>An Example</strong></p><p>For my recent <a href="https://medium.com/@assel.kash/chain-of-logic-extracting-value-from-data-through-the-use-of-semantic-processing-unsupervised-110157c2629f">chain of logic article</a>, I needed to use the library Gensim which not only has a dependency on an older version of Numpy than that my system but also is only compatible with an older version of Python. So below I will step through how to identify something like this and set up a venv to meet the need.</p><p>To begin with, I did not know that Gensim is incompatible with the latest version of Python but after failing to upload the Gensim library with pip; with some extensive googling and thanks to multiple answers on StackOverflow, I settled on trying to troubleshoot my problem by downgrading my running version of Python to something which is known to be compatible. Not wanting to change the main set up on my machine, I needed to set up a new virtual environment specifically for my project, which is good practice anyway.</p><p>Since I wanted my venv to run Python3.9, using terminal I first confirmed that it is installed with brew using the command <strong><em>brew list</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*2WQzv0c8C_IY_x7V4e1RTw.png" /><figcaption><strong>brew list</strong><em> to show which Python versions are available on your local machine.</em></figcaption></figure><p>Navigating to the directory path where I want to store my venv, I used <strong><em>python3.9 -m venv MY-VENV-NAME </em></strong>command to create a new venv instance. You will notice a bunch of files appear in the MY-VENV-NAME folder in your directory. (Note that to create a venv with a specific version of python you need to specify it within your command whereas if you want it to match the preferred version on your machine, you just put python.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPoRz0SRBVwYazztvQxeOQ.png" /><figcaption>Upon executing <strong><em>python3.9 -m venv MY-VENV-NAME </em></strong><em>in terminal, you will see the system creates a number of resources in the new venv folder.</em></figcaption></figure><p>After the venv has been set up, it needs to be activated by using the command<strong><em> source MY-VENV-NAME/bin/activate.</em></strong></p><p>You can download your required libraries using pip in your new venv. By using the prompt <strong><em>pip list –local</em></strong> you can review what libraries are installed. You can compare the difference between that and what is installed on your main machine by using the same command inside and outside the venv. Remember since the venv is a containerised space, all libraries that are required for your project need to be added there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bogdWla2H_zwklrqHhj6JA.png" /><figcaption>Python libraries within the created venv.</figcaption></figure><p>The final step is that you need to add you venv as a python interpreter in VSCode. To be able to successfully use the venv in Jupyter Notebooks, you need to make sure you have used pip to install the jupyter and ipykernal library within your venv using the command <strong><em>pip install jupyter ipykernal.</em> </strong>With the following command, you can add your venv to the VSCode path: <strong><em>python -m ipykernel install — user — name=MY-VENV-NAME — display-name “WHATEVER NAME YOU WANT TO SHOW IN VSCODE”. </em></strong>Restart VSCode. When you open a Notebook and select an execution kernel, you should be able to see your new venv listed under ‘Python Environments’. <strong>Make sure your venv is activated otherwise it wont be detected.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*B6AxQLu9Z-6k2ek23nlBtQ.png" /><figcaption>By using the commands above, VSCode will detect the activated venv on your system automatically when selecting a Jupyter Notebook execution kernel.</figcaption></figure><p>Now that your venv is up and running, you will be able to import the resources as you would normally would into your scripts.</p><p>Once you are done, you need to deactivate the venv by using the command <strong><em>deactivate</em></strong> in terminal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8994617f71f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a private, custom distilled Deepseek-R1 model on your local machine & using it within an…]]></title>
            <link>https://medium.com/@assel.kash/creating-a-private-custom-distilled-deepseek-r1-model-on-your-local-machine-using-it-within-an-9606ff37bb87?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/9606ff37bb87</guid>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 16:10:34 GMT</pubDate>
            <atom:updated>2025-02-16T16:10:34.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a private, custom distilled Deepseek-R1 model on your local machine &amp; using it within an operational Python pipeline</h3><p>I doubt there is any need for me to introduce what Generative AI is capable of and since its conception with <a href="https://en.wikipedia.org/wiki/GPT-1">GPT-1</a> in 2018, LLMs are becoming increasingly integrated with our day-to-day lives. Most of us have interacted with them via a web or app UI which allows us to ask questions of the LLM and receive answers within a chat interface. This method is effective to get answers when you want it to help with a bug in your code or give you the ingredients for a Spaghetti Bolognese, but less so when trying to integrate custom LLMs into your automated pipelines and run operations on your datasets. In today’s article I will introduce how to achieve this by creating a local version of <a href="https://github.com/deepseek-ai/DeepSeek-R1">Deepseek-R1</a>, customizing the LLM and seamlessly running it within your python scripts.</p><p>Last month <a href="https://www.deepseek.com/">Deepseek</a> released its latest LLM offering to much excitement which rocked the tech world. Alongside Deepseek-R1, the team released several distilled model variants which come in a variety of sizes. Thanks to the process of model distillation which transfers knowledge from a larger LLM to smaller containerised models; developers can utilise LLMs locally and reap the benefits of its reasoning capabilities in a more efficient and hardware agnostic way. One of the substantial benefits of having a local version of the model is data privacy. Since you aren’t making any API calls to send and receive messages from the LLM like a service, your processes run locally engaging with the local instance of the Deepseek model. This means that this method has enhanced privacy (as well as being able to be fully functional offline).</p><p>To begin with you need to install <a href="https://ollama.com/">Ollama </a>on to your local machine. This can be easily done by navigating to <a href="http://www.ollama.com/">www.ollama.com</a> and clicking the download button. The next screen will provide you with the option to select the installer most relevant for your system and just navigate through that download process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpAwJ3cUQ50hjzdfC-EWIw.png" /><figcaption>Ollama website</figcaption></figure><p>Once that is complete, (assuming you are using a Macbook) open up terminal by ‘’command + space’’ and type in Terminal which will open up a new shell and simply instruct ollama to upload your desired distilled Deepseek-R1 model. Since my use case is not particularly sophisticated, I opted for the smallest model which is <strong>DeepSeek-R1-Distill-Qwen-1.5B. </strong>Once the ‘<strong><em>ollama run deepseek-r1:1.5b</em></strong>’ command starts executing, you will see the pull being uploaded onto your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhbJymGI5eTMov6lBJJO6g.png" /><figcaption>Install of local instance of deepseek-r1:1.5b model. Make sure to specify the correct model. My first download was not the correct one which needed to be aborted by using command+c.</figcaption></figure><p>The incredible thing is once this is uploaded, you can start interacting with the model straight away within the terminal window. By writing your prompt directly after the &gt;&gt;&gt; you can start to engage with the local version of your model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPjdzkiZqVMWwYPFWVDPqA.png" /><figcaption>Asking a few questions of the LLM within terminal directly after install</figcaption></figure><p>Since we are looking to use this model within a python script, now we need to also upload the ollama python library which provides a number of helper functions to interact with the installed model. Ideally within your working virtual environment (or on your machine globally) download the library through using the command ‘<strong><em>pip install ollama</em></strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfuNEwqJD2FtRWiyQjzGoQ.png" /><figcaption>If the library is already installed in your working enviroment, you will see ‘Requirement already satisfied:’ as shown above. Otherwise pip will proceed to install the library</figcaption></figure><p>Now let’s make sure we can interact with the model through our notebook in VSCode just as we could from terminal. Navigate to VSCode, open up a new notebook and double check that the kernel you are selecting to run your notebook with is the correct instance with all your libraries installed.</p><pre>from ollama import chat<br>from ollama import ChatResponse<br><br>response: ChatResponse = chat(model=&quot;deepseek-r1:1.5b&quot;, messages=[<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;what is ketchup made out of?&quot;<br>    }<br>])<br>print(response[&#39;message&#39;][&#39;content&#39;])</pre><p>What the <a href="https://github.com/ollama/ollama-python/blob/main/README.md">code above</a> does is send a message to your model with a dictionary to define the role and prompt question being asked. We can see the conversational nature of Deepseek models based on the verbose response I get to my question of ‘What is ketchup made out of?’.</p><pre>&lt;think&gt;<br>Alright, the user is asking about what ketchup is made out of. I know that ketchup is a common condiment, so probably from tomatoes. But maybe there&#39;s more to it.<br><br>I remember hearing about tomatoes being classified as red or yellow in botany. That might influence the type of sauce. Let me think—red tomatoes are typically used for tomato-based sauces like ketchup because they tend to have softer skin and a different flavor profile.<br><br>Also, I think ketchup is a sweet dressing. So maybe it&#39;s not just from tomatoes alone but has some sugar content. Perhaps it uses tomatoes in conjunction with other ingredients like sugar or honey to make the sauce甜.<br><br>Wait, I&#39;m trying to remember if there are any other common condiments that are made from tomatoes. Maybe something else along the lines of onions or garlic? Or maybe vinegar or another acid is involved?<br><br>No, ketchup doesn&#39;t sound like it&#39;s made with anything like apple cider vinegar. That sounds more acidic, which doesn&#39;t fit a sweet taste. So I think it&#39;s primarily tomato-based, especially red tomatoes.<br><br>I should also consider other vegetables but probably not relevant here since the question is focused on ketchup. Maybe just adding some details about how it&#39;s prepared once made—like salt and pepper added, perhaps some sugar or honey to enhance flavor.<br><br>So putting it all together: Ketchup comes from red tomatoes, which are soft and rich in flavor. It&#39;s sweetened with sugar or honey and made into a condiment by dissolving the tomato juice into a dressing that can be enjoyed hot or cold.<br>&lt;/think&gt;<br><br>Ketchup is typically made from red tomatoes, often found in the American South. The sauce is rich, tangy, and flavorful because of its use of tomato juice, which has a sweet, slightly acidic flavor due to the acidity of the juice. Ketchup is prepared by dissolving the tomato juice into a dressing that can be enjoyed hot or cold. It is commonly used as a dip in many dishes and is a popular condiment worldwide.</pre><p>We can see that the structure of the responses from the model can be split into two parts, the chain of thought which is encased within the &lt;think&gt; | &lt;/think&gt; and the actual response in the latter part of the output string.</p><pre>I sure would like to see a resurrection of a up dated Seahunt series with the tech they have today it would bring back the kid excitement in me.<br>I grew up on black and white TV and Seahunt with Gunsmoke were my hero&#39;s every week.<br>You have my vote for a comeback of a new sea hunt.We need a change of pace in TV and this would work for a world of under water adventure.<br>Oh by the way thank you for an outlet like this to view many viewpoints about TV and the many movies.<br>So any ole way I believe I&#39;ve got what I wanna say.Would be nice to read some more plus points about sea hunt.<br>If my rhymes would be 10 lines would you let me submit,or leave me out to be in doubt and have me to quit,If this is so then I must go so lets do it.</pre><p>To show how the model can be utilised within a python script, I have found a dataset online which consists of lengthy opinions about movies; an example of an opinion captured within the dataset is shown above. For sake of example, I want the model to go through my dataset and understand the sentiment of the opinions and rank each one from -5 to 5 adding it to a new column. I want to utilise both parts of the models response and for each opinion string I have in my dataset, I want to also add a column which provides me the models thinking around why that specific score was given.</p><pre>import re<br>import pandas as pd <br>import openpyxl<br><br>def ask_deepseek(input_context, system_prompt, deep_think = True, print_log = True):<br>    response: ChatResponse = chat(model=&quot;deepseek-r1:1.5b&quot;, messages=[<br>    #we are sending a prompt consisting of two parts, the system and the input<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: input_context}<br>    ])<br>    response_text = response[&#39;message&#39;][&#39;content&#39;]<br><br>    if print_log: print(response_text)<br>    # Extract everything inside &lt;think&gt;...&lt;/think&gt; - this is the Deep Think<br>    think_texts = re.findall(r&#39;&lt;think&gt;(.*?)&lt;/think&gt;&#39;, response_text, flags=re.DOTALL)<br>    # Join extracted sections (if multiple &lt;think&gt; sections exist)<br>    think_texts = &quot;\n\n&quot;.join(think_texts).strip()<br>    # Exclude the Deep Think, and return the response<br>    clean_response= re.sub(r&#39;&lt;think&gt;.*?&lt;/think&gt;&#39;, &#39;&#39;, response_text, flags=re.DOTALL).strip()<br><br>    # Return either the context, or a tuple with the context and deep think<br>    return clean_response if not deep_think else (clean_response, think_texts)<br><br>#retrieve my movie opinions dataset from my local machine and convert to dataframe<br>file_path = &#39;/Users/assel/Downloads/facts_opinions.csv&#39;  <br>df = pd.read_csv(file_path)<br>#truncate the df to a more manageable size just for prompt engineering<br>df = df[:30]<br><br>#generate the prompt to be given to the model about the task that it needs to perform<br>system_prompt_sentiment = &#39;&#39;&#39;You will be provided with a dataset with comments about movies. <br>The users have given their opinions on the movies and you need to score each comment based on the sentiment of the user.<br>The sentiment score is on a scale of -5 (very negative) to 5 (very positive).<br>Please only answer with the ranked score and do not include any other word or explanation before or after the ranked score.<br>Do not include the &#39;+&#39; symbol in the output if the score is positive, but do include the &#39;-&#39; symbol if the score is negative.<br>&#39;&#39;&#39;<br><br># Ask model to rank each opinion with the inclusion of the logic and adding both to a new column within my dataframe<br>df[[&#39;LLM_SENTIMENT&#39;, &#39;LLM_DEEP_THINK&#39;]] = df[&#39;Text&#39;].apply(lambda opinion: ask_deepseek(opinion, system_prompt_sentiment)).apply(pd.Series)</pre><p>After running the above on 30 samples of my code, below is an example of the responses I received from the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgDrAT2zLMhNVY0ttmbjBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGtsl-PbSpEDSyrtWKjYBw.png" /></figure><p>Using the pandas apply() function, I can use the function specified above to run the model against all the rows in my dataframe alongside the helper system prompt to help guide the model to produce the correct output.</p><p>Reading through the rankings they seem reasonable and the chain of logic is certainly comprehensive. To perform this exercise for 30 opinion texts, the model took 5.09 min to execute. Through some prompt engineering, I am sure it is also possible to improve on both the latency and quality of output from the model, however optimisation of prompts is an extensive and elaborate art-form best left for another article.</p><p>In conclusion, the above guide gives you an easy way to create a local, private instance of one of the latest distilled Deepseek-R1 models and shows you a simple way to create custom prompts to run together in your on your own data in a scalable way. Although I have used the model for sentiment analysis, there is a magnitude of other applications such as extraction, translation and other forms of reasoning that can be applied using the process demonstrated above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9606ff37bb87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain of Logic: Extracting value from data through the use of semantic processing, unsupervised…]]></title>
            <link>https://medium.com/@assel.kash/chain-of-logic-extracting-value-from-data-through-the-use-of-semantic-processing-unsupervised-110157c2629f?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/110157c2629f</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 18:09:33 GMT</pubDate>
            <atom:updated>2025-01-28T18:09:33.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chain of Logic: Extracting value from data through the use of semantic processing, unsupervised clustering methods (&amp; RGB processing)</h3><p>The point of this article to demonstrate how a combination of techniques can be used in sequence to extract value out of modest datasets. I will present a fictional dataset and use-case and discuss some ML methods that can be used to quickly enrich data in a meaningful way which could be powerful in the commercial world.</p><p>Imagine you are a large manufacturer producing clothes that is looking to implement a new digital marketing strategy. You want to have a distinct campaign targeting different groups within your customer base based on common attributes. A simple way of achieving this could be using determinist methods such as defining rules that would tell you to ‘show this blue skirt to all the customers that like blue’ however we want to take it a step further and decide what the right way forward is based on more advanced methods. Here I will step through how we can achieve better results through doing data analysis utilising semantic processing, unsupervised clustering and some ingenuity with grouping colors.</p><p>Since this is a made-up example, my first step is to use<a href="https://faker.readthedocs.io/en/master/"> faker</a> to create notional data with customer names and a few associated attributes such as job, city, favourite colour and title.</p><pre>#Importing all needed libraries<br>from faker import Faker #for generating notional data<br><br>import pandas as pd #for data manipulation<br>import numpy as np #for numerical operations<br><br>from sentence_transformers import SentenceTransformer #for semantic processing of text BERT<br>from sklearn.cluster import KMeans #for clustering  <br>from sklearn.decomposition import PCA  #for dimensionality reduction<br><br>import matplotlib.pyplot as plt #for plotting<br>import webcolors    #for color names to RGB conversion</pre><pre>#creating a notional dataset using faker <br><br>fake = Faker()<br><br>dataset_size = 10000<br>fake_names_lst = [fake.name() for _ in range(dataset_size)]<br>fake_color_lst = [fake.color_name() for _ in range(dataset_size)]<br>fake_job_lst = [fake.job() for _ in range(dataset_size)]<br>fake_city_lst = [fake.city() for _ in range(dataset_size)]<br>fake_suffix_lst = [fake.suffix() for _ in range(dataset_size)]<br><br>data_struct = {<br>    &#39;Name&#39; : fake_names_lst,<br>    &#39;Color&#39;: fake_color_lst,<br>    &#39;Job&#39;  : fake_job_lst,<br>    &#39;City&#39; : fake_city_lst,<br>    &#39;Suffix&#39; : fake_suffix_lst<br>                }<br><br>main_df = pd.DataFrame(data_struct)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYgSXH9XfsOmfELS1sCR0g.png" /><figcaption>Screenshot to show the notional data generated by Faker library</figcaption></figure><p>In the real world, we often deal with high dimensionality data. Put in simple terms, an attribute can have many distinct values. In our notional data example, we can see this in the ‘Job’ or ‘Color’ attribute where there are over 100 distinct values. Since we cannot produce over 100 distinct marketing campaigns to match these attributes, the first step is to develop a classification method to create clusters out of the existing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*I-dzZxX_JSj2zgHeRz0Ciw.png" /></figure><h3>Semantic processing and K-means clustering</h3><p>One way of reducing the dimensionality of our dataset is by analysing the meaning of our attributes and grouping based on semantically meanful concepts. We do this naturally in language such as bucketing ‘CEO’ and ‘CFO’ as executives or ‘Frontend Engineer’ and ‘QA’ as engineers. The same can be done with data by creating a numerical representation of the words in large multidimensional vectors and then comparing the distances between them. The closer the vectors are to each other, the more similar the words semantics. By averaging or summing across sentences, you can also do the same for larger bodies of text. The process of finding the numerical representation of a word is called embeddings.</p><p><a href="https://en.wikipedia.org/wiki/Word2vec#:~:text=Word2vec%20is%20a%20technique%20in,text%20in%20a%20large%20corpus.">Word2Vec</a> is a model part of the <a href="https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html">Gensim library</a> allows you to perform these embeddings supporting both trained and untrained versions. As an unsupervised clustering ML model- Word2Vec can be trained solely on your data (this is advisable if you have a large repository of text data) where it will determine the right representation of your words in the vector space. For use-cases where you are using short or single word sentences, it is better to use the <a href="https://huggingface.co/fse/word2vec-google-news-300">pre-trained version</a> since context is important for the efficiency of creating accurate vectors. Having struggled to use it effectively for my job titles, I pivoted to using<a href="https://huggingface.co/docs/transformers/en/model_doc/bert"> BERT </a>by hugging face to generate the embeddings. BERT is trained on a larger corpus and unlike Word2Vec is a rich embedding accounting for context and surrounding words. It is also much easier to use without the need of preprocessing steps such as tokenisation or standardisation since that is all done under the hood.</p><pre># Load the pre-trained BERT model from Sentence-Transformers<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br># Generate BERT embeddings for the job titles<br>job_titles = main_df[&#39;Job&#39;].tolist()<br>embeddings = model.encode(job_titles)</pre><p>BERT generates large vectors, as we can see the vectors it produced for my job titles is 384 in length (this is actually mini-BERT that has similar performance but smaller compared to the 768 dimensional original BERT). Essentially what happens under the hood is that the words you pass to BERT are then looked-up and then passed through a transformer layer (this is a good<a href="https://www.analyticsvidhya.com/blog/2023/08/bert-embeddings/"> in-depth guide</a> to BERT)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l96OOExEs2_0yKjF-A8zVQ.png" /><figcaption>We can see here that the job title Proofreader has been converted to a 384 dimensional vector</figcaption></figure><p>To prepare and simplify our data for clustering, I am using PCA, a dimensionality reduction technique which reduces the noise and focuses on the most important features.</p><pre># reducing the dimensionality for better clustering<br>pca = PCA(n_components=50)  # Reduce to 50 dimensions<br>reduced_embeddings = pca.fit_transform(embeddings)</pre><p>Now that we have our job titles embedded and reduced to a manageable 50 dimensions, we can perform the clustering. For this I have chosen K-means due to its simplicity and explainability. This ML model calculates the <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distance</a> between vectors to determine its clusters. As an input parameter you need to feed the model with number of clusters you want the model to output. There is no concrete science to this but it can be determined by running the script with a range of cluster sizes and visualising the output and inspecting whether you are happy with the cohering with the groups. Alternatively the<a href="https://www.analyticsvidhya.com/blog/2021/01/in-depth-intuition-of-k-means-clustering-algorithm-in-machine-learning/"> elbow </a>or silhouette method can be used to assist with that. In my case I have gone for 8 since I am happy with the cohorting at level and it fits my theoretical use-case where the digital marketing team doesn’t want to create more than 8 distinct campaigns.</p><pre># KMeans clustering<br>kmeans = KMeans(n_clusters=8, random_state=42) <br>main_df[&#39;Cluster&#39;] = kmeans.fit_predict(reduced_embeddings)<br><br># PCA for visualization<br>pca_2d = PCA(n_components=2)<br>embeddings_2d = pca_2d.fit_transform(reduced_embeddings)<br><br># plotting the clusters<br>plt.figure(figsize=(10, 8))<br>plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=main_df[&#39;Cluster&#39;], cmap=&#39;viridis&#39;)<br>plt.title(&#39;2D visualization of Job Title Clusters&#39;)<br>plt.xlabel(&#39;PCA Component 1&#39;)<br>plt.ylabel(&#39;PCA Component 2&#39;)<br>plt.colorbar()<br>plt.show()<br><br># inspecting the clusters<br>for i in range(8): <br>    print(f&quot;Cluster {i}:&quot;)<br>    print(main_df[main_df[&#39;Cluster&#39;] == i][&#39;Job&#39;].tolist())<br>    print()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJDhOi4ryaTfSN7oGQjMgQ.png" /><figcaption>Clusters of the job title embeddings using BERT by Hugging Face &amp; K-Means</figcaption></figure><p>Comparing the cohorts, its come out quite well e.g. <strong>Cohort 0: [‘Production manager’, ‘Chartered management accountant’, ‘Customer service manager’, ‘Leisure centre manager’, ‘Records manager’, ‘Conference centre manager’, ‘Theme park manager’…]</strong> whereas<strong> Cohort 2: [‘Primary school teacher’, ‘Education administrator’, ‘Armed forces training and education officer’, ‘Further education lecturer’, ‘Adult nurse’, ‘International aid/development worker’ …]</strong> Not bad! Now the dataset has been enriched by automated cohorts determined by using semantic processing and unsupervised learning methods. Instead of 639 distinct values in my ‘Job’ column, I have grouped them into 8 buckets; much more manageable.</p><h3>Turns out it’s hard to deal with Colors</h3><p>Using faker, I was able to quickly generate notional data about colors which in my example today I am interpreting as being the favourite colour of the notional people in my dataset. When doing this I supposed that I would be able to apply the same logic as above to my ‘Color’ column.<strong> I was wrong</strong>. This resulted in poorly generated embeddings both with Word2Vec, FastText and BERT and even more shocking clusters. The reason for this is that colors are more concrete rather than conceptual and pre-trained models such as BERT lack context around colours. So despite it taking seconds to generate my color attribute, I had created myself a problem trying to figure out what the best way is to simply cluster colours without too much manual effort. <strong>This is a great demonstration of how it is important to select out which methods to use and how one size does not fit all.</strong></p><p>The great thing about colors is that we already have embeddings of sorts for them in the form of RBG. So to solve for our colour problem I just took our ‘Color’ column and used a library to map the string words to RGB representations.</p><pre># Converting color names to RGB values<br>def name_to_rgb(color_name):<br>    try:<br>        # Convert color name to RGB<br>        return np.array(webcolors.name_to_rgb(color_name)) / 255.0  # Normalize RGB values to [0, 1]<br>    except ValueError:<br>        return np.array([0, 0, 0])  # Default to black if invalid color name<br><br># Applying the RGB function <br>main_df[&#39;rgb&#39;] = main_df[&#39;Color&#39;].apply(name_to_rgb)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWtRdFXIcaI4DR8_AVDqkA.png" /><figcaption>Dataset enriched with Cluster column and RGB color representation</figcaption></figure><p>Now that we have the RGB representations for each color in our dataset, we can just manually determine the clusters for our colors based on the simple logic of whichever color is most dominent, taking it from 140 distinct values to 3.</p><pre>#function to classify the dominent color in rgb<br>def classify_dominant_color(rgb):<br>    red, green, blue = rgb<br>    if red &gt;= green and red &gt;= blue:<br>        return &#39;Red&#39;<br>    elif green &gt;= red and green &gt;= blue:<br>        return &#39;Green&#39;<br>    elif blue &gt;= red and blue &gt;= green:<br>        return &#39;Blue&#39;<br>    <br># applying function to column<br>main_df[&#39;Color&#39;] = main_df[&#39;rgb&#39;].apply(classify_dominant_color)</pre><p>Putting together the information from the clustering and RGB processing, further analysis can be conducted to understand the segmentation in the clusters and which attributes each cohort possess. In conclusion the above chain of logic demonstrates how different methods can be used in sequence to enrich data and create value for businesses by allowing it to be more usable and inform business strategy such as how to go about a digital marketing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=110157c2629f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of setting up Python & VSCode (with Homebrew) on your MacBook M1 + machine]]></title>
            <link>https://medium.com/@assel.kash/basics-of-setting-up-python-vscode-with-homebrew-on-your-macbook-m1-machine-478dd494fc7e?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/478dd494fc7e</guid>
            <category><![CDATA[homebrew]]></category>
            <category><![CDATA[macbook]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[setup-guide]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 14:22:37 GMT</pubDate>
            <atom:updated>2025-01-01T14:22:37.617Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Perhaps you are new to data science and have gone through some online courses but now its time to commit and set yourself up locally. Setting up a new dev environment on your local machine can feel exciting, confusing and daunting in equal measures; especially if you are new to the field. Here I try to demystify some concepts and provide a practical step-by-step guide on how to get python working on your MacBook and get everyone’s favourite IDE up and running. The below is specific to MacBooks with a M1 (or later) chip and Mac Ventura 13 (or later) operating systems.</strong></p><p>No digital environment remains stationary. Software, tools and utilities on your computer need to managed and over time installed, upgraded and removed. Many of these assets have dependencies which results in a more complex system to manage to ensure things work as intended. Package managers such as Homebrew are first class ways to help individuals keep on top of these things.</p><p>Homebrew is a package manager for macOS with a large repository of sources that can be installed onto your machine. Ran through command line, it does the heavy lifting under the hood to get your started and keep you going with a quick set up and a few short command line prompts. So before installing Python on your machine, it is advisable to download a package manager first to make life easier.</p><ol><li>Navigate to Terminal on your machine via ‘’command + space’’ and type in Terminal into the search bar which will open a command line interface. This allows you to control your operating system through writing commands in here.</li><li>Make sure you are in the root directory. You can use <strong>cd</strong> command to change directories and by typing <strong>ls</strong> you can output the list of files in the current working directory. (<a href="https://www.techrepublic.com/article/16-terminal-commands-every-user-should-know/">Link here</a> is a good guide to some basic terminal commands).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-TClqvqldMPGCwkeCgnhw.png" /><figcaption>Copy and paste the snippet of code below ‘Install Homebrew’ into terminal.</figcaption></figure><p>3. To install Homebrew, copy the command from the <a href="https://brew.sh/">brew.sh</a> website. Paste it into terminal and press enter. It will step you through the process with a couple of prompts; initially requesting to put in your system login password followed by prompts explaining what is being installed and requests to continue. What this is doing is running a script to install elements which will allow you to use the <strong>brew </strong>command in your terminal at your will.</p><p>4. Before proceeding to install Python, you want to make sure Homebrew is installing things in the right location. For this you need to provide Homebrew a path to this location which is known as a Cellar. If you type in the <strong>echo $PATH </strong>command it will give you a concatenated list of directories your system uses to store executable programmes. You are likely to see a long string of paths separated by<strong> :</strong>, the order in which it is displayed is what directories the system prioritises. You should see /<strong>opt/homebrew/bin </strong>as the first left most entry and if you do not that means that the path needs to be manually configured.</p><p>5. A .zrhrc file is a z-shell configuration file which runs every time you open a new shell (terminal window). Your machine uses this file and others to set up operations so this is where you will want to indicate your path. These configuration files are hidden and to view them you can use the command<strong> ls -al</strong> which will show you a list of normal and hidden files in the current working directory. Hidden files are denounced by a preceeding ‘.’ . .zshrc files are not usually found by default therefore need to be created.</p><p>5. To create the .zshrc type<strong> touch ~/.zshrc </strong>into terminal which will create a new empty file in the current working directory. Following this you can open that file with text editor by using the command<strong> open ~/.zshrc</strong>. You will expect to see a blank file open in text editor. Put the line:<strong> export PATH=”/opt/homebrew/bin:$PATH” </strong>into that file and click save. You can check that the change to the file has worked by typing in the <strong>cat ~/.zshrc </strong>in terminal which prints the contents of your file.</p><p>6. Refresh your terminal window by opening a new one, within it type in the <strong>echo $PATH</strong> and you should see /<strong>opt/homebrew/bin </strong>as the first entry which means now your system will use that directory path preferentially. Confirm Homebrew is operating as expected by using the command <strong>brew doctor </strong>to which the output should be ‘Your system is ready to brew’ and confirm its in the right location via the command <strong>where brew</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*K9gs3C00chWT9a5_32Cskg.png" /><figcaption>Upon successful install, you should be able to use brew command in terminal.</figcaption></figure><p>7. Now you are finally ready to install Python which you can do with <strong>brew install python; </strong>this gets you the latest version. To search for a specific version of python, you can use the command <strong>brew search python </strong>which will output all sources available in Homebrew. A formulae is a core software whereas a cask is an application with an interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoIBjvwbJTtYsM2e2EdYmg.png" /><figcaption>A list of all sources which Homebrew has that have python in the name split out by formulae and casks.</figcaption></figure><p>8. Once install is complete you can use <strong>brew info python</strong>, this will provide you with all the details about your install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG-9SV-brrdtdcDhhnKOJw.png" /><figcaption>Full details about your python install</figcaption></figure><p>10. You can use Python within terminal so to make doubly sure everything is working, use <strong>cd </strong>to navigate to the directory of your choice and create a new hello_world file there with the command <strong>echo ‘print(“Hello World!”)’ &gt; hello_world.py</strong>. What this command does is create the file with filename hello_world.py if it doesn’t exist and inserts print(‘Hello World!’) as the script. To execute this script, you simply use <strong>python3 hello_world.py</strong>. If everything is working as expected, you will see this output directly in terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5ovJdVsDSEide9GEbZiCg.png" /><figcaption>Creating a basic script to check python is running on your machine.</figcaption></figure><p>11. Finally you can also use brew to install <a href="https://code.visualstudio.com/">Visual Studio Code </a>too with <strong>brew install — cask visual-studio-code</strong>. Once the install is complete, you can find VSCode in your applications folder on your mac.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v41VVZcSgG5BVGpCG-LBkA.png" /><figcaption>By searching brew, you can find all sources for visual-studio.</figcaption></figure><p>12. VSCode does a good job at guiding you through the set up so just follow the step-by-step guide in the GUI. You can once again confirm your python download when VSCode prompts you to select your interpreter and it shows the brew install as your recommended option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mj4wSZmA3Br0H0fBy-p5nw.png" /><figcaption>Within VSCode, you can select the brew installed python as the interpreter.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478dd494fc7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grouped bar chart with duel y-axis using Python and Plotly (Part 2)]]></title>
            <link>https://medium.com/@assel.kash/grouped-bar-chart-with-duel-y-axis-using-python-and-plotly-part-2-62dee190021?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/62dee190021</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 18:08:39 GMT</pubDate>
            <atom:updated>2024-12-29T18:08:39.331Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@assel.kash/grouped-bar-chart-with-duel-y-axis-using-python-and-plotly-part-1-35cb48e063ec">part 1 </a>of this series I demonstrated how to create a static version of the visualisation described in the title of this post. I have found that this visualisation is particularly powerful at demonstrating categorical data where the audience needs to make between and within group comparisons.</p><p>Though static plots are informative, making a plot dynamic and interactive always elevates the experience for the user as they can probe the underlying dataset by segmenting based on their personal needs. So, within this article I will show how to recreate an interactive version of the plot by introducing a dropdown button.</p><p>Though I have kept the implementation below simple for clearer demonstration, there are countless ways you can enhance and customise visualisations using <a href="https://dash.plotly.com/">Plotly Dash</a>, so I would encourage further self-exploration of the documents to adjust the code to your personal requirements.</p><p>1.) <strong>The basic structure of a dash app</strong></p><p>All Plotly Dash applications have the same basic structure and must follow the same order. After importing all the required libraries for the project, an instance of the app needs to be created by initialising <strong>app = Dash(__name__)</strong> and then the<a href="https://dash.plotly.com/layout"> <strong>app.layout</strong> </a>needs to be defined. This is the part which informs the UI of the app. Following that, the <a href="https://dash.plotly.com/basic-callbacks"><strong>@app.callback</strong></a> properties and functions need to be defined. A callback informs what the interactive functionality the elements within the layout should have. It is possible to have multiple separate callback functions for different callback properties. Finally, all scripts need to finish with <strong>app.run_server </strong>function contained in an ‘if main’ statement which runs the code. When running the script on your local machine, this statement allows you to access your app through your local host IP in your browser (<a href="http://127.0.0.1:8050/">http://127.0.0.1:8050/</a>).</p><pre><strong>#app required libraries</strong></pre><pre>from dash import Dash, dcc, html<br>from dash.dependencies import Input, Output, State</pre><pre><strong>#libraries required for visualisation</strong></pre><pre>import plotly.express as px<br>import plotly.graph_objs as go<br>from plotly.subplots import make_subplots</pre><pre><strong>#general</strong></pre><pre>import pandas as pd<br>import numpy as np<br>import random<br>from datetime import datetime, timedelta</pre><pre><strong>#creating a dash app instance</strong></pre><pre>app = Dash(__name__)</pre><pre>app.layout = &lt;your app layout&gt;</pre><pre>@app.callback(&lt;your callback properties&gt;)</pre><pre>&lt;your callback functions&gt;</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run_server(debug=True)</pre><p>2.)<strong> Adding the dcc.Graph and dcc.Dropdown elements to the app</strong></p><p>Now that you have the basic structure of the application, elements need to be added into the app.layout.</p><p>When building an application, all elements that are visible on the screen are presented within containers. <a href="https://dash.plotly.com/dash-html-components">The dash.html module</a> has basic html containers that can be added to the UI such as a div’s. These are generic containers that need to be customised. For containers that need to have an interactive component such as a button or graph, <a href="https://dash.plotly.com/dash-core-components">dash core components (dcc) </a>makes the task easier by providing a number of components with predetermined layout and functionality constraints that can be easily integrated into your application without having to build out the element from scratch. So after creating a container to house your components, you will use the <a href="https://dash.plotly.com/dash-core-components/dropdown">dropdown</a> and <a href="https://dash.plotly.com/dash-core-components/graph">graph</a> dcc components to insert those elements into the UI.</p><pre>app.layout = html.Div([</pre><pre>dcc.Dropdown(<br>    id=&#39;car_attribute_dropdown&#39;,<br>    placeholder=&#39;Car Attribute&#39;,<br>    options= [{&#39;label&#39;: i, &#39;value&#39;: i} for i in remove_cost()],<br>    style= { <br>       &#39;width&#39;: &#39;50%&#39;,<br>       &#39;text-align&#39;:&#39;center&#39;,<br>       &#39;font-size&#39; :&#39;large&#39;,<br>       &#39;font-weight&#39; : &#39;bold&#39;,<br>       &#39;font-family&#39; : &quot;DejaVu Sans Mono, monospace&quot;}),</pre><pre>dcc.Graph( <br>    id = &#39;bar_graph&#39;, <br>    style= { &#39;width&#39;: &#39;80%&#39;, <br>       &#39;height&#39;: &#39;800px&#39;})</pre><pre>  ])</pre><p>As you can see in the code snippet above, the html.div container takes a list of dcc components which have their own properties. Both elements have an id property that we will need for the callback function and an optional style property. The styling of each element can be customised using CSS. The full reference for CSS arguments can be found <a href="https://developer.mozilla.org/en-US/docs/Web/CSS">here</a>.</p><p>3.)<strong> Setting up the callback property</strong></p><p>The callback always begins with defining the input and output. Specific properties of components within the app.layout are associated with being inputs and outputs. The first argument for each input/output tuple begins with the property id followed by the component property that informs the argument.</p><p>Since you want the user to select a value in the dropdown which will then be used to segment the dataset and render the graph, you need to assign the input and output as described below.</p><pre>@app.callback(</pre><pre>Output(&quot;bar_graph&quot;, &quot;figure&quot;),<br>Input(&quot;car_attribute_dropdown&quot;, &quot;value&quot;),</pre><pre>)</pre><p>4.)<strong> Setting up the callback function</strong></p><p>Next you need to define a function which would take the input argument from the callback and return the output. Here, you can essentially reuse the same function as when creating a static plot.</p><pre>def make_grouped_plot(attribute):</pre><pre><strong>#an if statement to handle if no value is selected in dropdown and None is passed</strong></pre><pre>  if attribute is None:<br>      attribute = &#39;Car Brand&#39;</pre><pre><strong>#creating the aggregated view of the selected dropdown value</strong></pre><pre>  df = pd.DataFrame(car_inventory.groupby(attribute<br>[&#39;Cost&#39;].agg({&#39;sum&#39;, &#39;size&#39;}).reset_index()).rename(columns= {&#39;size&#39; : &#39;Unit&#39;, &#39;sum&#39;: &#39;Potential Revenue&#39;})</pre><pre><strong>#create figure with secondary y-axis</strong></pre><pre>   fig = make_subplots(specs=[[{&quot;secondary_y&quot;: True}]])</pre><pre><strong>#with plotly.go, each trace needs to be added into the figure separately</strong></pre><pre>   fig.add_trace(go.Bar(x=df[attribute], y=df[&#39;Unit&#39;], name=&#39;Unit Count&#39; ,marker_color = &#39;#43B02A&#39;,offsetgroup=1 ,),secondary_y=False)</pre><pre>   fig.add_trace(go.Bar(x=df[attribute], y=df[&#39;Potential Revenue&#39;], name=&#39;Potential Revenue&#39; ,marker_color = &#39;#00A3E0&#39;,offsetgroup=2 ,hovertemplate = &#39;%{y:$,.0f}&#39;), secondary_y=True)</pre><pre><strong>#change layout preferences</strong></pre><pre>   fig.update_layout(<br>     barmode=&#39;group&#39;,<br>     font_size = 20,<br>     hovermode=&quot;x unified&quot;,</pre><pre><strong>#set y-axes titles</strong></pre><pre>   fig.update_yaxes(title_text=&quot;Potential Revenue: &lt;b&gt;Cost (in $) &lt;/b&gt; &quot;, secondary_y=True)</pre><pre>   fig.update_yaxes(title_text=&quot;Unit &lt;b&gt;Count&lt;/b&gt;&quot;, secondary_y=False)</pre><pre>   return fig</pre><p>When you run your script from terminal, you should be able to view your dashboard within the browser by entering your local host IP address.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZGcAEIi3YECoILlHaV%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZGcAEIi3YECoILlHaV%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZGcAEIi3YECoILlHaV%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="264" frameborder="0" scrolling="no"><a href="https://medium.com/media/a275b5cd07fd1c22156dcd63d9013938/href">https://medium.com/media/a275b5cd07fd1c22156dcd63d9013938/href</a></iframe><p>Exploring our fictional car dealership data, we can see in the example above that the potential revenue is greater for blue and electric cars. Getting this macro view can help guide business decisions such as determining the best marketing strategy or forecasting perspective sales.</p><p>In conclusion, I have provided a guide to created a simple interactive bar chart with a duel-Y axis in Plotly Dash. I hope that this article has also highlighted some of the benefits to providing business stakeholders with dynamic plots.</p><p>For full implementation code, please check gist below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a0a1ee2383752757f21e26a72872cb/href">https://medium.com/media/18a0a1ee2383752757f21e26a72872cb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62dee190021" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grouped bar chart with duel y-axis using Python and Plotly (Part 1)]]></title>
            <link>https://medium.com/@assel.kash/grouped-bar-chart-with-duel-y-axis-using-python-and-plotly-part-1-35cb48e063ec?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/35cb48e063ec</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[visualisation]]></category>
            <category><![CDATA[plotly]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 21:16:15 GMT</pubDate>
            <atom:updated>2022-03-25T15:40:37.468Z</atom:updated>
            <content:encoded><![CDATA[<p>How data is visualised can have a big impact on how it is interpreted. The most meaningful insights can be rapidly overlooked when key metrics are presented in the wrong format. Recently, I was building a dashboard using <a href="https://plotly.com/dash/">Plotly Dash</a> and I had a clear idea of what sort of visualisation I wanted; a simple grouped bar chart with a Y-axis on either side to accommodate two different metrics.</p><p>Since I was presenting categorical data and wanted the audience to make between and within-group comparisons, I felt that the above format would help the audience to appreciate the full picture whereas using the more simplified solution of presenting the same information in subplots and comparing side-by-side would be dilute the intended impact of the analysis.</p><p>Having used Plotly for visualisations before, I anticipated that my desired output would be a quick solve but this simple task took a deceptively long time and a lot of digging. There are two ways of rendering visualisations using Plotly. There is the Plotly Graph Objects library (plotly.go) and the Plotly Express Module (plotly.px). Despite being easier to implement and more user friendly, Plotly Express has its limitations, one of which is that it<strong> does not support dual axis plots </strong>(something I wish I knew)<strong>. </strong>So to be able to get the desired graph , I will share my solution using plotly.go and do a deep dive into some arguments that are crucial to include for a successful implementation.</p><p>I have split this post into a two part release. This first part will provide the solution to create a static simple grouped bar chart with a duel y-axis whereas in part 2 I will cover how to create a dynamic version of the same visualisation within Plotly Dash utilising a dropdown to change which variables are presented.</p><p><strong>The Use Case</strong></p><p>A car dealership wants to compare the number of car units they have and understand the potential revenue that can be gained by selling those cars, split out by various attributes.</p><p>First step is to import the necessary libraries for the task and create the a dummy dataset for our fictional car dealership, which benefits from some suspiciously cheap cars…</p><pre><strong>#import required libraries</strong></pre><pre>import pandas as pd<br>import numpy as np<br>import plotly.graph_objs as go<br>import plotly.express as px<br>from plotly.subplots import make_subplots<br>import random<br>from datetime import datetime, timedelta</pre><pre><strong>#create dummy data</strong></pre><pre>car_inventory = pd.DataFrame({&#39;Car Brand&#39;: random.choices([&#39;Tesla&#39;, &#39;Toyota&#39;, &#39;Kia&#39;, &#39;Honda&#39;, &#39;Volvo&#39;, &#39;Skoda&#39;], k = 1000)})</pre><pre>car_inventory[&#39;Fuel Type&#39;] = random.choices([&#39;Electric&#39;, &#39;Diesel&#39;, &#39;Hybrid&#39;, &#39;Petrol&#39;], k = len(car_inventory))<br>car_inventory[&#39;Color&#39;] = random.choices([&#39;White&#39;, &#39;Blue&#39;, &#39;Silver&#39;, &#39;Black&#39;], k = len(car_inventory))</pre><pre><strong>#our fictional car dealership deals mainly with new cars, so lets assign weights to this attribute where the probability of a car within the inventory being new is 0.8</strong></pre><pre>car_inventory[&#39;New/Used&#39;] = np.random.choice([&#39;New&#39;, &#39;Used&#39;],len(car_inventory), p = [0.8,0.2])</pre><pre>car_inventory[&#39;Cost&#39;] = random.sample(range(2000, 15000), len(car_inventory))</pre><pre><strong>#pick random date from last 90 days for car purchase</strong></pre><pre>def random_date():<br>    start = datetime.now()<br>    end = start + timedelta(days=90)<br>    random_date = start + (end - start) * random.random()<br>    return random_date</pre><pre>car_inventory[&#39;Purchase Date&#39;] = car_inventory[&#39;Cost&#39;].apply(lambda x: random_date().strftime(&#39;%Y/%m/%d&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*4ypzMD12u27W5aetPmV2rg.png" /><figcaption>Screenshot of fictional car dealership inventory</figcaption></figure><p>The above dataset gives us an itemised inventory of what cars our fictional dealership might have in stock. Within the code snippet below, we create an aggregated view of how many car units there are and the cost split by the car brand.</p><pre>car_unit_cost_groupby = pd.DataFrame(car_inventory.groupby(&#39;Car Brand&#39;)[&#39;Cost&#39;].agg({&#39;sum&#39;, &#39;size&#39;}).reset_index()).rename(columns= {&#39;size&#39; : &#39;Unit&#39;, &#39;sum&#39;: &#39;Potential Revenue&#39;})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*97HSta1D8F1S_fpUbzp7KQ.png" /><figcaption>Total units in stock and potential cumulative revenue, split according to brand</figcaption></figure><p>Now we can use the function below to plot the aggregated data into a grouped bar chart, with unit count displayed on the left axis and associated potential on the right.</p><pre>def make_grouped_plot(df, attribute):<br>    <br>    <strong>#create figure with secondary y-axis</strong></pre><pre>    fig = make_subplots(specs=[[{&quot;secondary_y&quot;: True}]])<br>    <br><strong>    #with plotly.go, each trace needs to be added into the figure separately</strong></pre><pre>fig.add_trace(go.Bar(x=df[attribute], y=df[&#39;Unit&#39;], name=&#39;Unit Count&#39; ,marker_color = &#39;#43B02A&#39;,offsetgroup=1 ,), secondary_y=False)<br>    fig.add_trace(go.Bar(x=df[attribute], y=df[&#39;Potential Revenue&#39;], name=&#39;Potential Revenue&#39; ,marker_color = &#39;#00A3E0&#39;,offsetgroup=2 ,hovertemplate = &#39;%{y:$,.0f}&#39;), secondary_y=True)</pre><pre><strong>#change layout preferences</strong></pre><pre>    fig.update_layout(<br>    barmode=&#39;group&#39;,<br>    font_size = 14,<br>    hovermode=&quot;x unified&quot;,<br>    )<br>    <br>  <strong>  #set y-axes titles</strong></pre><pre>    fig.update_yaxes(title_text=&quot;Potential Revenue: &lt;b&gt;Cost (in $) &lt;/b&gt; &quot;, secondary_y=True)<br>    fig.update_yaxes(title_text=&quot;Unit &lt;b&gt;Count&lt;/b&gt;&quot;, secondary_y=False)<br>    <br>    fig.show()<br>    <br>make_grouped_plot(car_unit_cost_groupby, &#39;Car Brand&#39;)</pre><p>The output from the function looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4YIOHOLcBcc_PxbMBahjA.png" /><figcaption>Screenshot of the output for the make_grouped_plot() function</figcaption></figure><p><strong>Crucial arguments</strong></p><p>Now I want to highlight some of the key arguments from the above function that allow the graph to render successfully.</p><pre>make_subplots(specs=[[{&quot;secondary_y&quot;: True}]])</pre><p>The secondary_y parameter provides the argument that the subplot layout should have a secondary access positioned on the right.</p><pre>offsetgroup=1</pre><p>Setting a different offset group for the different traces is crucial <strong>otherwise the bars will be positioned on top of each other.</strong> Note this parameter is associated with go.Bar.</p><pre>secondary_y=True</pre><p>This argument sets which trace is associated with the secondary axis. Note that this parameter is for fig.add_trace().</p><pre>barmode=&#39;group&#39;</pre><p>This is a layout parameter without which the bars will be stacked on top of each other rather than grouped.</p><pre>hovertemplate = &#39;%{y:$,.0f}&#39; and hovermode=&#39;x unified&#39;</pre><p>These two arguments dictate the look and feel of the hover box in the plotly graph. To customise the formate, the go.Bar parameter hovertemplate can be used and hovermode parameter in fig.update_layout presents data in a neater way.</p><p>In p<a href="https://medium.com/@assel.kash/grouped-bar-chart-with-duel-y-axis-using-python-and-plotly-part-2-62dee190021">art 2 </a>,I will discuss how to bring this visualisation to life with the help of Plotly Dash core components, specifically utilising their dropdown function to dynamically change which metrics are shown within the bar chart.</p><p>For the full code please refer to the gist below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef7412adaa96673664fb97a1fc6443d/href">https://medium.com/media/4ef7412adaa96673664fb97a1fc6443d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35cb48e063ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update a file in Google Sheets via API using Postman and Python Requests]]></title>
            <link>https://medium.com/@assel.kash/update-a-file-in-google-sheets-via-api-using-postman-and-python-requests-d03aff6dc0eb?source=rss-60daae96d369------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03aff6dc0eb</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[google-sheet-api]]></category>
            <dc:creator><![CDATA[Assel Kashkenbayeva, PhD]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 14:19:52 GMT</pubDate>
            <atom:updated>2022-03-15T19:22:36.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Sheets can be a useful tool for people to share reports and perform quick analysis. To share my work with colleagues, I would find that I would have to take several manual steps to get work transferred from my workspace to Google Sheets to allow others to view the reports. Finding this process long and cumbersome, I decided to automate it.</p><p>Here I present a practical guide how to update a file in Google Sheets via API.</p><p>Before I go into it, as an FYI, Google has comprehensive documentation on how to use <a href="https://developers.google.com/sheets/api/quickstart/python">Google Sheets API</a> (and other Google Cloud APIs) which is primarily reliant on the use of their client libraries. However, for various reasons, I decided to do a basic implementation without it so this guide uses Postman and Python Requests instead.</p><p><strong>1) Setup in Google Console</strong></p><p>For the first step, you need to set up a project in <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><p>Make sure you are logged into your Google account and go to the Cloud Console. Within the navigation bar on the top left you will see ‘<strong>Select a project</strong>’ with a little arrow pointing down <strong><em>(1)</em></strong>. Click on that and create a new project by clicking the button on the right in the pop-up window <strong><em>(2)</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGEzrO0aLFA6I4tYtRDzcA.png" /><figcaption>Screenshot to show setup of new project in Google Cloud Console</figcaption></figure><p>Give your project a name and click ‘<strong>Create’</strong>. Now you should be able to select your project when you click ‘<strong>Select a project</strong>’ in the navigation bar.</p><p>Once your project is selected, it will take you to the main dashboard of your project. From there, on the left-hand side select ‘<strong>API and services</strong>’ and then select <strong>‘Enabled APIs and services</strong>’ from the dropdown. This view presents you with a breakdown of all APIs enabled for that particular project.</p><p>From here, click the blue ‘<strong>Enable API and services</strong>’ button below the navigation bar<em> </em><strong><em>(3)</em>. </strong>Find Google Sheets API in the following window and click ‘<strong>Enable’</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c51xAvIgeckCFOvmXAx0BQ.png" /><figcaption>Screenshot to show how to enable APIs and services for a selected project in Google Cloud Console</figcaption></figure><p>After this step, you will be redirected to a screen that provides the metrics for the enabled API. The next step is to create credentials. These credentials ensure that you can access the right data and authorise/authenticate your API requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYwvkLM7tcpTbEeowKFxMg.png" /><figcaption>Screenshot to show how to create credentials for enabled API</figcaption></figure><p>On the right-hand side of the screen click the blue ‘<strong>Create credentials</strong>’ button <strong><em>(4)</em></strong>. Since you want to be able to read and write to Google Sheets, you need to select the ‘<strong>User Data</strong>’ radio button <strong><em>(5) </em></strong>which will implement the use of the more secure OAuth client flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOLFe7YdpDxzV1_osSeWZA.png" /><figcaption>Screenshot to show the selection of User Data when creating credentials for the selected API.</figcaption></figure><p>Give your app a name, email and fill in the rest of the required fields and once you reach the OAuth Client tab, select ‘<strong>Web Application’ </strong>and under ‘<strong>Authorised Redirect URL’</strong> add the following URL: <a href="https://oauth.pstmn.io/v1/callback">https://oauth.pstmn.io/v1/callback</a><strong>,</strong> This is the call-back URL for Postman, a tool which you will be using to get all the right access and refresh tokens to be able to make an API call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUHNIxpQCageEQ5bl8WuEQ.png" /><figcaption>Screenshot to show the callback URI format</figcaption></figure><p>Click ‘<strong>Create’</strong> and you should now get a pop-up with your Client ID and Client<strong> </strong>Secret. Save these two strings somewhere safe, since you will need them in the next step.</p><p>Before you navigate away from the pop up, click the ‘<strong>OAuth consent screen</strong>’ link (or select it from the menu on the left) and make sure you add your Google email to test users. This will ensure you have the right access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZE6SFD1NZu5WkutV7RSnyA.png" /><figcaption>Screenshot to show pop-up with Client ID and Client Secret for the enabled API in selected project</figcaption></figure><p><strong>2)</strong> <strong>Setting up a Postman collection using the Client ID and Client Secret</strong></p><p><a href="https://www.postman.com/">Postman</a> is great resource to test out and work with APIs. You will use the tool to get exchange your Client ID<strong> </strong>and Client Secret for access and refresh tokens which are used to authenticate the API calls you will be making to Google Sheets API.</p><p>Within Postman, set up a ‘<strong>New Collection</strong>’ from the<strong> </strong>Collections tab on the left and for authorization type, select ‘<strong>OAuth 2.0’</strong> <strong><em>(7)</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWpK1STptAq6r1EEZfLfzQ.png" /><figcaption>Screenshot setting up Postman Collection</figcaption></figure><p>This new collection should appear on the left-hand side and below it select ‘<strong>Add a request</strong>’ button. From there, navigate to the Auth tab and again select ‘<strong>OAuth 2.0’</strong> from the dropdown for type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3DQEXJ4CWlinpImdclQjg.png" /><figcaption>Screenshot to show selection for making an OAuth 2.0 request</figcaption></figure><p>The request should be set up with the following details:</p><pre><strong>Type: </strong>OAuth 2.0<br><strong>Add Authorization data to: </strong>Request URL<br><strong>Access Token:</strong> Avaliable Tokens<br><strong>Header Prefix:</strong> Bearer<br><strong>Token Name: </strong>&lt;your token name&gt;<br><strong>Grant Type: </strong>Authorization Code<br><strong>Callback URL:</strong> <a href="https://oauth.pstmn.io/v1/callback">https://oauth.pstmn.io/v1/callback</a><br><strong>Auth URL:</strong> <a href="https://accounts.google.com/o/oauth2/auth?access_type=offline">https://accounts.google.com/o/oauth2/auth?access_type=offline</a><br><strong>Access Token URL: </strong><a href="https://oauth2.googleapis.com/token">https://oauth2.googleapis.com/token</a><br><strong>Client ID: </strong>&lt;your client ID from previous step&gt;<br><strong>Client Secret: </strong>&lt;your client Secret from previous step&gt;<br><strong>Scopes:</strong> <a href="https://www.googleapis.com/auth/spreadsheets">https://www.googleapis.com/auth/spreadsheets</a><br><strong>State: </strong>&lt;random string&gt;<br><strong>Client Authentication: </strong>Send as basic Auth Header</pre><p><strong>Some important points:</strong></p><p>1) Scopes are what manage what kind of access you have when using the API, it is important to<strong> </strong>pick the right ones for your own use case. Please refer to <a href="https://developers.google.com/identity/protocols/oauth2/scopes">this documentation</a> about the different scopes for Google Cloud APIs.</p><p>2) When setting up an automated pipeline, you do not want to have to authorize every time you make an API call. To make an API call, you need an access token and Google access tokens have a 1-hour life span. If it expires, you will have to do another Postman request to get a new access token.</p><p>To solve this issue, you need to receive a<strong> </strong>refresh token<strong> </strong>with your first request. This refresh token is valid for 1 year<strong> </strong>and can be used to retrieve a fresh access token whenever making an API call. It is important to set it up correctly, as otherwise the request will not return a refresh token. <a href="https://myaccount.google.com/u/0/permissions">Check</a> that your app doesn’t have access to your account prior to making this first call. If you can see your app name under the ‘Third-party apps with account access’ tab, remove access before making this call. Additionally, ensure that the Auth URL in the request above has the query parameter <em>access_type=offline</em><strong> </strong>appended to the end (as shown above). The OAuth 2.0 request will only return a refresh token on first authorization of the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ro4jEJuo8V1z5o4nSJ0ag.png" /><figcaption>Screenshot to show consent screen for allowing your app to access your account via the Google Sheets API</figcaption></figure><p>Once all the fields are complete, click the orange ‘<strong>Get New Access Tokens</strong>’ button at the bottom. You will be presented with a pop-up window which will take you through to the authorization process.</p><p>Log into your account (this should be the same one as you specified under the Test Users in the Google Cloud Console) and click ‘<strong>Allow’</strong>. Once this has gone through, you will be able to see your access details within Postman, including a <em>refresh_token</em> with the associated scopes. To check everything is set up right, you can <a href="https://myaccount.google.com/u/0/permissions">check the permissions</a> for your Google account and you should see your app name listed below the ‘Third-party apps with access to account’ subtitle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjAoHClXMYv1WDQZHwCMuQ.png" /><figcaption>Screenshot to show the response to the OAuth 2.0 request in Postman</figcaption></figure><p>For the next part, you will need to take note of the <em>refresh_token</em> from this response as well as your Client ID<strong> </strong>and Client Secret which were used to generate this request.</p><p><strong>3) Exchanging the refresh token for an access token.</strong></p><p>Import the following libraries into your Jupyter Notebook or .py file since you will need them to make your first API call and assign the Client ID, Client Secret and refresh token from the previous steps to variables (in string format). These credentials should be kept safe, it is best to save these stored in a separate file or as secure environmental variables. Purely for ease of demonstration, I will directly assign these credentials to variables below but please note, this is not good practice.</p><pre>import requests #library used to make API requests with Python<br>import json #to read and write json formatted text in Python<br>import pandas as pd<br>import os</pre><pre>client_id_google = &#39;your_client_id_in_string_format&#39;<br>client_secret_google = &#39;your_client_secret_in_string_format&#39;<br>refresh_token_google = &#39;your_refresh_token_in_string_format&#39;</pre><p>Now you have everything you need to be able to request an exchange of your refresh token for an access token.</p><pre>#this is the base url to POST a request to be able to get an access <br>token</pre><pre>url = &quot;<a href="https://www.googleapis.com/oauth2/v4/token">https://www.googleapis.com/oauth2/v4/token</a>&quot;</pre><pre>#note the payload and headers are formatted as a dict</pre><pre>payload = {<br>    &#39;client_id&#39; : client_id_google ,<br>    &#39;client_secret&#39; : client_secret_google,<br>    &#39;refresh_token&#39; : refresh_token_google ,<br>    &#39;grant_type&#39; : &#39;refresh_token&#39;, <br>}</pre><pre>headers = {<br>    &#39;Content-Type&#39;: &quot;application/x-www-form-urlencoded&quot;,<br>    &#39;cache-control&#39;: &quot;no-cache&quot;,<br>    }</pre><pre>#the response returns the response code whereas the response.text returns the associated json with the request</pre><pre>response = requests.request(&quot;POST&quot;, url, data=payload, headers=headers)</pre><pre>#json.loads is used to parse the json object returned with the response</pre><pre>response_dict = json.loads(response.text)</pre><pre>#the values can be accessed like a dict object</pre><pre>google_access_token = response_dict[&#39;access_token&#39;]</pre><p>Now we have our access token, we can finally proceed to updating a Google Sheets file.</p><p>4.) <strong>Making the update API call</strong></p><p>In this article, I am showing how to specifically update a pre-existing Google Sheet rather than create a new one (although the basic principles are transferrable). First you must go to your Google Drive and from the sheet that you are interested in updating, extract the sheet ID from the URL. For example if the URL for your sheet is <a href="https://docs.google.com/spreadsheets/d/12345678910ABC/edit">https://docs.google.com/spreadsheets/d/12345678910ABC</a> the sheet ID would be ‘12345678910ABC’.</p><p>Together with the access token you retrieved in the previous call and the sheet ID, we can now perform a request to update the sheet with the desired data. The below example uses a dummy pandas dataframe:</p><pre>#dummy dataframe to update sheet with</pre><pre>update_df = pd.DataFrame({&#39;col1&#39;: [1,2,3], &#39;col2&#39;: [4,5,6], &#39;col3&#39;: [7,8,10]})</pre><pre>#sheet ID of Google Sheet you want to update</pre><pre>sheetId = &#39;your_sheet_ID&#39;</pre><pre>#the base Google Sheet API URL is appended with the sheetId and ends with &#39;/values/{range}&#39;</pre><pre>google_put_url = &#39; https://sheets.googleapis.com/v4/spreadsheets/&#39; + sheetId + &#39;/values/{range}&#39;</pre><pre>#the headers are formatted as a dict with the access token which was retrieved from the previous call adding to the Authorization string. <br>#the accept header is not necessary for the write call but required when a read operation is done. This parameter specifies how the response should be formatted. </pre><pre>google_put_headers = {<br>  &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  &#39;Authorization&#39;: &#39;Bearer %s&#39; %google_access_token,<br>  &#39;Accept&#39;: &#39;application/json&#39;<br>}</pre><pre>#the range parameter of &#39;Sheet1!A001&#39; specifies that all sheet should be used</pre><pre>google_put_params  ={<br>  &#39;valueInputOption&#39;: &#39;USER_ENTERED&#39;,<br>    &quot;range&quot;: &quot;Sheet1!A001&quot;,<br>    }</pre><pre>#the dataframe that will be used to update the sheet needs to be formatted correctly for Google Sheets to receive it as input</pre><pre>result = [update_df.columns.values.tolist()]<br>result.extend(update_df.values.tolist())</pre><pre>#it is crucial to convert the dataframe into a dictionary as shown below and to use json.dumps so that the request body can received by the api. <strong>There will be an error if json.dumps() is not used and the input is manually formatted into a json. </strong></pre><pre>request_body = json.dumps(  {&quot;majorDimension&quot;: &quot;ROWS&quot;,&quot;values&quot;: result})</pre><pre>#to update the google sheet a PUT request needs to be used</pre><pre>google_response = requests.request(&quot;PUT&quot;, google_put_url, headers=google_put_headers,params= google_put_params, data=request_body )<br>google_response_pretty_json = json.loads(google_response.text)</pre><pre>#this print statement formats the response nicely she if the operation has been successful returns the sheet ID and update details</pre><pre>print(json.dumps(google_response_pretty_json, indent=4))</pre><p>Finally, check the sheet with the above sheet ID and it should be updated instantly.</p><p>With this API it is possible to update specific ranges or cells within a sheet and perform other more complex operations as well as append rather than replace data. For more details, please refer to the <a href="https://developers.google.com/sheets/api/guides/batchupdate">Google Sheet API documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03aff6dc0eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>