<?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 Lucas de Brito Silva on Medium]]></title>
        <description><![CDATA[Stories by Lucas de Brito Silva on Medium]]></description>
        <link>https://medium.com/@lucasbsilva29?source=rss-5289873d4c37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6QCEfXg7y8ZeQAPqTCEYSA.jpeg</url>
            <title>Stories by Lucas de Brito Silva on Medium</title>
            <link>https://medium.com/@lucasbsilva29?source=rss-5289873d4c37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 22:30:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucasbsilva29/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[From Pixels to Vectors: Image Embeddings in Practice]]></title>
            <link>https://levelup.gitconnected.com/from-pixels-to-vectors-image-embeddings-in-practice-835c57d4f361?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/835c57d4f361</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-embedding]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 15:49:39 GMT</pubDate>
            <atom:updated>2026-10-19T15:49:39.142Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to optimize storage with embeddings and learn the technique through a practical project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6UaEDWFcNtq5SenT" /><figcaption>Photo by <a href="https://unsplash.com/@nadineshaabana?utm_source=medium&amp;utm_medium=referral">Nadine E</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous article, we learned a little more about embeddings, how context became encoded in these representations following advances brought by Transformers, and how to measure distances between words.</p><p><a href="https://levelup.gitconnected.com/how-to-measure-similarity-between-sql-queries-using-embeddings-36a74b4beabf">How to Measure Similarity Between SQL Queries Using Embeddings</a></p><p>In this article, we will take things one step further by applying the same principle to images.</p><h4>But what about images?</h4><p>I have always enjoyed learning through practical examples. So, we will work on something we can implement and use in our daily lives.</p><p>Unlike the days when an analog film gave us only 36 shots, the number of pictures we can take with our phones today is virtually unlimited. It is not unusual to find a folder containing hundreds or thousands of files — or someone whose phone storage is full because of an overcrowded photo gallery. In these situations, we often have consecutive pictures of the same scene, the same image in different resolutions, or files that look very similar.</p><p>With only a few images, we can open them one by one and decide which ones to keep. However, as the collection grows, manual analysis becomes tedious and difficult to scale. This is where image embeddings can help us.</p><h4>Isn’t an image just a matrix of pixels?</h4><p>To a computer, an image is already a set of numbers: a matrix formed by its pixel values. However, comparing these values directly is not very robust, because compression, resizing, or a small crop can change many pixels without changing what we actually see.</p><p>Therefore, the right comparison depends on the question we want to answer:</p><p>- Are the files the same?<br>- Do the images appear to be the same photograph?<br>- Do the images represent similar concepts?</p><p>A cryptographic hash such as SHA-256 helps answer the first question. A perceptual hash such as pHash is useful for the second. Embeddings are especially interesting for the third.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Ku32DH-V8vwMTQaQ.png" /><figcaption>From left to right: an original image, a compressed one, and a different image (featuring the same person).</figcaption></figure><h4>What is an image embedding?</h4><p>As explained in the <a href="https://medium.com/gitconnected/how-to-measure-similarity-between-sql-queries-using-embeddings-36a74b4beabf">first article</a>, an embedding transforms information into a vector representation that preserves important characteristics of its meaning. In that case, we worked with text and queries; now, we will do the same with images.</p><p>After passing through an encoder, each photograph is represented by a vector. When we place these vectors in the same space, we can calculate how close they are to one another: beach images tend to be close to other beach images, while car photographs may occupy a different region. The same photograph at different resolutions tends to be even closer, although the result depends on the encoder being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*R5dvUMbG5WBtlrxZ.png" /><figcaption>Representation of a semantic feature space for images.</figcaption></figure><p>To create these representations, we need to choose a model capable of understanding visual features. This is where CLIP comes in.</p><h4>CLIP: bringing images and text closer together</h4><p>In this experiment, we will use the clip-ViT-B-32 model, available through the sentence-transformers library.</p><p>CLIP is particularly interesting because it was trained to bring matching images and text descriptions closer together in a shared space. This creates possibilities that go beyond comparing two photographs. In a more complete application, we could search for images using a sentence such as “a dog playing in the park,” even if that text had never been stored in the file’s metadata.</p><p>In our case, we will focus on comparing images. We will use CLIP’s encoder to generate the embeddings and place them in a vector space, where we can calculate the similarity between the images.</p><h3>Let’s get to the project</h3><p>Now that we have defined the problem and understand how embeddings can help, we will use Python 3.10 or later to build our solution. We will also need a few libraries for image processing, mathematical operations, and working with Transformers.</p><p>Although I will explain the main steps below, the complete project is available on GitHub:</p><p><a href="https://github.com/Lucs1590/image-embedding-lab">GitHub - Lucs1590/image-embedding-lab</a></p><p>We begin by locating the images that will be processed. The code scans the selected folder and its subdirectories, considering formats such as JPG, PNG, WEBP, BMP, and TIFF.</p><pre>SUPPORTED_EXTENSIONS = {<br>    &quot;.jpg&quot;, &quot;.jpeg&quot;, &quot;.png&quot;, &quot;.webp&quot;,<br>    &quot;.bmp&quot;, &quot;.tif&quot;, &quot;.tiff&quot;<br>}<br><br>def list_images(input_dir: Path) -&gt; list[Path]:<br>    paths = sorted(<br>        path<br>        for path in input_dir.rglob(&quot;*&quot;)<br>        if path.is_file()<br>        and path.suffix.lower() in SUPPORTED_EXTENSIONS<br>    )<br>    if len(paths) &lt; 2:<br>        raise ValueError(<br>            f&quot;Esperava ao menos 2 imagens em {input_dir}, &quot;<br>            f&quot;encontrei {len(paths)}.&quot;<br>        )<br>    return paths</pre><h4>Loading the images correctly</h4><p>Before passing an image to the model, we perform two important operations. The first is to respect its EXIF orientation, preventing photographs taken with a phone from being processed with the wrong rotation. The second is to convert it to RGB, ensuring a consistent input format.</p><pre>def load_rgb(path: Path) -&gt; Image.Image:<br>    with Image.open(path) as image:<br>        return ImageOps.exif_transpose(image).convert(&quot;RGB&quot;)</pre><p>This function may look simple, but it prevents several unexpected behaviors. In a more robust application, we would also need to handle corrupted files, unexpected formats, and excessively large images during decoding.</p><h4>Generating the embeddings</h4><p>With the images prepared, we load `clip-ViT-B-32` and call its `encode` method. If a CUDA-compatible GPU is available, it will be used. Otherwise, the processing will run on the CPU, although this computationally intensive step may take considerably longer.</p><pre>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model = SentenceTransformer(&quot;clip-ViT-B-32&quot;, device=device)<br><br>batch_embeddings = model.encode(<br>    images,<br>    batch_size=batch_size,<br>    normalize_embeddings=True,<br>    show_progress_bar=False,<br>)</pre><p>The normalize_embeddings=True parameter makes each vector have a norm of 1. This simplifies the calculation performed later, because the dot product of two normalized vectors is equivalent to their cosine similarity.</p><p>In simple terms, each image is no longer just a grid of pixels: it becomes a point in a high-dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4DIox0gn2-X3r9GI.png" /><figcaption>Image-to-vector conversion.</figcaption></figure><h4>Necessary optimizations</h4><p>An initial version of the project could load every image into memory, generate all the embeddings, and then compare every vector. This works for a small example. However, as the volume grows, three problems quickly appear:</p><ul><li>the decoded images may exhaust the available RAM;</li><li>the complete set of embeddings also consumes memory;</li><li>an interruption may force the entire process to start again.</li></ul><p>To solve the first problem, <strong>we load only one batch of images at a time</strong>. It is important to understand that setting a batch_size in the model would not be enough if every photograph had already been opened and stored in a list before the method call.</p><pre>for begin in range(start, len(paths), batch_size):<br>    end = min(begin + batch_size, len(paths))<br>    images = [<br>        load_rgb(path)<br>        for path in paths[begin:end]<br>    ]<br>    try:<br>            batch_embeddings = model.encode(<br>                images,<br>                batch_size=batch_size,<br>                normalize_embeddings=True,<br>                show_progress_bar=False,<br>            )<br>    finally:<br>        for image in images:<br>            image.close()</pre><p>The finally block ensures that the files are closed even if a failure occurs during processing.</p><p>To address the second problem, we use numpy.memmap through the open_memmap method. Instead of keeping every embedding in RAM, we create a disk-backed array and write to it as each batch is completed.</p><pre>embeddings = np.lib.format.open_memmap(<br>    embeddings_path,<br>    mode=&quot;w+&quot;,<br>    dtype=np.float32,<br>    shape=(len(paths), dimension),<br>)<br><br>embeddings[begin:end] = np.asarray(<br>    batch_embeddings,<br>    dtype=np.float32,<br>)<br>embeddings.flush()</pre><p>As a result, memory usage is tied **primarily to the batch size rather than to the total number of images**.</p><p>Finally, we save a checkpoint at the end of each batch. It records the next position to be processed and allows the execution to resume after an interruption.</p><pre>checkpoint_path.write_text(<br>    json.dumps(<br>        {**expected, &quot;next_index&quot;: end},<br>        indent=2,<br>    ),<br>    encoding=&quot;utf-8&quot;,<br>)</pre><p>However, saving only the position would not be safe. If an image were added, removed, or modified, the vectors could become associated with the wrong files. For this reason, **the checkpoint also contains a fingerprint calculated from the file paths, sizes, and modification dates, along with the model being used.**</p><pre>def dataset_fingerprint(<br>    paths: list[Path],<br>    model_name: str,<br>) -&gt; str:<br>    digest = hashlib.sha256(model_name.encode())<br><br>    for path in paths:<br>        stat = path.stat()<br>        digest.update(<br>            f&quot;{path.resolve()}|{stat.st_size}|&quot;<br>            f&quot;{stat.st_mtime_ns}&quot;.encode()<br>        )<br><br>    return digest.hexdigest()</pre><p>These three decisions (batch processing, disk-backed storage, and validated checkpoints) do not change the purpose of the project, but they allow it to become more than a demonstration that works only with a small number of photographs.</p><h4>Cosine similarity</h4><p>Once all the images have been transformed into vectors, we can compare them. The metric we will use is cosine similarity, which measures the angle between two vectors:</p><pre>cosine_similarity(A, B) = (A · B) / (||A|| × ||B||)</pre><p>The more closely aligned the vectors are, the greater their similarity. Because our embeddings have already been normalized, the denominator is equal to 1. Therefore, we can perform the calculation using a matrix product:</p><pre>scores = left @ right.T</pre><p>However, we once again face a scalability problem. A matrix containing every possible combination among N images has dimensions of N × N. <strong>For 100,000 images, this would represent 10 billion entries, even before considering any other processing structures.</strong></p><p>For this reason, the implementation compares blocks of vectors and writes the resulting pairs directly to a CSV file:</p><pre>for left_start in range(0, n, comparison_batch_size):<br>    left_end = min(<br>        left_start + comparison_batch_size,<br>        n,<br>    )<br>    left = np.asarray(<br>        embeddings[left_start:left_end]<br>    )<br><br>    for right_start in range(<br>        left_start,<br>        n,<br>        comparison_batch_size,<br>    ):<br>        right_end = min(<br>            right_start + comparison_batch_size,<br>            n,<br>        )<br>        right = np.asarray(<br>            embeddings[right_start:right_end]<br>        )<br>        scores = left @ right.T</pre><p>This allows us to limit memory usage. It is important to note, however, that we are still performing all the comparisons. We have addressed the space problem, but the time complexity remains quadratic, or approximately O(N²).</p><p>For truly large collections, a natural evolution would be to use an approximate nearest neighbor index such as FAISS or HNSW and compare only the most likely neighbors of each image.</p><h4>Similarity does not mean duplication</h4><p>This brings us to an essential distinction: <strong>if two photographs have nearby embeddings, that does not necessarily mean they are identical.</strong></p><p>Two different pictures of a beach may have high semantic similarity. Two consecutive photographs of the same person may also be very close, even though each one captures a unique moment.</p><p>Therefore, we also use pHash, or perceptual hashing. Unlike a cryptographic hash, it is designed to produce similar results for images that look alike.</p><pre>hashes[begin:end] = [<br>    np.uint64(<br>        int(str(imagehash.phash(image)), 16)<br>    )<br>    for image in images<br>]</pre><p>The distance between two hashes is calculated by counting the number of differing bits:</p><pre>def phash_distance(<br>    a: np.uint64,<br>    b: np.uint64,<br>) -&gt; int:<br>    return int(int(a ^ b).bit_count())</pre><p>In the project, we classify a pair as probable_duplicate only when it meets two criteria simultaneously:</p><ul><li>very high embedding similarity;</li><li>a small perceptual distance.</li></ul><p>If only the first criterion is met, the pair is classified as semantically_similar.</p><pre>probable_duplicate = (<br>    score &gt;= duplicate_threshold<br>    and distance &lt;= max_phash_distance<br>)</pre><p>We use thresholds to make this classification, but they should only be treated as starting points. The best value depends on the model, the type of image, and the cost of each error. If a false positive could cause an important photograph to be lost, for example, the final decision must remain a human one.</p><p>A safer alternative would be to move candidate files to a quarantine folder, preserving a backup and allowing them to be reviewed before permanent deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kkWueaO7a7hpSg_B.png" /><figcaption>Classifications in example images.</figcaption></figure><h4>Visualizing the vector space</h4><p>A CLIP embedding has far more than two dimensions. Because we cannot display that space directly in a chart, we need to reduce its dimensionality.</p><p>The project supports PCA and UMAP. <strong>PCA performs a linear projection</strong> that aims to preserve as much variance as possible. <strong>UMAP, on the other hand, is a nonlinear technique</strong> that tends to preserve certain local relationships between points more effectively.</p><p>However, we must be careful when interpreting the resulting figure. **The chart is not the original space: it is a projection, and some information is inevitably lost during the transformation.**</p><p>Projecting the entire collection may also consume a large amount of memory. For this reason, we select a reproducible sample:</p><pre>rng = np.random.default_rng(7)<br>indices = np.sort(<br>    rng.choice(<br>        len(paths),<br>        size=min(max_points, len(paths)),<br>        replace=False,<br>    )<br>)<br>sample = np.asarray(embeddings[indices])</pre><p>We then apply the selected technique:</p><pre>points = umap.UMAP(<br>    n_components=2,<br>    n_neighbors=max(<br>        2,<br>        min(15, len(sample) - 1),<br>    ),<br>    metric=&quot;cosine&quot;,<br>    random_state=7,<br>).fit_transform(sample)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qafkeUaYzl3j4ERM.png" /><figcaption>Feature space with images after embedding.</figcaption></figure><p>Semantically related images are expected to appear in similar regions. However, the distance shown in the chart should not replace the metric calculated in the original vector space.</p><h4>CLIP or SigLIP?</h4><p>CLIP is a great choice for introducing multimodal embeddings, and it has broad support across libraries and examples. However, it is not the only option.</p><p><strong>SigLIP</strong> also learns relationships between text and images, but it uses a sigmoid loss instead of the softmax-based contrastive formulation used by CLIP. In practice, different versions of these models may produce different results depending on the domain, language, resolution, and available infrastructure.</p><p>We should not choose a model simply because it leads a particular benchmark. For this problem, it would be useful to build a small evaluation dataset containing:</p><ul><li>duplicate images with different compression levels and resolutions;</li><li>consecutive photographs of the same scene;</li><li>semantically similar images that should still be preserved;</li><li>visually similar but semantically different images;</li><li>real examples from the collection we want to organize.</li></ul><p>We could then evaluate precision and recall at different thresholds, along with latency, throughput, memory usage, and embedding size.</p><p><strong>Another important consideration is that vectors generated by different models do not necessarily belong to the same space. If the encoder changes, the collection must be processed again and its index rebuilt.</strong></p><h4>Conclusion</h4><p>By transforming images into vectors, we can work with characteristics that go beyond their individual pixels. This allows us to visualize relationships between photographs and identify candidates that may be consuming unnecessary storage.</p><p>However, this experiment also reveals an important distinction: <strong>semantic similarity and duplication are not the same thing. Embeddings help us find related images</strong>, while <strong>pHash adds a signal of perceptual similarity</strong>. Even when both are used, automatic deletion still requires caution, calibration, and a recovery strategy.</p><p>We also saw that a seemingly simple solution quickly introduces engineering challenges. <strong>Loading every image, building a complete similarity matrix, and projecting every vector may work in a small demonstration, but they do not scale.</strong> Batch processing, disk-backed arrays, and checkpoints make the experiment more robust.</p><p>More than just a way to reduce the size of a photo folder, working with image embeddings is a practical way to understand how multimodal models organize information. <strong>Images stop being mere matrices of pixels and begin to occupy a mathematical space where we can compare meaning and uncover relationships that would be difficult to discover by comparing their pixels directly.</strong></p><h4>References</h4><ul><li><a href="https://levelup.gitconnected.com/how-to-measure-similarity-between-sql-queries-using-embeddings-36a74b4beabf">How to Measure Similarity Between SQL Queries Using Embeddings</a></li><li><a href="https://arxiv.org/abs/2103.00020?source=post_page-----1b225b77cab3-----------------------------------------">Learning Transferable Visual Models From Natural Language Supervision</a></li><li><a href="https://arxiv.org/abs/2303.15343?source=post_page-----1b225b77cab3-----------------------------------------">Sigmoid Loss for Language Image Pre-Training</a></li><li><a href="https://www.sbert.net/examples/sentence_transformer/applications/image-search/README.html?source=post_page-----1b225b77cab3-----------------------------------------">Image Search - Sentence Transformers documentation</a></li><li><a href="https://arxiv.org/abs/1802.03426?source=post_page-----1b225b77cab3-----------------------------------------">UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835c57d4f361" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-pixels-to-vectors-image-embeddings-in-practice-835c57d4f361">From Pixels to Vectors: Image Embeddings in Practice</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[De pixels a vetores: Image Embeddings na prática]]></title>
            <link>https://medium.com/data-hackers/de-pixels-a-vetores-image-embeddings-na-pr%C3%A1tica-1b225b77cab3?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b225b77cab3</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-embedding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 20:34:37 GMT</pubDate>
            <atom:updated>2026-10-16T20:34:37.148Z</atom:updated>
            <content:encoded><![CDATA[<h4>Como otimizar o armazenamento usando embedding e aprender essa técnica na prática</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_En3S0kYB5dqMIfD" /><figcaption>Photo by <a href="https://unsplash.com/@dodancs?utm_source=medium&amp;utm_medium=referral">Dominik Dancs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>No artigo anterior, pudemos aprender um pouco mais sobre a técnica de <em>embedding</em>, como o contexto fica armazenado depois das inovações inerentes aos Transformers e como encontrar distâncias entre palavras.</p><p><a href="https://lucasbsilva29.medium.com/entendendo-dist%C3%A2ncia-entre-queries-dd039cdf6cbc">Entendendo distância entre queries</a></p><p>Neste artigo, vamos dar um passo adiante: aplicar o mesmo princípio ao domínio das imagens.</p><h4>Todavia, e para o domínio das imagens?</h4><p>Eu sempre gostei de aprender com algo prático. Sendo assim, vamos trabalhar com algo que possamos implementar e utilizar no dia a dia.</p><p>Diferentemente de antigamente, quando tínhamos apenas 36 fotos disponíveis em um filme analógico, atualmente as fotos tiradas com celulares são praticamente ilimitadas. Não é difícil encontrar uma pasta com centenas ou milhares de arquivos, ou alguém com a memória cheia por ter uma galeria lotada. Nesses cenários, é comum termos fotografias consecutivas da mesma cena, a mesma imagem em resoluções diferentes ou arquivos muito semelhantes.</p><p>Para poucas imagens, podemos abrir uma por uma e decidir o que manter. Todavia, à medida que esse conjunto aumenta, a análise manual torna-se cansativa e pouco escalável. É aqui que os embeddings de imagens podem nos ajudar.</p><h4>Uma imagem não é apenas uma matriz de pixels?</h4><p>Para o computador, uma imagem já é um conjunto de números: uma matriz formada pelos valores de seus pixels. Entretanto, comparar esses valores diretamente é pouco robusto, pois uma compressão, um redimensionamento ou um pequeno recorte pode alterar muitos pixels sem mudar aquilo que enxergamos.</p><p>Sendo assim, a comparação depende da pergunta que queremos responder:</p><ul><li>Os arquivos são exatamente iguais?</li><li>As imagens parecem ser a mesma fotografia?</li><li>As imagens representam conceitos semelhantes?</li></ul><p>Um hash criptográfico, como SHA-256, ajuda a responder à primeira pergunta. Um hash perceptual, como o pHash, é útil na segunda. Já os embeddings são especialmente interessantes para a terceira.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGVyL6KWeZGHcVf_Ga5n6A.png" /><figcaption>Da esquerda para a direita, uma imagem original, uma comprimida e uma diferente (com a mesma pessoa).</figcaption></figure><h4>E o que é um embedding de imagem?</h4><p>Como explicado <a href="https://medium.com/data-hackers/entendendo-dist%C3%A2ncia-entre-queries-dd039cdf6cbc">no primeiro artigo</a>, um embedding transforma uma informação em uma representação vetorial que preserva características importantes de seu significado. Naquele caso, trabalhamos com textos e queries e agora faremos o mesmo com imagens.</p><p>Depois de passar por um encoder, cada fotografia será representada por um vetor. Quando colocamos esses vetores no mesmo espaço, podemos calcular sua proximidade: imagens de praias tendem a ficar próximas de outras praias, enquanto fotografias de carros podem ocupar outra região. A mesma foto em resoluções diferentes tende a ficar ainda mais próxima, embora o resultado dependa do encoder utilizado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*XeGSXbHotQalSTS6N8cOWg.png" /><figcaption>Representação de um espaço de caracteristica semântico de imagens.</figcaption></figure><p>Para criar essas representações, precisamos escolher um modelo capaz de entender características visuais. É aqui que entra o CLIP.</p><h4>CLIP: aproximando imagens e textos</h4><p>Neste experimento, utilizaremos o modelo clip-ViT-B-32, disponível por meio da biblioteca sentence-transformers.</p><p>O CLIP é especialmente interessante porque foi treinado para aproximar imagens e descrições textuais correspondentes em um espaço compartilhado. Isso abre possibilidades que vão além da comparação entre duas fotos. Em uma aplicação mais completa, poderíamos procurar imagens usando uma frase como “um cachorro brincando no parque”, mesmo que esse texto não estivesse salvo nos metadados do arquivo.</p><p>No nosso caso, vamos concentrar o exemplo na comparação entre imagens e utilizaremos o encoder do clip para realizar os embeddings e depois teremos isso no espaço vetorial, onde poderemos calcular a similaridade entre as imagens.</p><h3>Vamos ao projeto?</h3><p>Agora que o problema está evidenciado e sabemos como os embeddings podem ajudar, vamos usar Python 3.10 ou superior para construir nossa solução. Algumas bibliotecas de processamento de imagens, cálculos matemáticos e uso de Transformers também serão necessárias.</p><p>Embora eu vá explicar as principais etapas logo abaixo, o projeto completo está disponível no GitHub:</p><p><a href="https://github.com/Lucs1590/image-embedding-lab">GitHub - Lucs1590/image-embedding-lab</a></p><p>Começamos localizando as imagens que serão processadas. O código percorre a pasta e seus subdiretórios, considerando formatos como JPG, PNG, WEBP, BMP e TIFF.</p><pre>SUPPORTED_EXTENSIONS = {<br>    &quot;.jpg&quot;, &quot;.jpeg&quot;, &quot;.png&quot;, &quot;.webp&quot;,<br>    &quot;.bmp&quot;, &quot;.tif&quot;, &quot;.tiff&quot;<br>}<br><br>def list_images(input_dir: Path) -&gt; list[Path]:<br>    paths = sorted(<br>        path<br>        for path in input_dir.rglob(&quot;*&quot;)<br>        if path.is_file()<br>        and path.suffix.lower() in SUPPORTED_EXTENSIONS<br>    )<br>    if len(paths) &lt; 2:<br>        raise ValueError(<br>            f&quot;Esperava ao menos 2 imagens em {input_dir}, &quot;<br>            f&quot;encontrei {len(paths)}.&quot;<br>        )<br>    return paths</pre><h4>Carregando as imagens corretamente</h4><p>Antes de passar uma imagem para o modelo, realizamos duas operações importantes. A primeira é respeitar sua orientação EXIF, evitando que fotografias feitas pelo celular sejam processadas rotacionadas. A segunda é convertê-la para RGB, garantindo uma entrada consistente.</p><pre>def load_rgb(path: Path) -&gt; Image.Image:<br>    with Image.open(path) as image:<br>        return ImageOps.exif_transpose(image).convert(&quot;RGB&quot;)</pre><p>Essa função parece simples, mas evita uma série de comportamentos inesperados. Em uma aplicação mais robusta, também seria importante tratar arquivos corrompidos, formatos inesperados e imagens excessivamente grandes durante o decode.</p><h4>Gerando os embeddings</h4><p>Com as imagens preparadas, carregamos o clip-ViT-B-32 e executamos seu método encode. Caso uma GPU compatível com CUDA esteja disponível, ela será utilizada. Caso contrário, o processamento acontecerá na CPU, mas como essa atividade é computacionalmente custosa, dificilmente concluirá.</p><pre>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model = SentenceTransformer(&quot;clip-ViT-B-32&quot;, device=device)<br><br>batch_embeddings = model.encode(<br>    images,<br>    batch_size=batch_size,<br>    normalize_embeddings=True,<br>    show_progress_bar=False,<br>)</pre><p>O parâmetro normalize_embeddings=True faz com que os vetores tenham norma igual a 1. Isso simplifica o cálculo posterior, pois o produto escalar entre dois vetores normalizados equivale à similaridade de cosseno.</p><p>De maneira simplificada, cada imagem deixa de ser apenas uma grade de pixels e passa a ocupar um ponto em um espaço de muitas dimensões.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0ZMu7xcZLevA2FapjOVBQ.png" /><figcaption>Transformação de imagem em vetor.</figcaption></figure><h4>Otimizações necessárias</h4><p>Uma primeira versão do projeto poderia carregar todas as imagens na memória, gerar todos os embeddings e então comparar todos os vetores. Para um exemplo pequeno, isso funciona. Todavia, quando o volume cresce, três problemas aparecem rapidamente:</p><ul><li>as imagens decodificadas podem esgotar a RAM;</li><li>o conjunto completo de embeddings também ocupa memória;</li><li>uma interrupção pode obrigar o processamento a começar novamente.</li></ul><p>Para resolver o primeiro problema,<strong> carregamos somente um lote de imagens por vez</strong>. É importante perceber que definir um batch_size no modelo não seria suficiente se todas as fotos já tivessem sido abertas e armazenadas em uma lista antes da chamada.</p><pre>for begin in range(start, len(paths), batch_size):<br>    end = min(begin + batch_size, len(paths))<br>    images = [<br>        load_rgb(path)<br>        for path in paths[begin:end]<br>    ]<br>    try:<br>            batch_embeddings = model.encode(<br>                images,<br>                batch_size=batch_size,<br>                normalize_embeddings=True,<br>                show_progress_bar=False,<br>            )<br>    finally:<br>        for image in images:<br>            image.close()</pre><p>O bloco finally garante que os arquivos sejam fechados, mesmo se ocorrer alguma falha durante o processamento.</p><p>Para o segundo problema, usamos numpy.memmap por meio do método open_memmap. Em vez de manter todos os embeddings na RAM, criamos um array mapeado em disco e escrevemos nele conforme os lotes são concluídos.</p><pre>embeddings = np.lib.format.open_memmap(<br>    embeddings_path,<br>    mode=&quot;w+&quot;,<br>    dtype=np.float32,<br>    shape=(len(paths), dimension),<br>)<br><br>embeddings[begin:end] = np.asarray(<br>    batch_embeddings,<br>    dtype=np.float32,<br>)<br>embeddings.flush()</pre><p>Assim, o uso de memória fica relacionado <strong>principalmente ao tamanho do lote, e não à quantidade total de imagens.</strong></p><p>Por fim, salvamos um checkpoint ao término de cada lote. Ele registra qual será a próxima posição processada e permite retomar a execução em caso de interrupção.</p><pre>checkpoint_path.write_text(<br>    json.dumps(<br>        {**expected, &quot;next_index&quot;: end},<br>        indent=2,<br>    ),<br>    encoding=&quot;utf-8&quot;,<br>)</pre><p>Todavia, salvar apenas a posição não seria seguro. Se uma imagem fosse incluída, removida ou alterada, poderíamos associar os vetores aos arquivos errados. Por esse motivo, <strong>o checkpoint também contém um fingerprint calculado a partir dos caminhos, tamanhos e datas de modificação dos arquivos, além do modelo utilizado.</strong></p><pre>def dataset_fingerprint(<br>    paths: list[Path],<br>    model_name: str,<br>) -&gt; str:<br>    digest = hashlib.sha256(model_name.encode())<br><br>    for path in paths:<br>        stat = path.stat()<br>        digest.update(<br>            f&quot;{path.resolve()}|{stat.st_size}|&quot;<br>            f&quot;{stat.st_mtime_ns}&quot;.encode()<br>        )<br><br>    return digest.hexdigest()</pre><p>Essas três decisões (processamento em lotes, armazenamento mapeado em disco e checkpoints validados) não mudam o objetivo do projeto, mas fazem com que ele deixe de ser apenas uma demonstração que funciona com poucas fotos.</p><h4>Similaridade de cosseno</h4><p>Depois que todas as imagens foram transformadas em vetores, podemos compará-las. A métrica utilizada será a similaridade de cosseno, que mede o ângulo entre dois vetores:</p><pre>cosine_similarity(A, B) = (A · B) / (||A|| × ||B||)</pre><p>Quanto mais alinhados estiverem os vetores, maior será a similaridade entre eles. Como nossos embeddings já foram normalizados, o denominador é igual a 1. Sendo assim, podemos fazer o cálculo por meio do produto matricial:</p><pre>scores = left @ right.T</pre><p>Todavia, encontramos novamente um problema de escala. Uma matriz contendo todas as combinações entre N imagens possui dimensões N × N. <strong>Para 100 mil imagens, isso representaria 10 bilhões de posições, antes mesmo de considerarmos outras estruturas de processamento.</strong></p><p>Por esse motivo, a implementação compara blocos de vetores e escreve os pares encontrados diretamente em um arquivo CSV:</p><pre>for left_start in range(0, n, comparison_batch_size):<br>    left_end = min(<br>        left_start + comparison_batch_size,<br>        n,<br>    )<br>    left = np.asarray(<br>        embeddings[left_start:left_end]<br>    )<br><br>    for right_start in range(<br>        left_start,<br>        n,<br>        comparison_batch_size,<br>    ):<br>        right_end = min(<br>            right_start + comparison_batch_size,<br>            n,<br>        )<br>        right = np.asarray(<br>            embeddings[right_start:right_end]<br>        )<br>        scores = left @ right.T</pre><p>Com isso, limitamos a memória utilizada. É importante observar, porém, que continuamos realizando todas as comparações. Resolvemos o problema de espaço, mas o custo de tempo continua sendo quadrático, ou aproximadamente O(N²).</p><p>Para coleções realmente grandes, uma evolução natural seria utilizar um índice de vizinhos aproximados, como FAISS ou HNSW, e comparar somente os vizinhos mais prováveis de cada imagem.</p><h4>Semelhança não significa duplicidade</h4><p>Aqui chegamos a uma distinção essencial. <strong>Se duas fotografias possuem embeddings próximos, isso não significa obrigatoriamente que sejam iguais</strong>.</p><p>Duas fotos diferentes de uma praia podem possuir grande similaridade semântica. Duas fotografias consecutivas da mesma pessoa também podem estar muito próximas, embora cada uma registre um momento único.</p><p>Sendo assim, utilizamos também o pHash, ou hash perceptual. Diferentemente de um hash criptográfico, ele busca produzir resultados próximos para imagens visualmente semelhantes.</p><pre>hashes[begin:end] = [<br>    np.uint64(<br>        int(str(imagehash.phash(image)), 16)<br>    )<br>    for image in images<br>]</pre><p>A distância entre dois hashes é calculada pela quantidade de bits diferentes:</p><pre>def phash_distance(<br>    a: np.uint64,<br>    b: np.uint64,<br>) -&gt; int:<br>    return int(int(a ^ b).bit_count())</pre><p>No projeto, classificamos um par como provavel_duplicata apenas quando ele atende simultaneamente a dois critérios:</p><ul><li>similaridade de embedding muito alta;</li><li>distância perceptual pequena.</li></ul><p>Caso apenas o primeiro critério seja atendido, o par recebe a classificação semanticamente_semelhante.</p><pre>probable_duplicate = (<br>    score &gt;= duplicate_threshold<br>    and distance &lt;= max_phash_distance<br>)</pre><p>Utilizamos alguns limiares para fazer essa classificação, mas eles são apenas pontos de partida. O melhor valor depende do modelo, do tipo de imagem e do custo de cada erro. Se um falso positivo puder levar à perda de uma fotografia importante, por exemplo, a decisão final precisa continuar sendo humana.</p><p>Uma alternativa mais segura seria mover os arquivos candidatos para uma pasta de quarentena, preservando um backup e permitindo a revisão antes da remoção definitiva.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*3woKfqfMeEcsXpd1cKhsIw.png" /><figcaption>Classificações em imagens de exemplo.</figcaption></figure><h4>Visualizando o espaço vetorial</h4><p>Um embedding do CLIP possui muito mais do que duas dimensões. Como não conseguimos representar esse espaço diretamente em um gráfico, precisamos reduzir sua dimensionalidade.</p><p>O projeto permite utilizar PCA ou UMAP. <strong>O PCA realiza uma projeção linear</strong> que busca preservar a maior quantidade possível de variância. <strong>O UMAP, por sua vez, é uma técnica não linear </strong>que tende a preservar melhor certas relações locais entre os pontos.</p><p>Todavia, devemos tomar cuidado ao interpretar essa figura. <strong>O gráfico não é o espaço original: ele é uma projeção e, durante essa transformação, parte da informação é inevitavelmente perdida.</strong></p><p>Além disso, projetar todo o conjunto pode novamente consumir muita memória. Por esse motivo, selecionamos uma amostra reprodutível:</p><pre>rng = np.random.default_rng(7)<br>indices = np.sort(<br>    rng.choice(<br>        len(paths),<br>        size=min(max_points, len(paths)),<br>        replace=False,<br>    )<br>)<br>sample = np.asarray(embeddings[indices])</pre><p>Depois, aplicamos a técnica escolhida:</p><pre>points = umap.UMAP(<br>    n_components=2,<br>    n_neighbors=max(<br>        2,<br>        min(15, len(sample) - 1),<br>    ),<br>    metric=&quot;cosine&quot;,<br>    random_state=7,<br>).fit_transform(sample)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1UZtUWxrMp-wAJdfMBdIQ.png" /><figcaption>Espaço de caracteristicas com imagens após embedding.</figcaption></figure><p>É esperado que imagens semanticamente próximas apareçam em regiões semelhantes. Entretanto, a distância observada no gráfico não deve substituir a métrica calculada no espaço original.</p><h4><strong>CLIP ou SigLIP?</strong></h4><p>O CLIP é uma ótima escolha para introduzir embeddings multimodais e possui amplo suporte em bibliotecas e exemplos. Todavia, ele não é a única alternativa.</p><p>O <strong>SigLIP</strong> também aprende relações entre texto e imagem, mas utiliza uma função de perda sigmoide em vez da formulação contrastiva baseada em softmax usada pelo CLIP. Na prática, diferentes versões desses modelos podem apresentar resultados distintos conforme o domínio, o idioma, a resolução e a infraestrutura disponível.</p><p>Não devemos escolher um modelo apenas porque ele liderou determinado benchmark. Para este problema, seria interessante construir um pequeno conjunto de avaliação contendo:</p><ul><li>imagens duplicadas com compressões e resoluções diferentes;</li><li>fotografias consecutivas da mesma cena;</li><li>imagens semanticamente próximas, mas que devem ser preservadas;</li><li>imagens visualmente parecidas, mas semanticamente diferentes;</li><li>exemplos reais do acervo que desejamos organizar.</li></ul><p>Depois, podemos avaliar precisão e recall em diferentes limiares, além de latência, throughput, consumo de memória e tamanho dos embeddings.</p><p><strong>Outro cuidado importante é que vetores gerados por modelos diferentes não pertencem necessariamente ao mesmo espaço. Se o encoder for alterado, a coleção precisa ser reprocessada e seu índice reconstruído.</strong></p><h4>Conclusão</h4><p>Ao transformar imagens em vetores, passamos a tratá-las por características que vão além de seus pixels. Com isso, conseguimos visualizar relações entre fotografias e encontrar candidatos que podem estar ocupando armazenamento desnecessariamente.</p><p>Todavia, este experimento também revelou uma distinção importante: <strong>similaridade semântica e duplicidade não são a mesma coisa.</strong> O <strong>embedding nos ajuda a encontrar imagens relacionadas</strong>, enquanto o <strong>pHash adiciona um sinal de semelhança perceptual.</strong> Mesmo utilizando os dois, a exclusão automática ainda exige cautela, calibração e uma estratégia de recuperação.</p><p>Também vimos que uma solução aparentemente simples encontra rapidamente desafios de engenharia. <strong>Carregar todas as imagens, construir uma matriz completa de similaridade e projetar todos os vetores podem funcionar em uma demonstração pequena, mas não escalam.</strong> O processamento em lotes, o uso de arrays mapeados em disco e os checkpoints tornam o experimento mais robusto.</p><p>Mais do que reduzir uma pasta de fotos, trabalhar com image embeddings é uma forma prática de compreender como modelos multimodais organizam informações. <strong>Imagens deixam de ser apenas matrizes de pixels e passam a ocupar um espaço matemático onde podemos comparar significado e encontrar relações que dificilmente seriam obtidas pela comparação direta de seus pixels.</strong></p><h3>Referências</h3><ul><li><a href="https://medium.com/data-hackers/entendendo-dist%C3%A2ncia-entre-queries-dd039cdf6cbc">Entendendo distância entre queries</a></li><li><a href="https://arxiv.org/abs/2103.00020">Learning Transferable Visual Models From Natural Language Supervision</a></li><li><a href="https://arxiv.org/abs/2303.15343">Sigmoid Loss for Language Image Pre-Training</a></li><li><a href="https://www.sbert.net/examples/sentence_transformer/applications/image-search/README.html">Image Search - Sentence Transformers documentation</a></li><li><a href="https://arxiv.org/abs/1802.03426">UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b225b77cab3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-hackers/de-pixels-a-vetores-image-embeddings-na-pr%C3%A1tica-1b225b77cab3">De pixels a vetores: Image Embeddings na prática</a> was originally published in <a href="https://medium.com/data-hackers">Data Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entendendo distância entre queries]]></title>
            <link>https://medium.com/data-hackers/entendendo-dist%C3%A2ncia-entre-queries-dd039cdf6cbc?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd039cdf6cbc</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 18:49:08 GMT</pubDate>
            <atom:updated>2025-12-12T18:49:08.806Z</atom:updated>
            <content:encoded><![CDATA[<h4>Você sabe qual é a diferença de distância entre queries? Quão parecidas (ou diferentes) elas são?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CXgMxsTmNiB9LCnU" /><figcaption>Photo by <a href="https://unsplash.com/@ianjbattaglia?utm_source=medium&amp;utm_medium=referral">Ian Battaglia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Um dos desafios, no âmbito da engenharia de dados, é entender como os usuários utilizam as consultas realizadas no data lake. Muitas vezes, os usuários são conscientes e possuem domínio das boas práticas, conseguindo consultar facilmente o que precisam e não ocupar grande parte da fila nem realizar uma varredura excessiva dos dados — o que impacta diretamente o custo financeiro da consulta, por exemplo, ao usar AWS Athena. Outras vezes, isso não acontece e passamos a enxergar um problema real nascer. Todavia, de qualquer forma, é importante entender como o usuário final tem usado a ferramenta de busca e segmentado as consultas.</p><h4><strong>Mas como entender a diferença entre as queries?</strong></h4><p>Quando se trata de números, é muito fácil entender a <strong>diferença </strong>entre dois ou mais pontos. Por exemplo, a diferença entre 10 e 5 é igual a 5. Quando se trata de vetores, que são sequências de números, isso também é palpável. Para exemplificar, imagine que o primeiro vetor é representado por <strong>u = (u1, u2)</strong> e o segundo, por <strong>v = (v1, v2);</strong> pode-se calcular a diferença entre ambos subtraindo seus componentes, por meio da fórmula <strong>(u1 - v1, u2 - v2)</strong>. Transformando isso em números para exemplificar, temos u = (1, 1) e v = (2,-3); logo, a diferença desses vetores é (1–2, 1–(-3)) ou (-1, 4). <strong>Mas quando se trata de palavras e caracteres, como fazemos essa conta? </strong>Qual a diferença entre Gabriel e Gabriela, ou no sentido das queries, <strong>qual a diferença entre as seguintes queries?</strong></p><pre>SELECT * FROM datalake_x</pre><pre>SELECT name FROM datalake_y</pre><p>E, na resposta, fica evidente que não se pode encontrar uma resposta a isso usando a mesma fórmula que usamos para vetores ou números.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*krYcMfU-sRnPP_0OC-nlEA.png" /></figure><h4>Mas e se fosse possível transformar as letras em números?</h4><p>E é exatamente respondendo a essa frase que podemos resolver o problema de achar diferença entre frases e caracteres — e não se limita a isso, mas também a áudios, imagens, vídeos, documentos e assim por diante. O nome desse tópico é “vector embedding” ou, quando se trata diretamente de palavras, “word embedding”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6Ak9iipm8RJqASC.png" /></figure><p>Nesse caso, as queries passam a ser um ponto em um hiperplano e podem ser utilizadas em operações, inclusive aquelas que demonstram diferença. Além disso, tudo o que passa a ser vetorizado ganha um significado semântico, no sentido de carregar consigo suas características e, naturalmente, isso será demonstrado no hiperplano. Por exemplo, palavras em plural estarão mais próximas do que palavras no singular; a cor do objeto, o tamanho, o tipo e outras características também serão considerados e, em resumo, <strong>quanto mais similares forem, mais próximas estarão.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*DuoNMXq1bPOVOodN.png" /></figure><h4>E como fazer esse processo?</h4><p>O processo de <em>embedding</em> pode ser realizado por meio de técnicas como Bag of Words (BoW) ou Term Frequency Inverse Document Frequency (TF-IDF), por exemplo, mas, com o advento das LLMs, tornou-se comum utilizar modelos baseados em arquitetura de Transformers para aplicar essas técnicas. Por exemplo, no link abaixo (Hugging Face) é possível ver uma série de modelos especializados nessa atividade.</p><p><a href="https://huggingface.co/models?other=embeddings">Models - Hugging Face</a></p><h4>E minhas queries? Quando vou ver a distância delas?</h4><p>Para a construção desse projeto, será necessário ter o <strong>Python</strong> instalado na versão 3.6 ou superior, bem como as bibliotecas <strong>Chromadb, sentence-transformers, NumPy, sklearn e Matplotlib</strong>. Isso porque o <strong>Chromadb</strong> é um banco de dados especializado no armazenamento de vetores; a biblioteca <strong>sentence-transformers</strong> fornece um framework que oferece um método simples para calcular, acessar, usar e treinar modelos de embedding de última geração. O <strong>NumPy</strong>, por sua vez, é uma biblioteca amplamente utilizada em cálculos científicos e em engenharia de dados, possibilitando o trabalho com dados multidimensionais e o uso de listas e matrizes. O scikit-learn (ou sklearn) é uma biblioteca voltada à ciência, mas seu diferencial é que normalmente é usado para a aplicação de técnicas de Machine Learning, e nós também precisaremos disso. Finalmente, o Matplotlib será utilizado para a criação de gráficos, que demonstrarão visualmente os resultados de nossas segmentações.</p><p>Para realizar a instalação desses pacotes, use o seguinte comando:</p><pre>pip install -U chromadb sentence-transformers numpy scikit-learn matplotlib</pre><p>Feito isso, vamos listar algumas queries para podermos criar os embeddings e usar como exemplo para calcular a diferença entre elas, mas se você tiver um caso real, fique à vontade para usar esses dados, sendo necessário apenas realizar a organização em uma estrutura de CSV com a coluna “query”, como exemplificado abaixo:</p><pre>query<br>&quot;SELECT * FROM datalake_x&quot;<br>&quot;SELECT name FROM datalake_y&quot;<br>&quot;SELECT id, name FROM users WHERE active = 1;&quot;<br>&quot;SELECT COUNT(*) FROM orders WHERE order_date &gt;= &#39;2023-01-01&#39;;&quot;<br>&quot;SELECT u.id, u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.total &gt; 100;&quot;<br>&quot;WITH recent_orders AS (SELECT * FROM orders WHERE order_date &gt; CURRENT_DATE - INTERVAL &#39;30 days&#39;) SELECT user_id, COUNT(*) FROM recent_orders GROUP BY user_id;&quot;<br>&quot;UPDATE users SET last_login = NOW() WHERE id = 123;&quot;<br>&quot;INSERT INTO audit_log (user_id, action, created_at) VALUES (456, &#39;login&#39;, NOW());&quot;<br>&quot;DELETE FROM sessions WHERE expires_at &lt; NOW();&quot;<br>&quot;SELECT name, AVG(rating) as avg_rating FROM reviews GROUP BY name HAVING AVG(rating) &gt; 4.5;&quot;<br>&quot;SELECT product_id, RANK() OVER (PARTITION BY category ORDER BY sales DESC) as rank FROM product_sales;&quot;<br>&quot;SELECT JSON_EXTRACT(payload, &#39;$.user.email&#39;) as email FROM events WHERE event_type = &#39;signup&#39;;&quot;<br>&quot;ALTER TABLE orders ADD COLUMN shipped_at TIMESTAMP;&quot;<br>&quot;SELECT * FROM orders WHERE status = &#39;shipped&#39; LIMIT 10 OFFSET 20;&quot;<br>&quot;SELECT DISTINCT country FROM customers;&quot;<br>&quot;SELECT u.name, COUNT(o.id) as cnt FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.name;&quot;<br>&quot;SELECT * FROM information_schema.tables WHERE table_schema = &#39;public&#39;;&quot;<br>&quot;SELECT ARRAY_AGG(id) FROM items WHERE category = &#39;tools&#39;;&quot;<br>&quot;SELECT CASE WHEN amount &gt; 100 THEN &#39;high&#39; ELSE &#39;low&#39; END as level FROM payments;&quot;<br>&quot;SELECT * FROM payments WHERE metadata-&gt;&gt;&#39;source&#39; = &#39;mobile&#39;;&quot;<br>&quot;SELECT id FROM users WHERE email LIKE &#39;%@example.com&#39;;&quot;<br>&quot;SELECT * FROM logs WHERE message ILIKE &#39;%error%&#39; ORDER BY timestamp DESC;&quot;<br>&quot;CREATE INDEX idx_users_email ON users(email);&quot;<br>&quot;SELECT p.* FROM products p WHERE p.price BETWEEN 10 AND 50;&quot;<br>&quot;SELECT EXTRACT(MONTH FROM order_date) as month, SUM(total) FROM orders GROUP BY month ORDER BY month;&quot;</pre><p>Abaixo, apresento a importação das bibliotecas em andamento. Observe que, na biblioteca sklearn, vamos importar o K-means, que será o responsável pela clusterização (ou agrupamento) dos dados, enquanto o TSNE será o responsável pela redução de dimensionalidade não linear, com base em conceitos de aprendizado de manifold. E, por fim, a similaridade de cosseno (cosine_similarity) será nossa métrica para avaliar a semelhança entre uma query e outra.</p><pre>import chromadb<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>from sklearn.cluster import KMeans<br>from sklearn.manifold import TSNE<br>from sklearn.metrics.pairwise import cosine_similarity<br>from sentence_transformers import SentenceTransformer</pre><p>Em seguida, definimos o número de agrupamentos desejados com o algoritmo K-means. Vale dizer que para problemas conhecidos, costuma-se definir esse número de modo estocástico, todavia para problemas em que não se conhece o valor de K desejado, utiliza-se de um método chamado cotovelo (ou elbow method) em que são realizados testes com vários números de K e o melhor valor é definido por meio daquele K que forma um cotovelo em sua visualização. Isso acontece porque, depois daquele valor, não costuma haver um bom custo-benefício. Fique à vontade para escolher o seu número de K ou para fazer um teste com a técnica que citei.</p><p>Feito isso, realiza-se a leitura da base de dados com as queries e armazena-se em sql_queries.</p><pre>NUMBER_CLUSTERS = 20<br><br>sql_queries = pd.read_csv(&#39;sql_queries.csv&#39;)[&#39;query&#39;].tolist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*gKJNjqVGPSdyY092.png" /><figcaption>Representação do Elbow Method.</figcaption></figure><p>A etapa de definição do Chromadb é importante, pois esse será o banco de dados que suportará todas as nossas queries. Aqui, nesse caso, realizamos a deleção da base, caso ela já exista, pois não queremos resíduos no nosso estudo. Depois definimos qual será a collection que utilizaremos.</p><pre>def setup_chroma_db():<br>    &quot;&quot;&quot;Initialize ChromaDB client and collection&quot;&quot;&quot;<br>    client = chromadb.Client()<br><br>    try:<br>        client.delete_collection(&quot;sql_queries&quot;)<br>    except Exception as e:<br>        print(f&quot;Error deleting collection: {e}&quot;)<br><br>    collection = client.create_collection(<br>        name=&quot;sql_queries&quot;,<br>        metadata={&quot;description&quot;: &quot;SQL queries for similarity analysis&quot;}<br>    )<br><br>    return client, collection</pre><p>Tendo o banco de dados já definido, vamos ao processo de armazenamento das queries no Chromadb, utilizando a função store_queries_in_chroma, definindo um ID único para cada query e adicionando um metadado para rastreabilidade.</p><pre>def store_queries_in_chroma(collection, queries):<br>    &quot;&quot;&quot;Store SQL queries in ChromaDB&quot;&quot;&quot;<br>    ids = [f&quot;query_{i}&quot; for i in range(len(queries))]<br>    collection.add(<br>        documents=queries,<br>        ids=ids,<br>        metadatas=[<br>            {&quot;type&quot;: &quot;sql_query&quot;, &quot;index&quot;: i}<br>            for i in range(len(queries))<br>        ]<br>    )<br><br>    print(f&quot;Stored {len(queries)} SQL queries in ChromaDB&quot;)</pre><p>Neste passo seguinte, encontra-se um dos corações do processamento, pois aqui realizamos o embedding das funções. Nesse ponto, recuperamos todas as queries e IDs do banco de dados e, logo em seguida, passamos cada uma delas pelo processo de embedding, obtendo-se os dados vetorizados e podendo retornar os IDs, os documentos originais e seus vetores. No caso do exemplo utilizado nesse projeto, optamos pela rede <strong>all-MiniLM-L6</strong>, mas fique à vontade para usar a que preferir, podendo escolher uma open-source no HuggingFace ou uma privada.</p><pre>def get_embeddings_for_clustering(collection):<br>    &quot;&quot;&quot;Get embeddings from ChromaDB for clustering&quot;&quot;&quot;<br>    results = collection.get()<br>    documents = results[&#39;documents&#39;]<br>    ids = results[&#39;ids&#39;]<br>    model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>    embeddings = model.encode(documents)<br><br>    return embeddings, documents, ids</pre><p>Agora, realizaremos o agrupamento dessas queries, pois, como já temos os dados em forma de vetor, conseguiremos realizar cálculos entre eles, podendo identificar o que está mais próximo, o mais distante e realizar outras operações. Nesse caso, utilizaremos o algoritmo de Machine Learning K-means para realizar o agrupamento, pois, por não ser supervisionado, não precisaremos passar por uma etapa de treinamento, podendo criar um DataFrame com cada uma das queries e o número do cluster/agrupamento a que ela pertence. Vale lembrar que, por padrão, o K-means utiliza a distância euclidiana para calcular as distâncias, e, assim, esses clusters são agrupados por meio dessa técnica. Em resumo, neste ponto teremos as queries, suas representações vetoriais, seus IDs e o número do grupo a que pertencem. Sendo assim, basta aplicar o cálculo para saber qual a distância entre essas queries.</p><pre>def perform_clustering(embeddings, documents, n_clusters=5):<br>    &quot;&quot;&quot;Perform K-means clustering on SQL queries&quot;&quot;&quot;<br>    kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)<br>    cluster_labels = kmeans.fit_predict(embeddings)<br><br>    df = pd.DataFrame({<br>        &#39;query&#39;: documents,<br>        &#39;cluster&#39;: cluster_labels<br>    })<br><br>    print(f&quot;\nClustering Results ({n_clusters} clusters):&quot;)<br><br>    for cluster_id in range(n_clusters):<br>        cluster_queries = df[df[&#39;cluster&#39;] == cluster_id][&#39;query&#39;].tolist()<br>        print(f&quot;\nCluster {cluster_id} ({len(cluster_queries)} queries):&quot;)<br>        for query in cluster_queries:<br>            print(f&quot;  - {query}&quot;)<br><br>    return cluster_labels, df</pre><p>Então, agora partiremos para a parte final do nosso projeto, em que saberemos a distância entre nossas queries e a veremos por meio de um plot, podendo seguir para uma das alternativas: 1) Realizar o “cruzamento” entre todas as queries e ver as que mais se parecem, por meio da função analyze_query_similarity_matrix ou 2) realizar o cruzamento de todas as queries com uma em específico, descobrindo quais mais se parece com ela, por meio da função find_similar_queries.</p><pre>def analyze_query_similarity_matrix(embeddings, documents):<br>    similarity_matrix = cosine_similarity(embeddings)<br>    print(&quot;\nTop 5 Most Similar Query Pairs:&quot;)<br>    print(&quot;=&quot; * 50)<br><br>    indices = np.triu_indices_from(similarity_matrix, k=1)<br>    similarities = similarity_matrix[indices]<br><br>    top_indices = np.argsort(similarities)[-5:][::-1]<br><br>    for idx in top_indices:<br>        i, j = indices[0][idx], indices[1][idx]<br>        similarity = similarities[idx]<br>        print(f&quot;Similarity: {similarity:.3f}&quot;)<br>        print(f&quot;  Query 1: {documents[i]}&quot;)<br>        print(f&quot;  Query 2: {documents[j]}&quot;)<br>        print()</pre><p>A função analyze_query_similarity_matrix calcula uma matriz de similaridade usando a função cosine_similarity, que mede a semelhança entre os embeddings de cada par de consultas. A matriz resultante é quadrada, com cada entrada correspondente à similaridade de cosseno entre duas consultas.</p><p>Para evitar comparações redundantes (já que a matriz é simétrica e a diagonal representa a autossimilaridade), a função extrai apenas o triângulo superior da matriz (excluindo a diagonal) com np.triu_indices_from(similarity_matrix, k=1). Isso fornece os índices de todos os pares de consultas únicos. Em seguida, ela recupera os valores de similaridade correspondentes e os ordena para identificar os cinco pares mais semelhantes.</p><p>Para cada um desses pares principais, a função imprime a pontuação de similaridade e os textos das duas consultas envolvidas, o que facilita a identificação rápida de quais consultas são mais semelhantes.</p><pre>def find_similar_queries(collection, query, n_results=3):<br>    &quot;&quot;&quot;Find similar queries using ChromaDB&quot;&quot;&quot;<br>    results = collection.query(<br>        query_texts=[query],<br>        n_results=n_results<br>    )<br><br>    print(f&quot;\nQuery: {query}&quot;)<br>    print(&quot;Similar queries:&quot;)<br>    for i, (doc, distance) in enumerate(zip(results[&#39;documents&#39;][0], results[&#39;distances&#39;][0])):<br>        similarity = 1 - distance<br>        print(f&quot;  {i+1}. Similarity: {similarity:.3f} - {doc}&quot;)</pre><p>Já a função find_similar_queries exibe consultas semelhantes a uma consulta de entrada fornecida, permitindo ajustar o número de retornos por meio do parâmetro n_results.</p><p>Na função realiza-se a chamada da collection.query, passando a consulta de entrada como uma lista de um único elemento e a quantidade de outputs esperados. Resultando em um dicionário com os registros e as respectivas distâncias.</p><p>Finalmente, a função então exibe a consulta de referência e itera sobre os pares de documentos semelhantes e suas distâncias, usando zip. Para cada par, ela calcula uma pontuação de similaridade com a fórmula <strong>1 — distância</strong>, em que valores mais altos indicam maior similaridade.</p><pre>def visualize_clusters(embeddings, cluster_labels, documents):<br>    tsne = TSNE(<br>        n_components=2,<br>        random_state=42,<br>        perplexity=min(30, len(documents)-1)<br>    )<br>    embeddings_2d = tsne.fit_transform(embeddings)<br><br>    plt.figure(figsize=(12, 8))<br>    scatter = plt.scatter(<br>        embeddings_2d[:, 0],<br>        embeddings_2d[:, 1],<br>        c=cluster_labels,<br>        # cmap=&#39;tab10&#39;,<br>        alpha=0.7<br>    )<br><br>    for i, _ in enumerate(documents):<br>        label = f&#39;query_{i}&#39;<br>        plt.annotate(<br>            label,<br>            (embeddings_2d[i, 0], embeddings_2d[i, 1]),<br>            fontsize=8,<br>            alpha=0.7<br>        )<br><br>    plt.title(&#39;SQL Queries Clustering Visualization&#39;)<br>    plt.xlabel(&#39;t-SNE Component 1&#39;)<br>    plt.ylabel(&#39;t-SNE Component 2&#39;)<br>    plt.colorbar(scatter, label=&#39;Cluster Label&#39;)<br>    plt.tight_layout()<br>    plt.savefig(&#39;sql_queries_clustering.png&#39;)</pre><p>Finalmente, partimos para o passo final, em que teremos os clusters agrupados visualmente. Isso acontece com a função visualize_clusters. Nessa função, utilizamos t-SNE (TSNE do scikit-learn) para reduzir a dimensionalidade dos embeddings a duas dimensões únicas, de modo que possamos visualizar o resultado. O parâmetro perplexity é definido como o mínimo de 30 ou um valor inferior ao número de documentos, o que ajuda o t-SNE a equilibrar os aspectos locais e globais da estrutura dos dados.</p><p>Após a redução da dimensionalidade, a função cria um gráfico de dispersão com Matplotlib, em que cada ponto representa uma consulta SQL, posicionada de acordo com suas coordenadas t-SNE. A cor de cada ponto é determinada pelo rótulo de cluster, permitindo distinguir visualmente diferentes clusters e, assim, o gráfico é salvo como um arquivo PNG.</p><p>Essa visualização ajuda os usuários a entender rapidamente como as consultas SQL são agrupadas e quanto distintas ou sobrepostas são as clusters, o que é valioso para tarefas como a análise de consultas ou a detecção de anomalias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5kteugvSL8wA6EmkIMkmg.png" /></figure><h4>Conclusão</h4><p>Ao transformar consultas SQL em vetores e analisar suas distâncias, abrimos um caminho poderoso para entender padrões de uso, identificar similaridades semânticas e até detectar anomalias no comportamento dos usuários. Técnicas de embeddings — antes restritas ao processamento de linguagem natural — tornam-se ferramentas essenciais para a engenharia de dados, permitindo que queries deixem de ser apenas textos estáticos e passem a ocupar um espaço matemático, onde podem ser comparadas, agrupadas e visualizadas.</p><p>Com isso, o processo de otimização do data lake torna-se mais inteligente e estratégico. Agrupar consultas semelhantes ajuda a compreender como os times usam os dados, quais padrões se repetem e onde há oportunidades de melhoria, seja na documentação, na governança ou até mesmo na performance.</p><p>Mais do que uma análise técnica, trabalhar com embeddings de queries é um passo em direção à maturidade analítica: <strong>transforma observações subjetivas em métricas concretas e visualizáveis.</strong> Ao dominar essas técnicas, você não só entende a distância entre consultas — entende melhor o próprio comportamento dos dados e de quem os utiliza.</p><p>Para consultar o script final: <a href="https://gist.github.com/Lucs1590/f0fa5a42d9a7889b6b5d850fab9e8985">https://gist.github.com/Lucs1590/f0fa5a42d9a7889b6b5d850fab9e8985</a></p><h4>Referências</h4><ul><li><a href="https://towardsdatascience.com/working-with-embeddings-closed-versus-open-source-39491f0b95c2/">Working with Embeddings: Closed versus Open Source | Towards Data Science</a></li><li><a href="https://towardsdatascience.com/deep-learning-for-nlp-word-embeddings-4f5c90bcdab5/">Deep Learning for NLP: Word Embeddings | Towards Data Science</a></li><li><a href="https://medium.com/turing-talks/introdu%C3%A7%C3%A3o-a-bag-of-words-e-tf-idf-43a128151ce9">Introdução a Bag of Words e TF-IDF</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd039cdf6cbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-hackers/entendendo-dist%C3%A2ncia-entre-queries-dd039cdf6cbc">Entendendo distância entre queries</a> was originally published in <a href="https://medium.com/data-hackers">Data Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Measure Similarity Between SQL Queries Using Embeddings]]></title>
            <link>https://levelup.gitconnected.com/how-to-measure-similarity-between-sql-queries-using-embeddings-36a74b4beabf?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a74b4beabf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[vector-similarity]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 03:49:27 GMT</pubDate>
            <atom:updated>2025-12-11T03:49:27.248Z</atom:updated>
            <content:encoded><![CDATA[<h4>Transform SQL queries into vector embeddings to cluster, compare, and analyze behaviors in data lakes with precision.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bVP3BMJrmBjEffj9" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the recurring challenges in data engineering is understanding how users interact with the data lake. Some users follow best practices, write efficient queries, and avoid scanning unnecessary data — helping control costs on engines like AWS Athena. Others… not so much. And that’s when real problems begin to surface.</p><p>Regardless of the scenario, gaining visibility into how users write queries — how they search, filter, and access data — is crucial. But that raises an interesting question:</p><h4>How do we measure the difference between two queries?</h4><p>When we talk about numbers, distance is trivial. The difference between 10 and 5 is 5.</p><p>With vectors, it’s also straightforward.<br>For example, consider:</p><ul><li><strong>u = (1, 1)</strong></li><li><strong>v = (2, −3)</strong></li></ul><p>Their difference is:<br> <strong>(1–2, 1–(-3)) → (-1, 4)</strong></p><p>But when it comes to <em>words</em> — or SQL queries — how do we compute this difference?</p><p>What’s the distance between:</p><pre>SELECT * FROM datalake_x</pre><p>and</p><pre>SELECT name FROM datalake_y</pre><p>Clearly, we can’t subtract words like we subtract numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*krYcMfU-sRnPP_0OC-nlEA.png" /></figure><h4>What if we could convert text into numbers?</h4><p>That’s precisely what embeddings enable.</p><p>“Vector embeddings” — or, when explicitly applied to words, “word embeddings” — convert text into numeric vectors. Once in vector form, queries become points in a high-dimensional space. Suddenly, all sorts of mathematical operations become possible:</p><ul><li>Measuring distance</li><li>Finding similar queries</li><li>Grouping queries by semantics</li><li>Detecting anomalies</li><li>Visualizing relationships</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6Ak9iipm8RJqASC.png" /></figure><p>Because embeddings capture meaning, queries that “feel” similar will naturally appear closer in this vector space.</p><h4>How do we generate embeddings?</h4><p>Classical techniques include:</p><ul><li><strong>Bag of Words (BoW)</strong></li><li><strong>TF-IDF</strong></li></ul><p>But with the rise of transformer-based models, it’s now standard practice to use sentence-level embeddings. The Hugging Face Model Hub offers thousands of models, both open-source and commercial.</p><p><a href="https://huggingface.co/models?other=embeddings">Models - Hugging Face</a></p><h4>Preparing Your Environment</h4><p>For the project demonstrated here, you’ll need:</p><ul><li>Python 3.6+</li><li>chromadb</li><li>sentence-transformers</li><li>numpy</li><li>scikit-learn</li><li>matplotlib</li></ul><p>Install everything with:</p><pre>pip install -U chromadb sentence-transformers numpy scikit-learn matplotlib</pre><p>We’ll build a CSV containing a list of SQL queries under a single column (query). Example:</p><pre>query<br>&quot;SELECT * FROM datalake_x&quot;<br>&quot;SELECT name FROM datalake_y&quot;<br>&quot;SELECT id, name FROM users WHERE active = 1;&quot;<br>&quot;SELECT COUNT(*) FROM orders WHERE order_date &gt;= &#39;2023-01-01&#39;;&quot;<br>&quot;SELECT u.id, u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.total &gt; 100;&quot;<br>&quot;WITH recent_orders AS (SELECT * FROM orders WHERE order_date &gt; CURRENT_DATE - INTERVAL &#39;30 days&#39;) SELECT user_id, COUNT(*) FROM recent_orders GROUP BY user_id;&quot;<br>&quot;UPDATE users SET last_login = NOW() WHERE id = 123;&quot;<br>&quot;INSERT INTO audit_log (user_id, action, created_at) VALUES (456, &#39;login&#39;, NOW());&quot;<br>&quot;DELETE FROM sessions WHERE expires_at &lt; NOW();&quot;<br>&quot;SELECT name, AVG(rating) as avg_rating FROM reviews GROUP BY name HAVING AVG(rating) &gt; 4.5;&quot;<br>&quot;SELECT product_id, RANK() OVER (PARTITION BY category ORDER BY sales DESC) as rank FROM product_sales;&quot;<br>&quot;SELECT JSON_EXTRACT(payload, &#39;$.user.email&#39;) as email FROM events WHERE event_type = &#39;signup&#39;;&quot;<br>&quot;ALTER TABLE orders ADD COLUMN shipped_at TIMESTAMP;&quot;<br>&quot;SELECT * FROM orders WHERE status = &#39;shipped&#39; LIMIT 10 OFFSET 20;&quot;<br>&quot;SELECT DISTINCT country FROM customers;&quot;<br>&quot;SELECT u.name, COUNT(o.id) as cnt FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.name;&quot;<br>&quot;SELECT * FROM information_schema.tables WHERE table_schema = &#39;public&#39;;&quot;<br>&quot;SELECT ARRAY_AGG(id) FROM items WHERE category = &#39;tools&#39;;&quot;<br>&quot;SELECT CASE WHEN amount &gt; 100 THEN &#39;high&#39; ELSE &#39;low&#39; END as level FROM payments;&quot;<br>&quot;SELECT * FROM payments WHERE metadata-&gt;&gt;&#39;source&#39; = &#39;mobile&#39;;&quot;<br>&quot;SELECT id FROM users WHERE email LIKE &#39;%@example.com&#39;;&quot;<br>&quot;SELECT * FROM logs WHERE message ILIKE &#39;%error%&#39; ORDER BY timestamp DESC;&quot;<br>&quot;CREATE INDEX idx_users_email ON users(email);&quot;<br>&quot;SELECT p.* FROM products p WHERE p.price BETWEEN 10 AND 50;&quot;<br>&quot;SELECT EXTRACT(MONTH FROM order_date) as month, SUM(total) FROM orders GROUP BY month ORDER BY month;&quot;</pre><h4>ChromaDB Setup</h4><p>ChromaDB will store our SQL queries as documents and allow efficient vector retrieval.</p><pre>def setup_chroma_db():<br>    &quot;&quot;&quot;Initialize ChromaDB client and collection&quot;&quot;&quot;<br>    client = chromadb.Client()<br><br>    try:<br>        client.delete_collection(&quot;sql_queries&quot;)<br>    except Exception as e:<br>        print(f&quot;Error deleting collection: {e}&quot;)<br><br>    collection = client.create_collection(<br>        name=&quot;sql_queries&quot;,<br>        metadata={&quot;description&quot;: &quot;SQL queries for similarity analysis&quot;}<br>    )<br><br>    return client, collection</pre><h4>Storing Queries in ChromaDB</h4><p>Each query receives a unique ID and metadata for traceability.</p><pre>def store_queries_in_chroma(collection, queries):<br>    &quot;&quot;&quot;Store SQL queries in ChromaDB&quot;&quot;&quot;<br>    ids = [f&quot;query_{i}&quot; for i in range(len(queries))]<br>    collection.add(<br>        documents=queries,<br>        ids=ids,<br>        metadatas=[<br>            {&quot;type&quot;: &quot;sql_query&quot;, &quot;index&quot;: i}<br>            for i in range(len(queries))<br>        ]<br>    )<br><br>    print(f&quot;Stored {len(queries)} SQL queries in ChromaDB&quot;)</pre><h4>Embedding the Queries</h4><p>Here, we use the all-MiniLM-L6-v2 model from Sentence Transformers.</p><pre>def get_embeddings_for_clustering(collection):<br>    &quot;&quot;&quot;Get embeddings from ChromaDB for clustering&quot;&quot;&quot;<br>    results = collection.get()<br>    documents = results[&#39;documents&#39;]<br>    ids = results[&#39;ids&#39;]<br>    model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>    embeddings = model.encode(documents)<br><br>    return embeddings, documents, ids</pre><h4>Clustering the Queries</h4><p>With embeddings in hand, we can group similar queries using <strong>K-Means</strong>.</p><pre>def perform_clustering(embeddings, documents, n_clusters=5):<br>    &quot;&quot;&quot;Perform K-means clustering on SQL queries&quot;&quot;&quot;<br>    kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)<br>    cluster_labels = kmeans.fit_predict(embeddings)<br><br>    df = pd.DataFrame({<br>        &#39;query&#39;: documents,<br>        &#39;cluster&#39;: cluster_labels<br>    })<br><br>    print(f&quot;\nClustering Results ({n_clusters} clusters):&quot;)<br><br>    for cluster_id in range(n_clusters):<br>        cluster_queries = df[df[&#39;cluster&#39;] == cluster_id][&#39;query&#39;].tolist()<br>        print(f&quot;\nCluster {cluster_id} ({len(cluster_queries)} queries):&quot;)<br>        for query in cluster_queries:<br>            print(f&quot;  - {query}&quot;)<br><br>    return cluster_labels, df</pre><p>If you don’t know how many clusters to use, apply the <strong>Elbow Method</strong> to find a good balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*gKJNjqVGPSdyY092.png" /><figcaption>Elbow Method representation.</figcaption></figure><h3>Measuring Distance Between Queries</h3><h4>1. Compute a Full Similarity Matrix</h4><pre>def analyze_query_similarity_matrix(embeddings, documents):<br>    similarity_matrix = cosine_similarity(embeddings)<br>    print(&quot;\nTop 5 Most Similar Query Pairs:&quot;)<br>    print(&quot;=&quot; * 50)<br><br>    indices = np.triu_indices_from(similarity_matrix, k=1)<br>    similarities = similarity_matrix[indices]<br><br>    top_indices = np.argsort(similarities)[-5:][::-1]<br><br>    for idx in top_indices:<br>        i, j = indices[0][idx], indices[1][idx]<br>        similarity = similarities[idx]<br>        print(f&quot;Similarity: {similarity:.3f}&quot;)<br>        print(f&quot;  Query 1: {documents[i]}&quot;)<br>        print(f&quot;  Query 2: {documents[j]}&quot;)<br>        print()</pre><p>This function identifies the <em>five most similar query pairs</em> based on cosine similarity.</p><h4>2. Find Similar Queries to One Input</h4><pre>def find_similar_queries(collection, query, n_results=3):<br>    &quot;&quot;&quot;Find similar queries using ChromaDB&quot;&quot;&quot;<br>    results = collection.query(<br>        query_texts=[query],<br>        n_results=n_results<br>    )<br><br>    print(f&quot;\nQuery: {query}&quot;)<br>    print(&quot;Similar queries:&quot;)<br>    for i, (doc, distance) in enumerate(zip(results[&#39;documents&#39;][0], results[&#39;distances&#39;][0])):<br>        similarity = 1 - distance<br>        print(f&quot;  {i+1}. Similarity: {similarity:.3f} - {doc}&quot;)</pre><p>Helpful in understanding how a specific query compares to others in the dataset.</p><h3>Visualizing the Clusters</h3><p>We use <strong>t-SNE</strong> to reduce the embedding dimensionality to 2D and plot the results.</p><pre>def visualize_clusters(embeddings, cluster_labels, documents):<br>    tsne = TSNE(<br>        n_components=2,<br>        random_state=42,<br>        perplexity=min(30, len(documents)-1)<br>    )<br>    embeddings_2d = tsne.fit_transform(embeddings)<br><br>    plt.figure(figsize=(12, 8))<br>    scatter = plt.scatter(<br>        embeddings_2d[:, 0],<br>        embeddings_2d[:, 1],<br>        c=cluster_labels,<br>        # cmap=&#39;tab10&#39;,<br>        alpha=0.7<br>    )<br><br>    for i, _ in enumerate(documents):<br>        label = f&#39;query_{i}&#39;<br>        plt.annotate(<br>            label,<br>            (embeddings_2d[i, 0], embeddings_2d[i, 1]),<br>            fontsize=8,<br>            alpha=0.7<br>        )<br><br>    plt.title(&#39;SQL Queries Clustering Visualization&#39;)<br>    plt.xlabel(&#39;t-SNE Component 1&#39;)<br>    plt.ylabel(&#39;t-SNE Component 2&#39;)<br>    plt.colorbar(scatter, label=&#39;Cluster Label&#39;)<br>    plt.tight_layout()<br>    plt.savefig(&#39;sql_queries_clustering.png&#39;)</pre><p>This chart helps reveal structure: tight clusters, overlaps, outliers, and similarities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5kteugvSL8wA6EmkIMkmg.png" /></figure><h3>Conclusion</h3><p>By transforming SQL queries into vectors, we unlock a robust set of analytical capabilities. Embeddings allow us to:</p><ul><li>Identify semantically similar queries</li><li>Understand user behavior</li><li>Detect inefficiencies or anomalies</li><li>Improve governance and documentation</li><li>Optimize data lake usage</li></ul><p>Instead of treating queries as plain text, we treat them as meaningful numerical representations — making their relationships quantifiable and visible.</p><p>This approach shifts query analysis from guesswork to measurable insights. As you adopt embeddings into your data engineering workflow, you gain a deeper understanding not only of query <em>distance</em> but of how your organization truly interacts with its data.</p><p><strong>Full script available here:</strong><br><a href="https://gist.github.com/Lucs1590/f0fa5a42d9a7889b6b5d850fab9e8985">https://gist.github.com/Lucs1590/f0fa5a42d9a7889b6b5d850fab9e8985</a></p><h3>References</h3><ul><li><a href="https://towardsdatascience.com/working-with-embeddings-closed-versus-open-source-39491f0b95c2/">Working with Embeddings: Closed versus Open Source | Towards Data Science</a></li><li><a href="https://towardsdatascience.com/deep-learning-for-nlp-word-embeddings-4f5c90bcdab5/">Deep Learning for NLP: Word Embeddings | Towards Data Science</a></li><li><a href="https://medium.com/turing-talks/introdu%C3%A7%C3%A3o-a-bag-of-words-e-tf-idf-43a128151ce9">Introdução a Bag of Words e TF-IDF</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a74b4beabf" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-measure-similarity-between-sql-queries-using-embeddings-36a74b4beabf">How to Measure Similarity Between SQL Queries Using Embeddings</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM to Strava: Análise Inteligente de Treinos com Co-coaching]]></title>
            <link>https://lucasbsilva29.medium.com/llm-to-strava-an%C3%A1lise-inteligente-de-treinos-com-co-coaching-0775b845d613?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/0775b845d613</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[sports]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 17:01:47 GMT</pubDate>
            <atom:updated>2025-10-04T17:01:47.320Z</atom:updated>
            <content:encoded><![CDATA[<h4>Feedback instantâneo para otimizar sua performance esportiva.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gBMgYcvOw2QkxoEt" /><figcaption>Photo by <a href="https://unsplash.com/@gabinvallet?utm_source=medium&amp;utm_medium=referral">Gabin Vallet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Como expliquei em um artigo anterior aqui no Medium, no ano passado mergulhei no mundo do triathlon e desenvolvi uma aplicação para sincronizar meus treinos do Strava para o TrainingPeaks — uma integração que ainda não existe nativamente. Se você tem curiosidade sobre essa aplicação, os detalhes estão no artigo abaixo:</p><p><a href="https://levelup.gitconnected.com/strava-to-trainingpeaks-fa3a0fa05f79">Strava to TrainingPeaks</a></p><p>Após alguns meses de desenvolvimento e vivência no esporte, identifiquei uma necessidade clara: <strong>feedback rápido sobre treinos-chave. </strong>Meu treinador tem centenas de alunos e nem sempre consegue fornecer análises imediatas. Foi então que comecei a pensar em como resolver esse problema integrando uma solução à aplicação que já havia desenvolvido.</p><p>A resposta veio através dos <strong>Large Language Models (LLMs) </strong>— uma tecnologia que se tornou popular por sua capacidade generativa e conhecimento generalista abrangente.</p><h4>Plano de desenvolvimento</h4><p>Embora as LLMs sejam excelentes para contextos criativos, é importante esclarecer que elas não são uma “bala de prata”. Meu objetivo não era criar dados artificiais, mas analisar informações reais usando todo o conhecimento que a LLM adquiriu durante seu treinamento.</p><p>Para que a LLM funcione efetivamente nesse contexto analítico, era essencial ter acesso aos dados dos esportes praticados. Isso se alinhava perfeitamente com meu projeto existente de download de arquivos TCX do Strava, pois esses dados ficam temporariamente na memória — o momento ideal para expô-los à LLM para análise e feedback.</p><p><strong>Limitação identificada: </strong>Os dados de natação em piscina são exportados de forma diferente e não possuem todas as informações necessárias para análises completas, conforme mencionado no artigo anterior.</p><h4>Implementação</h4><p>Para corrida e ciclismo, após validar que o arquivo TCX foi baixado corretamente e contém todas as informações necessárias, implementei a pergunta:<strong> “Você quer ter análises de desempenho a partir da IA?”</strong></p><p>A confirmação dessa resposta tornou-se o gatilho para ativar a funcionalidade de inteligência artificial no projeto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Inrz2YMBu-fwBYpAbrcmjg.png" /><figcaption>Opções de execução de análise de desempenho com IA.</figcaption></figure><p>Por padrão, a opção de análise com IA fica desabilitada, pois é necessário definir uma chave da OpenAI com créditos disponíveis para interações de input e output. Para configurar sua chave, consulte:</p><p><a href="https://medium.com/@lorenzozar/how-to-get-your-own-openai-api-key-f4d44e60c327">How To Get Your Own OpenAI API Key</a></p><h4>Por que OpenAI?</h4><p>Escolhi a OpenAI por ser pioneira no desenvolvimento e popularização das LLMs, oferecendo modelos econômicos e performáticos ideais para projetos generalistas. O usuário final pode escolher a LLM que melhor se adapta ao seu problema específico.</p><p>Atualmente, mantenho o projeto atualizado com os modelos mais recentes. <strong>Nota importante: </strong>No momento da escrita deste artigo, o modelo mais avançado disponível é GPT-5. Esse modelo já oferece capacidades multimodais robustas, suportando texto e imagem, além de ser multilíngue.</p><h4>Contextualizando o Treino</h4><p>Quando você tem um treinador, sua abordagem ao exercício muda completamente. Em vez de simplesmente calçar os tênis e sair correndo, você segue uma planilha estruturada. Essa contextualização é fundamental para que a IA realize análises precisas.</p><p>O primeiro <em>input </em>solicitado ao usuário é o treino planejado. Para treinos livres, basta pressionar “Enter” — os detalhes do treino executado já estão na memória do sistema.</p><p>Pensando em internacionalização, o próximo parâmetro é o idioma desejado para o feedback, aproveitando a capacidade multilíngue da IA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvolxnhv10HHt_0etsrXzA.png" /><figcaption>Opção mostrando a opção de definição de treino e a linguagem definida para o output.</figcaption></figure><h4>Otimização de Custos</h4><p>Um desafio importante são os custos baseados em <em>tokens </em>(fragmentos de palavras ou palavras completas). Quanto maior for o texto enviado e recebido, mais cara fica a requisição. Era necessário balancear a riqueza dos dados com a sua representatividade em relação ao custo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*9kOmk0NpKg1eiRpjGdMAeA.png" /><figcaption>Imagem exemplificando balanço entre custo e representatividade.</figcaption></figure><p>A solução foi implementar <strong>exclusão de pontos similares usando distância euclidiana.</strong> Todos os pontos são comparados entre si, e dos mais similares, um é deletado. Isso mantém a representatividade dos dados enquanto reduz significativamente a quantidade de tokens enviados.</p><h4>Engenharia de Prompt</h4><p>Os dados otimizados são anexados a um prompt cuidadosamente construído. A qualidade do prompt é crucial, pois dita completamente como a IA responderá.</p><p>Após diversos testes e refinamentos, apliquei as melhores práticas da OpenAI para maximizar a eficácia do modelo:</p><p><a href="https://cookbook.openai.com/examples/gpt-5/gpt-5_prompting_guide">GPT-5 prompting guide | OpenAI Cookbook</a></p><p>O resultado é um output detalhado com análises do seu treino:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGZCobmDuTXt5L1783frxw.png" /><figcaption>Output da IA.</figcaption></figure><h4>A Pergunta que Não Quer Calar: Posso Dispensar Meu Treinador?</h4><p><strong>Resposta curta: Não.</strong></p><p>Embora a IA ofereça acessibilidade àqueles sem acesso a treinadores profissionais,<strong> a necessidade de um profissional qualificado é insubstituível.</strong></p><p>A IA funciona como auxiliar para feedbacks e insights rápidos, mas ter alguém que acompanhe de perto o atleta é essencial. Concordo com Matt Fitzgerald em <em>“Should You Allow AI to Coach You?”</em>, onde ele reconhece que aplicativos com IA conseguem reproduzir muitas decisões de treinadores experientes — ajustes de carga baseados em dados e princípios bem definidos.</p><p>Porém, há aspectos aonde a IA ainda não se equipara a um treinador humano, principalmente nas <strong>habilidades relacionais</strong>: motivação, comunicação, empatia, personalização profunda e capacidade de interpretar sutilezas do atleta (estado mental, fatores externos, lesões latentes, etc.).</p><p><a href="https://stories.strava.com/articles/should-you-allow-ai-to-coach-you">Should You Allow AI to Coach You?</a></p><p>Portanto, <strong>o Strava to TrainingPeaks com LLMs deve ser usado como auxiliar, não substituto</strong>. Aqui analisamos treinos isolados, enquanto um treinador conhece o atleta integralmente.</p><h4>Como o Feedback Pode ser Útil no TrainingPeaks?</h4><p>Além de fornecer feedback rápido ao atleta, as análises podem ser anexadas ao treino no TrainingPeaks, auxiliando o treinador com insights que ele poderia não perceber em detalhes específicos.</p><p>É consenso que a capacidade analítica das máquinas supera frequentemente a humana em aspectos específicos. Com feedback apurado, o treinador fica munido para oferecer <strong>treinamento ainda mais refinado ao atleta.</strong></p><h4>Conclusão</h4><p>A integração de LLMs na análise de treinos representa um avanço significativo na democratização do acesso a insights esportivos de qualidade. Embora não substitua a especialização humana, oferece uma ferramenta valiosa para atletas e treinadores otimizarem a performance por meio de feedback inteligente e imediato.</p><p>O projeto continua evoluindo, sempre buscando o equilíbrio entre inovação tecnológica e as necessidades reais dos praticantes de esportes de resistência.</p><p>Fique à vontade para fazer parte desse projeto! Acesse-o através do seguinte link, use e contribua!</p><p><a href="https://github.com/Lucs1590/strava-to-trainingpeaks/tree/1.3.0">GitHub - Lucs1590/strava-to-trainingpeaks at 1.3.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0775b845d613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM to Strava: Intelligent Training Analysis with AI Co-coaching]]></title>
            <link>https://levelup.gitconnected.com/llm-to-strava-intelligent-training-analysis-with-ai-co-coaching-03f1cf866597?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f1cf866597</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sports]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 02:41:15 GMT</pubDate>
            <atom:updated>2025-10-03T02:41:15.503Z</atom:updated>
            <content:encoded><![CDATA[<h4>Instant feedback to optimize your athletic performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xav1C80NquM9pjpK" /><figcaption>Photo by <a href="https://unsplash.com/@jeffreyflin?utm_source=medium&amp;utm_medium=referral">Jeffrey F Lin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As I explained in a previous article here on Medium, last year I dove into the world of triathlon and developed an application to sync my workouts from Strava to TrainingPeaks — an integration that doesn’t exist natively. If you’re curious about this application, the details are in the article below:</p><p><a href="https://levelup.gitconnected.com/strava-to-trainingpeaks-fa3a0fa05f79">Strava to TrainingPeaks</a></p><p>After months of development and experience in the sport, I identified a clear need: <strong>quick feedback on key workouts.</strong> My coach has hundreds of athletes and can’t always provide immediate analysis. That’s when I started thinking about how to solve this problem by integrating a solution into the application I had already developed.</p><p>The answer came <strong>through Large Language Models (LLMs) </strong>— a technology that has become popular for its generative capabilities and comprehensive generalist knowledge.</p><h4>Development Plan</h4><p>While LLMs are excellent for creative contexts, it’s important to clarify that they’re not a “silver bullet.” My goal wasn’t to create artificial data, but to <strong>analyze real information </strong>using all the knowledge the LLM acquired during its training.</p><p>For the LLM to function effectively in this analytical context, it was essential to have access to sports data. This aligned perfectly with my existing project for downloading TCX files from Strava, as this data temporarily resides in memory — the ideal moment to expose it to the LLM for analysis and feedback.</p><p><strong>Identified limitation:</strong> Swimming pool data is exported differently and doesn’t contain all the information necessary for complete analysis, as mentioned in the previous article.</p><h4>Implementation</h4><p>For running and cycling, after validating that the TCX file was downloaded correctly and contains all necessary information, I implemented the question: <strong>“Do you want performance analysis from AI?”</strong></p><p>Confirming this response became the trigger to activate the artificial intelligence functionality in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Inrz2YMBu-fwBYpAbrcmjg.png" /><figcaption>AI-powered performance analysis execution options.</figcaption></figure><p>By default, the AI analysis option is disabled, as it requires setting up an OpenAI key with available credits for input and output interactions. To configure your key, check out:</p><p><a href="https://medium.com/@lorenzozar/how-to-get-your-own-openai-api-key-f4d44e60c327">How To Get Your Own OpenAI API Key</a></p><h4>Why OpenAI?</h4><p>I chose OpenAI for being a pioneer in developing and popularizing LLMs, offering economical and performant models ideal for generalist projects. End users can choose the LLM that best fits their specific problem.</p><p>Currently, I keep the project updated with the latest models. <strong>Important note:</strong> At the time of writing this article, the most advanced available model is GPT-5. This model offers robust multimodal capabilities, supporting text and images, plus multilingual functionality.</p><h4>Contextualizing the Workout</h4><p>When you have a coach, your approach to exercise changes completely. Instead of simply putting on your shoes and running, you follow a structured plan. This contextualization is fundamental for the AI to perform accurate analysis.</p><p>The first input requested from the user is the planned workout. For free workouts, just press “Enter” — the details of the executed workout are already in the system’s memory.</p><p>Thinking about internationalization, the next parameter is the desired language for feedback, leveraging the AI’s multilingual capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xvolxnhv10HHt_0etsrXzA.png" /><figcaption>Option showing the training definition option and the language defined for the output.</figcaption></figure><h4>Cost Optimization</h4><p>An important challenge is the token-based costs (word fragments). The larger the text sent and received, the more expensive the request becomes. It was necessary to balance data richness versus cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9kOmk0NpKg1eiRpjGdMAeA.png" /><figcaption>Image exemplifying the balance between cost and representativeness.</figcaption></figure><p>The solution was implementing exclusion of similar points using Euclidean distance. All points are compared with each other, and from the most similar ones, one is deleted. This maintains data representativeness while significantly reducing the number of tokens sent.</p><h4>Prompt Engineering</h4><p>The optimized data is attached to a carefully constructed prompt. Prompt quality is crucial, as it completely dictates how the AI will respond.</p><p>After numerous tests and refinements, I applied OpenAI’s best practices to maximize model effectiveness:</p><p><a href="https://cookbook.openai.com/examples/gpt-5/gpt-5_prompting_guide">GPT-5 prompting guide | OpenAI Cookbook</a></p><p>The result is a detailed output with analysis of your workout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGZCobmDuTXt5L1783frxw.png" /><figcaption>AI Output.</figcaption></figure><h4>The Burning Question: Can I Ditch My Coach?</h4><p><strong>Short answer: No.</strong></p><p>While AI offers accessibility to those without access to professional coaches, <strong>the need for a qualified professional is irreplaceable.</strong></p><p>AI works as an assistant for quick feedback and insights, but having someone who closely monitors the athlete is essential. I agree with Matt Fitzgerald in “Should You Allow AI to Coach You?”, where he recognizes that AI-powered apps can reproduce many decisions of experienced coaches — load adjustments based on data and well-defined principles.</p><p>However, there are aspects where AI still doesn’t match a human coach, especially in <strong>relational skills:</strong> motivation, communication, empathy, deep personalization, and the ability to interpret athlete subtleties (mental state, external factors, latent injuries, etc.).</p><p><a href="https://stories.strava.com/articles/should-you-allow-ai-to-coach-you">Should You Allow AI to Coach You?</a></p><p>Therefore, <strong>Strava to TrainingPeaks with LLMs should be used as an assistant, not a replacement.</strong> Here we analyze isolated workouts, while a coach knows the athlete comprehensively.</p><h4>How Can Feedback Be Useful in TrainingPeaks?</h4><p>Beyond providing quick feedback to the athlete, analyses can be attached to the workout in TrainingPeaks, assisting the coach with insights they might not notice in specific details.</p><p>It’s consensus that machine analytical capacity frequently surpasses human capacity in specific aspects. With accurate feedback, the coach is equipped to offer <strong>even more refined training</strong> to the athlete.</p><h4>Conclusion</h4><p>Integrating LLMs into training analysis represents a significant advancement in democratizing access to quality sports insights. While it doesn’t replace human expertise, it offers a valuable tool for athletes and coaches to optimize performance through intelligent and immediate feedback.</p><p>The project continues evolving, always seeking the balance between technological innovation and the real needs of endurance sports practitioners.</p><p>Feel free to join this project! Access it through the following link, use it, and contribute!</p><p><a href="https://github.com/Lucs1590/strava-to-trainingpeaks/tree/1.3.0">GitHub - Lucs1590/strava-to-trainingpeaks at 1.3.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f1cf866597" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/llm-to-strava-intelligent-training-analysis-with-ai-co-coaching-03f1cf866597">LLM to Strava: Intelligent Training Analysis with AI Co-coaching</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Strava para o Training Peaks]]></title>
            <link>https://lucasbsilva29.medium.com/do-strava-para-otraining-peaks-b54aa496c6e3?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/b54aa496c6e3</guid>
            <category><![CDATA[dados]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[strava]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[trainingpeaks]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 23:18:05 GMT</pubDate>
            <atom:updated>2025-10-28T22:52:56.994Z</atom:updated>
            <content:encoded><![CDATA[<h4>Aprenda a conectar treinos do Strava com Training Peaks (TP).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aztLx6yOaDxcRSu6" /><figcaption>Photo by <a href="https://unsplash.com/@nodirkh?utm_source=medium&amp;utm_medium=referral">Nodir Khalilov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Motivação do Projeto</h4><p>Desde criança, fui incentivado pelos meus pais a praticar esportes, e na adolescência meu interesse por tecnologia, dados e inteligência artificial só aumentou. Essa combinação de paixões sempre foi essencial para mim, e hoje procuro integrá-las de forma inovadora.</p><p>Nos últimos anos, minha dedicação estava focada na corrida. Porém, no último ano, decidi me desafiar e me preparei para um <em>triathlon</em> — um esporte que une natação, ciclismo e corrida, e que revelou ser muito mais complexo e exigente do que qualquer atividade que eu já havia experimentado.</p><p>Ao embarcar nesse novo desafio, procurei um treinador especializado em triathlon. Em nossas conversas, além de alinharmos meus objetivos e compreendermos o funcionamento do meu metabolismo por meio de uma anamnese completa, ele me apresentou a plataforma <a href="https://www.trainingpeaks.com/"><strong>Training Peaks</strong></a>. Segundo ele, se eu usasse um <em>smartwatch</em> de marcas como Garmin ou Polar, meus treinos seriam sincronizados automaticamente com a plataforma, permitindo o acompanhamento detalhado da minha planilha de treinos.</p><p>Contudo, optei por utilizar um smartwatch da Samsung (Galaxy Watch 4), o que gerava uma particularidade: enquanto meus treinos eram automaticamente sincronizados com o <a href="https://www.strava.com/"><strong>Strava</strong></a>, a integração com o Training Peaks não ocorria de forma automática. Diante desse cenário, eu tinha duas alternativas: <strong>realizar o upload manual dos treinos</strong>, conforme sugerido pelo próprio Training Peaks (<a href="https://help.trainingpeaks.com/hc/en-us/articles/204070254-How-Do-I-Sync-My-Workout-Data-From-Strava-Into-TrainingPeaks">Como sincronizar seus dados do Strava com o Training Peaks</a>), ou <strong>desenvolver uma solução que automatizasse o processo de download dos dados do Strava e o upload para o Training Peaks</strong>. Naturalmente, escolhi o desafio de criar essa solução!</p><h4>Desenvolvimento do Projeto</h4><p>Um dos grandes diferenciais da aplicação é a <strong>interatividade</strong> que ela oferece, permitindo que o usuário selecione o esporte ou atividade que deseja sincronizar entre as plataformas. Essa funcionalidade é essencial, pois o método de <em>download</em> dos dados do Strava varia conforme o tipo de atividade.</p><p>Por exemplo:</p><ul><li><strong>Corrida e pedalada:</strong> Basta adicionar `/export_tcx` ao final da URL da atividade para obter um arquivo TCX.</li><li><strong>Natação:</strong> É necessário adicionar `/export_original` ao final da URL, pois o método padrão não gera o arquivo corretamente.</li></ul><p>Em ambos os casos, o arquivo baixado é no formato TCX. Desenvolvido pela <a href="https://www.garminstore.com.br/">Garmin</a> em 2007, esse formato foi projetado para transmitir dados em XML — como pontos de latitude e longitude, frequência cardíaca, cadência e calorias — tanto para atividades indoor quanto outdoor. No entanto, seu uso é mais restrito às soluções da própria Garmin e seus concorrentes não possuem tanta compatibilidade.</p><p>Após a seleção do esporte e a obtenção do arquivo TCX (seja via <em>download</em> automático ou seleção manual) inicia-se a etapa de processamento dos dados, sendo composta por:</p><ol><li><strong>Validação:</strong> Para corrida e pedalada, o arquivo é lido utilizando a biblioteca <a href="https://pypi.org/project/tcxreader/0.3.10/">tcxreader</a> e validado para garantir que o XML está correto.</li><li><strong>Ajustes Específicos para Natação:</strong> Devido à URI diferenciada, é necessário tratar o arquivo para corrigir o header padrão do XML e ajustar a tipagem de alguns valores.</li><li><strong>Finalização:</strong> Por fim, o arquivo é reformatado com uma indentação adequada, resultando num TCX pronto para ser importado no Training Peaks.</li></ol><p>Voilà! Com esses passos, o usuário tem em mãos um arquivo TCX devidamente processado e compatível para upload na plataforma.</p><h4>Como utilizar</h4><p>A interação com este projeto é realizada principalmente via interface de linha de comando (CLI). Para começar, certifique-se de ter o <a href="https://www.python.org/"><strong>Python</strong></a> instalado e configurado com todas as dependências necessárias. Siga os passos abaixo:</p><p><strong>1.Clone o Repositório:</strong></p><p>Baixe o projeto para o seu ambiente local executando:</p><pre>git clone https://github.com/Lucs1590/strava-to-trainingpeaks</pre><p><strong>2.Instale as Dependências:</strong></p><p>Navegue até o diretório do projeto e instale as bibliotecas necessárias:</p><pre>cd strava-to-trainingpeaks<br>pip install -r requirements.txt</pre><p><strong>3.Instalação Global do Script:</strong></p><p>Para permitir a execução do comando a partir de qualquer diretório, instale o projeto globalmente:</p><pre>pip install .</pre><p><strong>4.Execute o Comando Principal:</strong></p><p>Após a instalação, você poderá executar o script de qualquer lugar usando:</p><pre>strava-to-trainingpeaks</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*m8xBVZZSwNmdPnhauFhxjw.png" /><figcaption>Comando principal sendo executado via CLI.</figcaption></figure><p><strong>5. Conclua a Pipeline Manualmente:</strong></p><p>Embora o processo seja bastante automatizado, há alguns passos manuais para finalizar a integração:</p><ul><li><strong>Acesse o Calendário do Training Peaks:</strong><br>Abra a aba de calendário na plataforma <a href="https://app.trainingpeaks.com/#calendar">Training Peaks</a>.</li><li><strong>Localize o Arquivo:</strong><br>Vá até a pasta de “Downloads” do seu computador, onde o arquivo TCX foi salvo.</li><li><strong>Importe o Treino:</strong><br>Arraste o arquivo TCX e solte-o na aba do calendário do Training Peaks.</li></ul><p>Com esses passos, seu treino estará devidamente exportado do Strava para o Training Peaks!</p><h4><strong>Como Contribuir</strong></h4><p>Contribuições são sempre bem-vindas e essenciais para o aprimoramento deste projeto! Se você compartilha a paixão por tecnologia, esportes e automação, junte-se a nós e ajude a transformar essa ferramenta em algo ainda mais robusto e útil para a comunidade. Veja como você pode colaborar:</p><p><strong>1. Reporte Problemas e Melhorias</strong><br>Se encontrar algum <em>bug</em> ou comportamento inesperado, ou até memos se tiver alguma sugestão de melhoria, abra uma <em>issue </em>no GitHub descrevendo detalhadamente do que ocorreu ou do que você gostaria que o projeto tivesse. Isso nos ajuda a dar os próximos passos no nosso projeto.</p><p><strong>2. Envie Pull Requests</strong><br>Todavia, se você é como eu, gosta de colocar a mão na massa e deseja contribuir diretamente com o código ou alguma documentação. Faça um <em>fork</em> do repositório, implemente suas alterações e envie um <em>pull request. </em>Mas lembre-se de seguir as diretrizes do projeto e incluir uma descrição clara das mudanças propostas.</p><p><strong>3. Compartilhe e Divulgue</strong><br>Finalmente, se você gostou do projeto, deixe uma estrela no repositório, compartilhe com amigos e nas suas redes sociais, e incentive outros a contribuírem também.</p><p>Cada contribuição, por menor que seja, faz uma grande diferença.</p><h4>Considerações Finais</h4><p>Após seguir todos os passos descritos, seu treino será sincronizado com o Training Peaks, permitindo que seu treinador identifique pontos de atenção e acompanhe sua performance de forma personalizada. Essa integração não só facilita o monitoramento dos seus treinos, mas também abre novas possibilidades para análises detalhadas.</p><p>Além disso, o projeto possibilita a coleta completa dos dados do exercício, o que pode ser explorado para aplicar técnicas de inteligência artificial e gerar projeções ou análises mais profundas sobre seu desempenho.</p><p><strong>Lembre-se:</strong> este projeto está em constante evolução e é <em>open-source</em>, o que significa que você pode contribuir com melhorias, novas funcionalidades e correções.</p><p>Por fim, segue o link do projeto na versão que contempla tudo que foi explanado até o momento.</p><p><a href="https://github.com/Lucs1590/strava-to-trainingpeaks/tree/0.3.0">GitHub - Lucs1590/strava-to-trainingpeaks at 0.3.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b54aa496c6e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strava to TrainingPeaks]]></title>
            <link>https://levelup.gitconnected.com/strava-to-trainingpeaks-fa3a0fa05f79?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3a0fa05f79</guid>
            <category><![CDATA[trainingpeaks]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[strava]]></category>
            <category><![CDATA[sports]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 01:06:53 GMT</pubDate>
            <atom:updated>2025-03-12T01:06:53.448Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to connect Strava workouts to Training Peaks (TP)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pfmp4xKyCw9RNTWb" /><figcaption>Photo by <a href="https://unsplash.com/@ashleydelotz?utm_source=medium&amp;utm_medium=referral">Ashley de Lotz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Project Motivation</h4><p>Since childhood, my parents encouraged me to practice sports, and during my teenage years, my interest in technology, data, and artificial intelligence grew alongside it. This combination of passions has always been essential to me, and today, I strive to integrate them innovatively.</p><p>For the past few years, I have primarily focused on running. However, last year, I decided to challenge myself by training for a triathlon — a sport that combines swimming, cycling, and running. It turned out to be far more complex and demanding than anything I had experienced before.</p><p>As I took on this new challenge, I sought guidance from a triathlon coach. In our discussions, we aligned on my goals, conducted a complete metabolic assessment, and reviewed my training approach. He also introduced me to the <a href="http://www.trainingpeaks.com/">Training Peaks platform</a>. According to him, if I used a smartwatch from brands like Garmin or Polar, my workouts would sync automatically with the platform, allowing for seamless tracking of my training plan.</p><p>However, I chose to use a Samsung smartwatch (Galaxy Watch 4), which created a unique challenge. While my workouts were automatically synced with <a href="https://www.strava.com/">Strava</a>, there was no direct integration with Training Peaks. Faced with this situation, I had two options: <strong>manually upload my workouts</strong>, as recommended by Training Peaks <a href="https://help.trainingpeaks.com/hc/en-us/articles/204070254-How-Do-I-Sync-My-Workout-Data-From-Strava-Into-TrainingPeaks">(How to sync your Strava data with Training Peaks)</a>, or<strong> develop a solution to automate the process of downloading data from Strava and uploading it to Training Peaks</strong>. Naturally, I chose the challenge of building this solution!</p><h4>Project Development</h4><p>One of the key features of this application is its <strong>interactivity</strong>, allowing users to select the sport or activity they want to sync between platforms. This functionality is crucial because the method for downloading data from Strava varies depending on the activity type.</p><p>For example:</p><ul><li><strong>Running and cycling</strong>: Simply add /export_tcx to the end of the activity URL to obtain a TCX file.</li><li><strong>Swimming</strong>: You need to add /export_original to the URL, as the standard method does not generate the file correctly.</li></ul><p>In both cases, the downloaded file is in TCX format. Developed by <a href="https://www.garminstore.com/">Garmin</a> in 2007, TCX was designed to transmit XML-based data such as latitude and longitude points, heart rate, cadence, and calories — whether for indoor or outdoor activities. However, its usage is mostly confined to Garmin’s ecosystem, and competitors don’t offer the same level of compatibility.</p><p>Once the sport is selected and the TCX file is obtained (either through automatic download or manual selection), the data processing phase begins, which consists of:</p><ol><li><strong>Validation</strong>: For running and cycling, the file is read using the <a href="https://pypi.org/project/tcxreader/">tcxreader</a> library and checked to ensure the XML structure is correct.</li><li><strong>Specific Adjustments for Swimming</strong>: Since the file is downloaded using a different URL format, it requires additional processing to fix the default XML header and adjust certain data types.</li><li><strong>Finalization</strong>: Finally, the file is properly formatted with correct indentation, resulting in a TCX file that is fully compatible with Training Peaks.</li></ol><p>Voilà! With these steps, the user gets a properly processed TCX file, ready for upload to the platform.</p><h4>How to Use</h4><p>This project primarily operates through a command-line interface (CLI). To get started, ensure you have <a href="https://www.python.org/">Python</a> installed and set up with all necessary dependencies. Follow these steps:</p><p><strong>1.Clone the Repository<br></strong>Download the project to your local environment by running:</p><pre>git clone https://github.com/Lucs1590/strava-to-trainingpeaks</pre><p><strong>2.Install Dependencies<br></strong>Navigate to the project directory and install the required libraries:</p><pre>cd strava-to-trainingpeaks<br>pip install -r requirements.txt</pre><p><strong>3.Global Script Installation<br></strong>To allow execution from any directory, install the project globally:</p><pre>pip install .</pre><p><strong>4.Run the Main Command<br></strong>Once installed, you can execute the script from anywhere using:</p><pre>strava-to-trainingpeaks</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*m8xBVZZSwNmdPnhauFhxjw.png" /><figcaption>Main command being executed via CLI.</figcaption></figure><p><strong>5.Complete the Pipeline Manually</strong><br>While most of the process is automated, a few manual steps are required to finalize the integration:</p><ul><li><strong>Open the Training Peaks Calendar:</strong><br>Access the <a href="https://app.trainingpeaks.com/#calendar">calendar tab</a> in the Training Peaks platform.</li><li><strong>Locate the File:</strong><br>Go to your computer’s “Downloads” folder, where the TCX file was saved.</li><li><strong>Import the Workout:</strong><br>Drag and drop the TCX file into the Training Peaks calendar tab.</li></ul><p>With these steps completed, your workout will be successfully exported from Strava to Training Peaks!</p><h4>How to Contribute</h4><p>Contributions are always welcome and essential for improving this project! If you share a passion for technology, sports, and automation, join us in making this tool even more robust and valuable for the community. Here’s how you can help:</p><p><strong>1. Report Issues and Suggest Improvements<br></strong>If you come across a bug, an unexpected behavior, or have ideas for improvements, open an issue on GitHub with a detailed description of the problem or feature request. Your feedback helps shape the next steps of the project.</p><p><strong>2. Submit Pull Requests<br></strong>If you enjoy getting hands-on, you can contribute directly to the code or documentation. Fork the repository, make your changes, and submit a pull request. Be sure to follow the project guidelines and include a clear description of your modifications.</p><p><strong>3. Share and Spread the Word<br></strong>If you like this project, consider giving it a star on GitHub, sharing it with friends, and posting about it on your social media. Encouraging others to contribute helps grow the community and improve the project even further.</p><p>Even the smallest contribution makes a big difference!</p><h4>Final Considerations</h4><p>By following all the steps outlined, your workout will be successfully synchronized with Training Peaks, allowing your coach to identify key insights and track your performance in a personalized way. This integration not only simplifies workout monitoring but also opens new possibilities for detailed analysis.</p><p>Additionally, the project enables the complete collection of exercise data, which can be leveraged to apply artificial intelligence techniques for projections and deeper performance analysis.</p><p><strong>Remember</strong>, this project is constantly evolving and is open-source, meaning you can contribute by adding improvements, new features, and fixes.</p><p>Finally, here is the link to the project in its current version, which includes everything covered so far:</p><p><a href="https://github.com/Lucs1590/strava-to-trainingpeaks/tree/0.3.0">GitHub - Lucs1590/strava-to-trainingpeaks at 0.3.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3a0fa05f79" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/strava-to-trainingpeaks-fa3a0fa05f79">Strava to TrainingPeaks</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying FastAPI in Production: A Guide to Optimizing FastAPI Performance with Gunicorn]]></title>
            <link>https://levelup.gitconnected.com/deploying-fastapi-in-production-a-guide-to-optimizing-fastapi-performance-with-gunicorn-cf78c57b155b?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf78c57b155b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 17:50:16 GMT</pubDate>
            <atom:updated>2024-11-05T17:50:16.212Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering FastAPI Deployment: Best Practices for Performance, Security, and Scalability in Production</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hf7u2RXbnrzyd5Xb" /><figcaption>Photo by <a href="https://unsplash.com/@trinwin?utm_source=medium&amp;utm_medium=referral">Trinity Nguyen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>When the goal is to run a FastAPI application in a production environment, it is essential to consider some fundamental aspects. According to the official documentation, one of the best practices is to use containers to facilitate the deployment and scalability of APIs. Containers, such as those provided by Docker, ensure that the application’s dependencies and environment are standardized, allowing the “productionization” process to occur more efficiently.</p><p>In addition to the use of containers, other critical factors for optimizing performance include specific Gunicorn configurations, such as the number of workers and the process management model. Below, we will explore these and other aspects in detail that contribute to better FastAPI performance in production.</p><h3><strong>Using Containers</strong></h3><p>Deploying APIs in production with FastAPI often involves using Docker containers, a well-established practice that offers isolation for the application and its dependencies, keeping them separate from other containers and services on the system. This not only simplifies dependency management but also ensures that the application environment remains consistent across different executions.</p><p>Additionally, containers have a significantly lower resource consumption compared to virtual machines, as they typically run only a single isolated process. This reduced overhead is particularly advantageous for APIs, as it facilitates security, network configurations, development, and deployment.<br>The use of containers introduces the concept of container images, which are essentially ready-to-use templates from which containers are launched. These images contain specific versions of the necessary files, libraries, and configurations, ensuring predictability and consistency in the application’s behavior. In short, a container image acts as a template that, when executed, creates a container with the necessary instructions to run the application in isolation.</p><p>Containers remain active as long as the main command or configured process is running — exactly what is expected for FastAPI-based APIs. However, if no active processes are running, the container is automatically terminated.</p><p>Here is an example of a basic Dockerfile for a FastAPI application:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><p>This file is usually saved as <strong>Dockerfile</strong>, and to build the image, simply execute the following command:</p><pre>docker build -t api-image .</pre><p>And to run the container, the command would be:</p><pre>docker run -d --name mycontainer -p 80:80 api-image</pre><p>This process works perfectly, as long as some prerequisites are met, such as:</p><ul><li>Correct organization of directories and files (refer to: <a href="https://fastapi.tiangolo.com/deployment/docker/#directory-structure">FastAPI Docker — Directory Structure</a>);</li><li>A requirements.txt that correctly lists the application dependencies (see more at: <a href="https://fastapi.tiangolo.com/deployment/docker/#package-requirements">FastAPI Docker — Package Requirements</a>);</li><li>Error-free code in the main.py file (refer to the documentation: <a href="https://fastapi.tiangolo.com/deployment/docker/#create-the-fastapi-code">FastAPI Docker — Creating FastAPI Code</a>).</li></ul><p>After understanding the creation and use of containers, it’s essential to know other factors that optimize the use of APIs in production. Below, we will detail important points such as:</p><ul><li>HTTPS;</li><li>Startup configurations;</li><li>Automatic restarts;</li><li>Replication;</li><li>Memory optimization.</li></ul><h3><strong>HTTPS</strong></h3><p>When discussing HTTP and HTTPS protocols, it’s important to highlight that HTTPS offers a much higher level of security, as it uses encryption to protect the data transfer between the client and server. This is crucial for APIs, especially when they interact with external applications, where the protection of sensitive data becomes a priority.</p><p>In the official FastAPI documentation, there is a clear recommendation that HTTPS should be used whenever possible, particularly in production. Many hosting providers offer free SSL certificates, which simplifies the configuration of HTTPS connections.</p><p>Furthermore, if your application is behind a Proxy or Load Balancer, adjustments are necessary in the FastAPI application’s startup command. To ensure that the HTTP headers sent by the proxy are correctly forwarded to the application, you should add the --proxy-headers option. This ensures that the FastAPI application properly processes information about the original client (such as the IP address) in proxy scenarios.</p><p>Here is an updated example of the Dockerfile, with the inclusion of the --proxy-headers parameter:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><p>This command allows your FastAPI application to work properly behind a proxy while maintaining the security and integrity of the transferred data.</p><h3><strong>Startup Applications</strong></h3><p>There are several ways to initialize a container with FastAPI, from using Docker to more advanced solutions like Kubernetes. The choice of the ideal tool depends on the API’s complexity, the available infrastructure, and the project’s scope. The most common options include:</p><ul><li><strong>Docker</strong>: A simple and efficient solution for local development and less complex deployments. It is ideal for testing and running the application in an isolated environment with all dependencies configured.</li><li><strong>Docker Compose</strong>: Useful for orchestrating multiple containers that need to work together, such as when an API depends on a database or other services.</li><li><strong>Kubernetes</strong>: A robust tool suitable for managing containers at scale. It offers high availability, scalability, and automatic load balancing, making it ideal for large-scale APIs and distributed systems.</li></ul><p>The choice between these options should consider the project’s size, scalability requirements, and the level of automation desired in the deployment process.</p><h3><strong>Restarts</strong></h3><p>In production environments, it is essential to ensure that the FastAPI application can recover from unexpected failures. A common practice is to configure automatic restart mechanisms to prevent the application from becoming unavailable after an error. This can be done using features provided by Docker and Kubernetes.</p><p>A good practice in API development is to handle known errors directly in the code, returning appropriate status codes, such as 422 Unprocessable Entity, for invalid inputs. For example, if a user sends a boolean value instead of a number, the code can return this status without crashing the application.</p><p>However, some errors may be unpredictable and difficult to foresee. In these cases, rather than allowing the application to become completely unavailable, it is recommended to use an automatic restart mechanism. In Docker, this can be configured with the --restart option, which causes the container to restart automatically in case of failure.</p><p>Here is an updated example of the Dockerfile with the restart configuration:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;, &quot;--restart&quot;]</pre><p>In <strong>Docker Compose</strong>, you can add the restart configuration directly in the docker-compose.yml file:</p><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    image: api-image<br>    restart: always<br>    ports:<br>      - &quot;80:80&quot;</pre><p>This ensures that in case of an unexpected failure, the application will restart automatically, minimizing the impact in production.</p><h3><strong>Replication</strong></h3><p>The need for replication and scalability is one of the main reasons for optimizing the performance of APIs in production. In development environments, it’s generally not necessary to split requests across multiple processes, but in production, this practice is essential to ensure that the application remains efficient under high user load.</p><p>Process replication, also known as the use of multiple workers, is an approach recommended in the FastAPI documentation for handling a large volume of requests. In situations where the API is running on a machine with multiple CPU cores, or when traffic is too high for a single process, it is possible to use several processes (or “workers”) to divide the load. This ensures that multiple requests can be processed simultaneously, increasing efficiency and reducing response time.</p><p>This approach involves running multiple instances of the same API, where all instances “listen” for requests on the same port and divide the work among themselves. FastAPI, along with tools like Uvicorn and Gunicorn, makes it easy to configure these multiple workers, providing greater resilience and scalability.</p><h4><strong>Uvicorn vs. Gunicorn</strong></h4><p>Both Uvicorn and Gunicorn are popular for running APIs with FastAPI, but they have differences in process management:</p><ul><li><strong>Uvicorn</strong> is a lightweight and efficient ASGI server, ideal for simple, smaller-scale scenarios.</li><li><strong>Gunicorn</strong>, on the other hand, is a more robust WSGI server that can manage multiple processes more efficiently, especially in large-scale production environments. It also offers additional features like better worker control and automatic failure recovery, making it more suitable for high-availability scenarios.</li></ul><p>However, to get the best of both worlds, it’s common to use Gunicorn in combination with Uvicorn (via uvicorn.workers.UvicornWorker), resulting in a powerful server with greater control over processes, and more suited for complex production scenarios.</p><p><strong>Example with Uvicorn</strong></p><p>Here’s an example of a configuration to start multiple workers using Uvicorn alone:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;, &quot;--workers&quot;, &quot;4&quot;, &quot;--restart&quot;]</pre><p>This example uses 4 workers to process requests in parallel, improving the API’s ability to handle multiple simultaneous connections.</p><p><strong>Example with Gunicorn</strong></p><p>If the application requires more control and resilience, Gunicorn with Uvicorn is a more robust option. Below is an example of a Dockerfile using Gunicorn with 4 workers:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;gunicorn&quot;, &quot;-k&quot;, &quot;uvicorn.workers.UvicornWorker&quot;, &quot;app.main:app&quot;, &quot;--workers&quot;, &quot;4&quot;, &quot;--bind&quot;, &quot;0.0.0.0:80&quot;]</pre><p>This configuration takes advantage of Uvicorn’s efficiency but with Gunicorn’s robustness for process management, ensuring high availability and better performance in production environments.</p><h3><strong>Memory</strong></h3><p>When optimizing APIs for production, memory management is a crucial aspect that requires attention, especially when dealing with multiple workers. Unlike other optimizations, such as process tuning or proxy configuration, memory management heavily depends on the careful analysis of the specific needs of the application.</p><p>Each worker process running your application consumes a certain amount of memory, which includes execution variables, machine learning models (if used), cache, and other necessary data. In the case of multiple workers, it’s important to understand that each worker consumes its own portion of memory, and they do not share memory between them. This means that the total memory consumption will be the sum of the consumption of each worker.</p><p>When configuring multiple workers, a key point is ensuring that the server or instance running the application has enough RAM to support the load of each process. For example, if your instance has 10 GB of RAM and each worker consumes about 2 GB, starting 6 workers will exceed the available memory limit, which can lead to serious issues such as crashes or slowness.</p><p>Visually, this dynamic can be represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*xCnBdZ5oWnZKDEz-WJJ-Tw.png" /></figure><p>In the image, we see how the process manager distributes CPU usage among the workers and how each worker allocates a specific amount of RAM. This model clearly demonstrates that memory is duplicated for each worker, reinforcing the need for proper planning to avoid resource exhaustion.</p><h3><strong>Final Considerations</strong></h3><p>In this article, we explored best practices for optimizing and deploying a FastAPI application in production. We covered crucial aspects such as the use of containers, replication, memory management, and secure protocols, as well as analyzed how Gunicorn and Uvicorn can be used in different production scenarios.</p><p>With this detailed overview, you are now better prepared to adjust your API configuration according to your project’s needs. Elements like the number of workers, connection timeout, and the use of threads are just some of the variables available in Gunicorn to maximize performance. Each adjustment can directly impact the scalability and efficiency of your application.</p><p>Additionally, it’s important to consider whether FastAPI is truly the best choice for your use case. While it is an excellent option for high-performance APIs and easy to implement, alternatives like Django, Flask, and Bottle also offer distinct advantages, especially in terms of scalability, library integration, and ease of use. Evaluating these points in the context of your project can help you choose the most suitable solution.</p><p>Finally, remember that deploying an API in production involves more than just writing optimized code. The security provided by using HTTPS, efficient memory management, and a robust container configuration are essential factors to ensure success in production environments. The next step is to apply these configurations, test them in your environment, and adjust them as necessary, always striving for maximum performance, stability, and availability of your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf78c57b155b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deploying-fastapi-in-production-a-guide-to-optimizing-fastapi-performance-with-gunicorn-cf78c57b155b">Deploying FastAPI in Production: A Guide to Optimizing FastAPI Performance with Gunicorn</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Otimização de APIs em Produção: Usando FastAPI e Gunicorn]]></title>
            <link>https://medium.com/data-hackers/otimiza%C3%A7%C3%A3o-de-apis-em-produ%C3%A7%C3%A3o-usando-fastapi-e-gunicorn-3eec9bd24ef4?source=rss-5289873d4c37------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eec9bd24ef4</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lucas de Brito Silva]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 11:39:59 GMT</pubDate>
            <atom:updated>2024-11-06T14:36:32.449Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Descubra como usar containers, configurar workers, otimizar memória e aplicar práticas seguras em APIs com FastAPI no ambiente de produção</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U53TXXYbZVH_llZK" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introdução</h3><p>Quando o objetivo é executar uma aplicação FastAPI em um ambiente de produção, é essencial considerar alguns aspectos fundamentais. De acordo com a documentação oficial, uma das melhores práticas é <strong>utilizar containers</strong> para facilitar a implantação e escalabilidade das APIs. Containers, como os fornecidos pelo Docker, garantem que as dependências e o ambiente da aplicação sejam padronizados, permitindo que o processo de “produtização” ocorra de forma mais eficiente.</p><p>Além do uso de containers, outros fatores críticos para otimizar a performance incluem configurações específicas do Gunicorn, como o número de workers e o modelo de gerenciamento de processos. A seguir, exploraremos em detalhes esses e outros aspectos que contribuem para um melhor desempenho da FastAPI em produção.</p><h3>Uso de Containers</h3><p>O deploy de APIs em produção com FastAPI frequentemente envolve o uso de <strong>containers Docker</strong>, uma prática consolidada que oferece isolamento da aplicação e suas dependências, mantendo-as separadas de outros containers e serviços no sistema. Isso não apenas <strong>simplifica a gestão de dependências</strong>, mas também garante que o ambiente da aplicação seja consistente em diferentes execuções.</p><p>Além disso, containers têm um consumo de recursos significativamente menor quando comparados a máquinas virtuais, uma vez que normalmente executam apenas um processo isolado. Esse modelo reduzido de overhead é particularmente vantajoso para APIs, já que facilita aspectos relacionados à <strong>segurança</strong>, <strong>configurações de rede</strong>, <strong>desenvolvimento</strong> e <strong>deploy</strong>.</p><p>O uso de containers introduz o conceito de <strong>imagens de container</strong>, que são basicamente modelos prontos a partir dos quais os containers são executados. Essas imagens contêm versões específicas dos arquivos, bibliotecas e configurações necessárias, garantindo previsibilidade e consistência no comportamento da aplicação. Em resumo, uma imagem de container age como um <strong>template</strong>, que, ao ser executado, cria um container com as instruções necessárias para rodar a aplicação de forma isolada.</p><p>Containers ficam ativos enquanto o comando principal ou o processo configurado estiverem rodando — O que é exatamente o esperado para APIs em FastAPI. No entanto, se não houverem processos ativos, o container é finalizado automaticamente.</p><p>Aqui está um exemplo de um Dockerfile básico para uma aplicação FastAPI:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><p>Normalmente, esse arquivo é salvo como Dockerfile, e para construir a imagem, basta executar o seguinte comando:</p><pre>docker build -t api-image .</pre><p>E para rodar o container, o comando seria:</p><pre>docker run -d --name mycontainer -p 80:80 api-image</pre><p>Esse processo funciona perfeitamente, desde que alguns pré-requisitos sejam atendidos, como:</p><ul><li>Organização correta dos diretórios e arquivos (consulte: <a href="https://fastapi.tiangolo.com/deployment/docker/#directory-structure">FastAPI Docker — Estrutura de Diretórios</a>);</li><li>Um requirements.txt que lista corretamente as dependências da aplicação (veja mais em: <a href="https://fastapi.tiangolo.com/deployment/docker/#package-requirements">FastAPI Docker - Requisitos de Pacotes</a>);</li><li>Código livre de erros no arquivo main.py (veja a documentação: <a href="https://fastapi.tiangolo.com/deployment/docker/#create-the-fastapi-code">FastAPI Docker - Criar Código FastAPI</a>).</li></ul><p>Depois de entender a criação e uso de containers, é essencial conhecer outros fatores que otimizam o uso das APIs em produção. A seguir, detalharemos pontos importantes, como:</p><ul><li>HTTPS;</li><li>Configurações de Inicialização;</li><li>Restarts automáticos;</li><li>Replicação;</li><li>Otimização de memória.</li></ul><h3>HTTPS</h3><p>Ao discutir os protocolos HTTP e HTTPS, é importante destacar que o <strong>HTTPS</strong> oferece um nível muito mais alto de segurança, pois utiliza criptografia para proteger a transferência de dados entre cliente e servidor. Isso é crucial para APIs, especialmente quando elas interagem com aplicativos externos, onde a proteção de dados sensíveis se torna prioridade.</p><p>Na documentação oficial do FastAPI, há uma recomendação clara de que o uso de HTTPS é preferível sempre que possível, principalmente em produção. Muitos provedores de hospedagem oferecem certificados SSL gratuitos, o que simplifica a configuração de conexões HTTPS.</p><p>Além disso, se sua aplicação estiver por trás de um <strong>Proxy</strong> ou <strong>Load Balancer</strong>, é necessário fazer ajustes no comando de inicialização da aplicação em FastAPI. Para garantir que os cabeçalhos HTTP enviados pelo proxy sejam repassados corretamente até a aplicação, você deve adicionar a opção --proxy-headers. Isso garante que a aplicação FastAPI processe corretamente as informações sobre o cliente original (como o IP) em cenários de proxy.</p><p>Aqui está um exemplo atualizado do Dockerfile, com a inclusão do parâmetro --proxy-headers:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><p>Esse comando permite que sua aplicação FastAPI funcione de maneira adequada atrás de um proxy, mantendo a segurança e a integridade dos dados transferidos.</p><h3>Aplicações para Inicialização</h3><p>Existem várias maneiras de inicializar um <em>container</em> com FastAPI, desde o uso de Docker até soluções mais avançadas como Kubernetes. A escolha da ferramenta ideal depende da complexidade da API, da infraestrutura disponível e do escopo do projeto. As opções mais comuns incluem:</p><ol><li><strong>Docker</strong>: Uma solução simples e eficiente para desenvolvimento local e implantações de menor complexidade. É ideal para testar e rodar a aplicação em um ambiente isolado com todas as dependências configuradas.</li><li><strong>Docker Compose</strong>: Útil para orquestrar múltiplos containers que precisam trabalhar em conjunto, como quando uma API depende de um banco de dados ou de outros serviços.</li><li><strong>Kubernetes</strong>: Uma ferramenta robusta, adequada para gerenciar containers em grande escala. Oferece alta disponibilidade, escalabilidade e balanceamento de carga automático, sendo ideal para APIs de grande porte e sistemas distribuídos.</li></ol><p>A escolha entre essas opções deve considerar o tamanho do projeto, os requisitos de escalabilidade e o nível de automação desejado no processo de <em>deploy</em>.</p><h3>Restarts</h3><p>Em ambientes de produção, é essencial garantir que a aplicação FastAPI possa se recuperar de falhas inesperadas. Uma prática comum é configurar mecanismos de <strong>reinicialização automática</strong> para evitar que a aplicação fique indisponível após um erro. Isso pode ser feito utilizando funcionalidades oferecidas pelo Docker e Kubernetes.</p><p>Uma boa prática no desenvolvimento de APIs é tratar erros conhecidos diretamente no código, retornando códigos de status apropriados, como o 422 Unprocessable Entity, para entradas inválidas. Por exemplo, se um usuário enviar um dado do tipo booleano em vez de um número, o código pode retornar esse status sem quebrar a aplicação.</p><p>No entanto, alguns erros podem ser imprevisíveis e difíceis de prever. Para esses casos, em vez de permitir que a aplicação fique completamente indisponível, é recomendado o uso de um mecanismo de reinicialização automática. No Docker, isso pode ser configurado com a opção --restart, que faz com que o container reinicie automaticamente em caso de falha.</p><p>Aqui está um exemplo atualizado do Dockerfile com a configuração de reinicialização:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;fastapi&quot;, &quot;run&quot;, &quot;app/main.py&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;, &quot;--restart&quot;]</pre><p>No Docker Compose, você pode adicionar a configuração de restart diretamente no arquivo docker-compose.yml:</p><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    image: api-image<br>    restart: always<br>    ports:<br>      - &quot;80:80&quot;</pre><p>Isso garante que, em caso de falha inesperada, a aplicação será reiniciada automaticamente, minimizando o impacto em produção.</p><h3>Replicação</h3><p>A necessidade de replicação e escalabilidade é um dos principais motivos para otimizar o desempenho de APIs em produção. Em ambientes de desenvolvimento, geralmente não se pensa em dividir as requisições entre múltiplos processos, mas em produção, essa prática é essencial para garantir que a aplicação continue eficiente sob alta carga de usuários.</p><p>A <strong>replicação</strong> de processos, também conhecida como o uso de <strong>múltiplos workers</strong>, é uma abordagem recomendada pela documentação do FastAPI para lidar com um grande volume de requisições. Em situações em que a API está sendo executada em uma máquina com múltiplos núcleos de CPU, ou quando o tráfego é muito alto para um único processo, é possível utilizar vários processos (ou “workers”) para dividir a carga. Isso garante que várias requisições possam ser processadas simultaneamente, aumentando a eficiência e diminuindo o tempo de resposta.</p><p>Essa abordagem envolve a execução de múltiplos processos da mesma API, onde todos “ouvem” as requisições na mesma porta e dividem o trabalho entre si. A FastAPI, em conjunto com ferramentas como <strong>Uvicorn</strong> e <strong>Gunicorn</strong>, facilita a configuração desses múltiplos workers, proporcionando maior resiliência e escalabilidade.</p><h4>Uvicorn vs. Gunicorn</h4><p>Tanto <strong>Uvicorn</strong> quanto <strong>Gunicorn</strong> são populares para a execução de APIs com FastAPI, mas eles têm diferenças em termos de gerenciamento de processos:</p><ul><li><strong>Uvicorn</strong> é um servidor ASGI leve e eficiente, ideal para cenários simples e de menor escala.</li><li><strong>Gunicorn</strong>, por outro lado, é um servidor WSGI mais robusto, que pode gerenciar múltiplos processos de maneira mais eficiente, especialmente em ambientes de produção de grande escala. Ele também oferece recursos adicionais, como melhor controle de workers e recuperação automática de falhas, o que o torna mais adequado para cenários de alta disponibilidade.</li></ul><p>No entanto, para obter o melhor dos dois mundos, é comum usar <strong>Gunicorn</strong> em combinação com <strong>Uvicorn</strong> (via uvicorn.workers.UvicornWorker), resultando em um servidor poderoso, com maior controle sobre os processos e mais adequado para cenários de produção complexos.</p><h4>Exemplo com Uvicorn</h4><p>Aqui está um exemplo de configuração para iniciar múltiplos workers usando apenas o Uvicorn:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--proxy-headers&quot;, &quot;--port&quot;, &quot;80&quot;, &quot;--workers&quot;, &quot;4&quot;, &quot;--restart&quot;]</pre><p>Esse exemplo utiliza 4 workers para processar requisições em paralelo, melhorando a capacidade da API de lidar com várias conexões simultâneas.</p><h4>Exemplo com Gunicorn</h4><p>Caso a aplicação exija maior controle e resiliência, o Gunicorn com Uvicorn é uma opção mais robusta. A seguir, um exemplo de Dockerfile usando Gunicorn com 4 workers:</p><pre>FROM python:3.9<br><br>WORKDIR /code<br><br>COPY ./requirements.txt /code/requirements.txt<br><br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br><br>COPY ./app /code/app<br><br>CMD [&quot;gunicorn&quot;, &quot;-k&quot;, &quot;uvicorn.workers.UvicornWorker&quot;, &quot;app.main:app&quot;, &quot;--workers&quot;, &quot;4&quot;, &quot;--bind&quot;, &quot;0.0.0.0:80&quot;]</pre><p>Essa configuração aproveita a eficiência do Uvicorn, mas com a robustez do Gunicorn para gerenciamento de processos, garantindo alta disponibilidade e melhor performance em ambientes de produção.</p><h3>Memória</h3><p>Ao otimizar APIs para produção, o gerenciamento de memória é um aspecto crucial que requer atenção, especialmente quando lidamos com múltiplos workers. Diferente de outras otimizações, como o ajuste de processos ou a configuração de proxies, a gestão de memória depende muito da análise cuidadosa das necessidades específicas da aplicação.</p><p>Cada processo worker que executa a sua aplicação consome uma quantidade de memória, que inclui variáveis de execução, modelos de machine learning (se utilizados), cache e outros dados necessários. No caso de múltiplos workers, é importante entender que <strong>cada worker consome sua própria porção de memória</strong> e <strong>não compartilham</strong> essa memória entre si. Isso significa que o consumo de memória total será a soma do consumo de cada worker.</p><p>Um ponto de atenção ao configurar múltiplos workers é garantir que o servidor ou a instância em que a aplicação está sendo executada tenha memória RAM suficiente para suportar a carga de cada processo. Por exemplo, se a sua instância tem 10 GB de RAM e cada worker consome cerca de 2 GB, iniciar 6 workers ultrapassará o limite de memória disponível, o que pode causar problemas graves, como crashes ou lentidão.</p><p>Visualmente, essa dinâmica pode ser representada da seguinte forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*xCnBdZ5oWnZKDEz-WJJ-Tw.png" /></figure><p>Na imagem, vemos como o <strong>gerenciador de processos</strong> distribui o uso da CPU entre os workers, e como cada worker aloca uma quantidade específica de RAM. Esse modelo demonstra claramente que a memória é duplicada para cada worker, reforçando a necessidade de planejamento adequado para evitar esgotamento dos recursos.</p><h3>Considerações Finais</h3><p>Neste artigo, exploramos as melhores práticas para otimizar e colocar uma aplicação FastAPI em produção. Abordamos aspectos cruciais como o uso de containers, replicação, gerenciamento de memória, e protocolos seguros, além de analisar como Gunicorn e Uvicorn podem ser utilizados em diferentes cenários de produção.</p><p>Com essa visão detalhada, você agora está mais preparado para ajustar a configuração de sua API conforme as necessidades do seu projeto. Elementos como o número de workers, tempo limite de conexão e o uso de threads são apenas algumas das variáveis disponíveis no Gunicorn para maximizar a performance. Cada ajuste pode impactar diretamente na escalabilidade e eficiência da sua aplicação.</p><p>Além disso, é importante considerar se FastAPI é realmente a melhor escolha para o seu caso de uso. Embora seja uma excelente opção para APIs de alta performance e fácil de implementar, alternativas como Django, Flask e Bottle também oferecem vantagens distintas, especialmente em termos de escalabilidade, integração de bibliotecas e facilidade de uso. Avaliar esses pontos no contexto do seu projeto pode ajudá-lo a escolher a solução mais adequada.</p><p>Por fim, lembre-se de que colocar uma API em produção envolve mais do que apenas a escrita de código otimizado. A segurança garantida pelo uso de HTTPS, o gerenciamento eficiente da memória e uma configuração robusta de containers são fatores essenciais para garantir o sucesso em ambientes de produção. O próximo passo é aplicar essas configurações, testar no seu ambiente e ajustá-las conforme necessário, buscando sempre a máxima performance, estabilidade e disponibilidade da sua aplicação.</p><h3>Referências</h3><ul><li><a href="https://fastapi.tiangolo.com/deployment/server-workers/">https://fastapi.tiangolo.com/deployment/server-workers/</a></li><li><a href="https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc">https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc</a></li><li><a href="https://stackoverflow.com/questions/66254371/fastapi-gunicorn-uvicorn-for-production-deployment-with-google-cloud-run-stress">https://stackoverflow.com/questions/66254371/fastapi-gunicorn-uvicorn-for-production-deployment-with-google-cloud-run-stress</a></li><li><a href="https://dylancastillo.co/posts/fastapi-nginx-gunicorn.html#prerequisites">https://dylancastillo.co/posts/fastapi-nginx-gunicorn.html#prerequisites</a></li><li><a href="https://medium.com/@kevinzeladacl/deploy-a-fastapi-app-with-nginx-and-gunicorn-b66ac14cdf5a">https://medium.com/@kevinzeladacl/deploy-a-fastapi-app-with-nginx-and-gunicorn-b66ac14cdf5a</a></li><li><a href="https://docs.vultr.com/how-to-deploy-fastapi-applications-with-gunicorn-and-nginx-on-ubuntu-20-04">https://docs.vultr.com/how-to-deploy-fastapi-applications-with-gunicorn-and-nginx-on-ubuntu-20-04</a></li><li><a href="https://fastapi.tiangolo.com/alternatives/#benchmarks-and-speed">https://fastapi.tiangolo.com/alternatives/#benchmarks-and-speed</a></li><li><a href="https://medium.com/@carlosmarcano2704/seven-alternatives-to-fastapi-to-explore-and-contribute-python-47bcd394bf31">https://medium.com/@carlosmarcano2704/seven-alternatives-to-fastapi-to-explore-and-contribute-python-47bcd394bf31</a></li><li><a href="https://slashdot.org/software/p/Bottle/">https://slashdot.org/software/p/Bottle/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eec9bd24ef4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-hackers/otimiza%C3%A7%C3%A3o-de-apis-em-produ%C3%A7%C3%A3o-usando-fastapi-e-gunicorn-3eec9bd24ef4">Otimização de APIs em Produção: Usando FastAPI e Gunicorn</a> was originally published in <a href="https://medium.com/data-hackers">Data Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>