<?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 Tomás Manzur on Medium]]></title>
        <description><![CDATA[Stories by Tomás Manzur on Medium]]></description>
        <link>https://medium.com/@tommanzur?source=rss-e10e29dab75e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uEjssOp5t9iYyml1nGzFgg.jpeg</url>
            <title>Stories by Tomás Manzur on Medium</title>
            <link>https://medium.com/@tommanzur?source=rss-e10e29dab75e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:38:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tommanzur/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[Django Essentials: Step-by-Step Learning]]></title>
            <link>https://medium.com/django-unleashed/django-essentials-step-by-step-learning-42a8398c94a8?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a8398c94a8</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 03:45:32 GMT</pubDate>
            <atom:updated>2024-06-17T05:44:26.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Django_tutorial" src="https://cdn-images-1.medium.com/max/1024/0*gulj9QE6-wL28bFs" /></figure><p><a href="https://tommanzur.github.io/DjangoTurorialAdvanced/">→ Django Tutorial in HTML Version</a></p><h3>What is Django?</h3><p>Django is a powerful and flexible Python-based web framework designed to streamline the development process of web applications. It focuses on making web development faster and more straightforward by offering reusable components, encouraging rapid development, and adhering to the “Don’t Repeat Yourself” (DRY) principle. Django comes with numerous built-in features, including an ORM (Object-Relational Mapping) for database interactions, a comprehensive authentication system, and a user-friendly admin interface for managing application data.</p><h4>Key Features of Django</h4><ul><li><strong>Rapid Development</strong>: Django includes many built-in functionalities that reduce the time and effort needed to build complex web applications.</li><li><strong>Scalability</strong>: Designed to accommodate the needs of both small and large-scale projects.</li><li><strong>Security</strong>: Django helps developers avoid many common security mistakes, including SQL injection, cross-site scripting, and cross-site request forgery.</li><li><strong>Versatility</strong>: Suitable for a variety of projects, from simple websites to complex web applications.</li></ul><h3>What Can You Build with Django?</h3><p>Django’s versatility allows it to be used for building a wide range of web applications. Here are some examples:</p><h4>Types of Applications</h4><ul><li><strong>Content Management Systems (CMS)</strong>: Manage and organize web content easily.</li><li><strong>E-commerce Websites</strong>: Handle product listings, shopping carts, and payment gateways.</li><li><strong>Social Media Platforms</strong>: Create user profiles, messaging systems, and activity feeds.</li><li><strong>Scientific Computing Platforms</strong>: Manage and analyze large datasets and complex computations.</li><li><strong>APIs</strong>: Using Django REST Framework to create robust and scalable APIs.</li><li><strong>Web Applications with Complex Data Requirements</strong>: Handle intricate business logic and large volumes of data efficiently.</li></ul><h3>Difference Between a Project and an App in Django</h3><p>Understanding the distinction between a project and an app is crucial for organizing your Django codebase effectively.</p><h4>Project</h4><p>A Django project is a collection of settings and configurations for your web application. It defines the overall structure and behavior of your site. A project typically includes:</p><ul><li><strong>Global Settings</strong>: Configurations that apply to the entire project, such as database settings and middleware.</li><li><strong>URL Routing</strong>: A central place to define the URL patterns for the project.</li><li><strong>Project-Specific Files</strong>: Such as settings.py, urls.py, and wsgi.py.</li></ul><h4>App</h4><p>An app is a self-contained module within a Django project that handles specific functionalities. Each app is responsible for a distinct part of your application. For example, an e-commerce project might have separate apps for managing products, orders, and users. An app includes:</p><ul><li><strong>Models</strong>: Define the data structure and interact with the database.</li><li><strong>Views</strong>: Handle the logic for displaying data and processing user input.</li><li><strong>Templates</strong>: Define the HTML structure for rendering data.</li><li><strong>Static Files</strong>: Contain assets like CSS, JavaScript, and images.</li></ul><h3>How to Start a Django Project</h3><p>To create a new Django project, you can use the django-admin command-line utility. This utility sets up the initial project structure, including essential configuration files.</p><h4>Command to Create a Project</h4><pre>django-admin startproject projectname</pre><h4>Generated Project Structure</h4><pre>projectname/<br>    manage.py<br>    projectname/<br>        __init__.py<br>        settings.py<br>        urls.py<br>        wsgi.py</pre><ul><li><strong>manage.py</strong>: A command-line utility to manage your project, including running the development server and performing database migrations.</li><li><strong>projectname/settings.py</strong>: The configuration file for your project, containing settings for databases, installed apps, middleware, and more.</li><li><strong>projectname/urls.py</strong>: The URL configuration file, mapping URL patterns to views.</li><li><strong>projectname/wsgi.py</strong>: An entry-point for WSGI-compatible web servers to serve your project.</li></ul><h3>How to Start a Django App</h3><p>Within a Django project, you can create multiple apps to modularize your functionality. Each app is a Python package with a specific directory structure.</p><h4>Command to Create an App</h4><pre>python manage.py startapp appname</pre><h4>Generated App Structure</h4><pre>appname/<br>    __init__.py<br>    admin.py<br>    apps.py<br>    migrations/<br>        __init__.py<br>    models.py<br>    tests.py<br>    views.py</pre><ul><li><strong>models.py</strong>: Defines the data models (database schema) for the app.</li><li><strong>views.py</strong>: Contains the logic for handling requests and returning responses.</li><li><strong>admin.py</strong>: Configures the admin interface for managing app data.</li><li><strong>migrations/</strong>: Directory to store database migration files.</li></ul><h3>How to Run the Development Server</h3><p>Django comes with a lightweight development server that allows you to test your application locally. This server is not suitable for production but is perfect for development and testing.</p><h4>Command to Start the Server</h4><pre>python manage.py runserver</pre><h4>Accessing the Development Server</h4><p>Once the server is running, you can access your application at http://127.0.0.1:8000/. This URL points to your local machine&#39;s IP address and port 8000.</p><h3>Understanding the settings.py File</h3><p>The settings.py file is the heart of your Django project configuration. It contains various settings that control the behavior of your application.</p><h4>Key Configurations in settings.py</h4><ul><li><strong>DEBUG</strong>: A boolean that should be set to True during development for detailed error messages and False in production.</li><li><strong>ALLOWED_HOSTS</strong>: A list of strings representing the host/domain names that the Django site can serve.</li><li><strong>DATABASES</strong>: Configuration for connecting to your database. Example:</li></ul><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,<br>        &#39;NAME&#39;: BASE_DIR / &quot;db.sqlite3&quot;,<br>    }<br>}</pre><ul><li><strong>INSTALLED_APPS</strong>: A list of applications that are enabled in your project. Each app is represented by a string of its full Python path.</li><li><strong>MIDDLEWARE</strong>: A list of middleware components that process requests and responses.</li><li><strong>TEMPLATES</strong>: Configuration for the template engine, including the directories to search for templates and context processors.</li></ul><h4>Example Configuration Snippet</h4><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: &#39;mydatabase&#39;,<br>        &#39;USER&#39;: &#39;myuser&#39;,<br>        &#39;PASSWORD&#39;: &#39;mypassword&#39;,<br>        &#39;HOST&#39;: &#39;localhost&#39;,<br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><h3>Models, Views, and Templates (MVT) in Django</h3><p>The MVT pattern in Django separates concerns into three main components: Models, Views, and Templates.</p><h4>Models</h4><p>Models define the structure of your database. Each model class represents a table in the database, and each attribute of the class represents a field in the table.</p><pre>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.IntegerField()</pre><h4>Views</h4><p>Views handle the logic of your application. They process user requests, interact with models to fetch data, and return responses.</p><pre>from django.shortcuts import render<br>from .models import Author<br><br>def author_list(request):<br>    authors = Author.objects.all()<br>    return render(request, &#39;author_list.html&#39;, {&#39;authors&#39;: authors})</pre><h4>Templates</h4><p>Templates define the presentation layer of your application. They are HTML files that display data provided by the views.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Author List&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Author List&lt;/h1&gt;<br>    &lt;ul&gt;<br>        {% for author in authors %}<br>            &lt;li&gt;{{ author.name }} ({{ author.age }} years old)&lt;/li&gt;<br>        {% endfor %}<br>    &lt;/ul&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>URL Patterns and Configuration</h3><p>URL patterns define the routes for your application, mapping URLs to views. This is configured using the urlpatterns list.</p><h4>Example Configuration</h4><pre>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>    path(&#39;&#39;, views.home, name=&#39;home&#39;),<br>    path(&#39;authors/&#39;, views.author_list, name=&#39;author_list&#39;),<br>]</pre><h4>Including App URLs in Project URL Configuration</h4><pre>from django.contrib import admin<br>from django.urls import include, path<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, include(&#39;appname.urls&#39;)),<br>]</pre><h3>Django Admin Panel</h3><p>The Django admin interface is a powerful tool that allows you to manage your application data easily. It provides a web-based interface to create, update, delete, and view the data models.</p><h4>Enabling the Admin Interface</h4><ol><li><strong>Add your app to </strong><strong>INSTALLED_APPS in </strong><strong>settings.py</strong>:</li></ol><pre>INSTALLED_APPS = [     ...     &#39;appname&#39;, ]</pre><p><strong>2. Register models in </strong><strong>admin.py</strong>:</p><pre>from django.contrib import admin<br>from .models import Author<br><br>admin.site.register(Author)</pre><p><strong>3. Create a superuser to access the admin interface</strong>:</p><pre>python manage.py createsuperuser</pre><p><strong>4. Run the development server and visit </strong><strong>http://127.0.0.1:8000/admin to log in</strong>.</p><h3>makemigrations and migrate in Django</h3><h4>makemigrations</h4><p>This command generates migration files based on the changes you make to your models. Migrations are a way of propagating changes you make to your models into the database schema.</p><pre>python manage.py makemigrations</pre><h4>migrate</h4><p>This command applies the migrations to your database, updating the schema to match your models.</p><pre>python manage.py migrate</pre><h3>Class-Based vs. Function-Based Views</h3><h4>Function-Based Views (FBV)</h4><p>Function-based views are simple and easy to use, especially for straightforward logic.</p><pre>from django.http import HttpResponse<br><br>def home(request):<br>    return HttpResponse(&quot;Welcome to the home page!&quot;)</pre><h4>Class-Based Views (CBV)</h4><p>Class-based views provide a more organized and reusable structure, making them ideal for more complex applications.</p><pre>from django.views import View<br>from django.http import HttpResponse<br><br>class HomeView(View):<br>    def get(self, request):<br>        return HttpResponse(&quot;Welcome to the home page!&quot;)</pre><h4>Preference</h4><p>Class-based views are preferred for their scalability and organization, especially in larger applications where reusability and modularity are crucial.</p><h3>Preferred Databases with Django</h3><p>Django supports multiple databases, each with its advantages and use cases.</p><h4>Commonly Used Databases</h4><ul><li><strong>SQLite</strong>: Suitable for development and testing due to its simplicity and zero configuration.</li><li><strong>PostgreSQL</strong>: Preferred for production environments because of its robustness, advanced features, and reliability.</li><li><strong>MySQL</strong>: Another popular choice for production, known for its speed and wide usage.</li></ul><h3>Configuring Database Connection in Django</h3><p>In settings.py, you can configure the database connection settings for your Django project.</p><h4>Example Configuration for PostgreSQL</h4><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: &#39;mydatabase&#39;,<br>        &#39;USER&#39;: &#39;myuser&#39;,<br>        &#39;PASSWORD&#39;: &#39;mypassword&#39;,<br>        &#39;HOST&#39;: &#39;localhost&#39;,<br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><h3>Dynamic URL Access in Django</h3><p>Django provides utilities to dynamically generate URLs, making your application more maintainable and robust.</p><h4>Using reverse in Views</h4><pre>from django.urls import reverse<br>from django.shortcuts import redirect<br><br>def my_view(request):<br>    url = reverse(&#39;my_view_name&#39;)<br>    return redirect(url)</pre><h4>Using {% url %} in Templates</h4><pre>&lt;a href=&quot;{% url &#39;my_view_name&#39; %}&quot;&gt;Go to my view&lt;/a&gt;</pre><h3>Storing Templates in Django</h3><p>Templates are usually stored in the templates directory within each app or in a global templates directory.</p><h4>Example Structure</h4><pre>appname/<br>    templates/<br>        appname/<br>            my_template.html</pre><h4>Configuring settings.py to Include Template Directories</h4><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [BASE_DIR / &#39;templates&#39;],<br>        &#39;APP_DIRS&#39;: True,<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                &#39;django.template.context_processors.debug&#39;,<br>                &#39;django.template.context_processors.request&#39;,<br>                &#39;django.contrib.auth.context_processors.auth&#39;,<br>                &#39;django.contrib.messages.context_processors.messages&#39;,<br>            ],<br>        },<br>    },<br>]</pre><h3>Understanding Double Curly Braces {{ }} in Templates</h3><p>In Django templates, double curly braces {{ }} are used to render variables passed from views.</p><h4>Example</h4><pre>&lt;p&gt;Hello, {{ user.username }}!&lt;/p&gt;</pre><p>This will display the username of the logged-in user.</p><h3>Using {% %} in Django Templates</h3><p>The {% %} syntax is used for template tags, which provide logic and control structures within templates.</p><h4>Example of a Loop</h4><pre>&lt;ul&gt;<br>{% for author in authors %}<br>    &lt;li&gt;{{ author.name }}&lt;/li&gt;<br>{% endfor %}<br>&lt;/ul&gt;</pre><p>This loop will iterate over the authors queryset and render each author&#39;s name in an unordered list.</p><h3>Including and Extending Templates</h3><h4>Including Templates</h4><p>Including templates allows you to reuse common sections like headers or footers across multiple templates.</p><pre>{% include &#39;header.html&#39; %}</pre><h4>Extending Templates</h4><p>Template inheritance allows you to create a base template and extend it in other templates, promoting DRY principles.</p><pre>{% extends &#39;base.html&#39; %}<br>{% block content %}<br>    &lt;h1&gt;Welcome&lt;/h1&gt;<br>{% endblock %}</pre><p>This extends base.html and defines content for the content block.</p><h3>Static Files in Django</h3><h4>What are Static Files?</h4><p>Static files are files like CSS, JavaScript, and images that are not dynamically generated by the server but are necessary for your application.</p><h4>Including Static Files</h4><p>To include static files in your Django project:</p><ol><li><strong>Create a </strong><strong>static directory in your app folder</strong>.</li><li><strong>Configure </strong><strong>settings.py</strong>:</li></ol><pre>STATIC_URL = &#39;/static/&#39; STATICFILES_DIRS = [     BASE_DIR / &quot;static&quot;, ]</pre><p><strong>3. Load static files in templates</strong>:</p><pre>{% load static %}<br>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{% static &#39;css/style.css&#39; %}&quot;&gt;<br>&lt;script src=&quot;{% static &#39;js/script.js&#39; %}&quot;&gt;&lt;/script&gt;</pre><h4>Configuring Static Files in Development</h4><p>During development, Django can serve static files for you. Ensure django.contrib.staticfiles is included in INSTALLED_APPS, then use python manage.py runserver to serve static files automatically.</p><h3>What is Media Root?</h3><p>MEDIA_ROOT is a setting in Django that defines the directory where user-uploaded files are stored.</p><h4>Configuring Media Root</h4><ol><li><strong>Add the media root and URL settings to </strong><strong>settings.py</strong>:</li></ol><pre>MEDIA_URL = &#39;/media/&#39; MEDIA_ROOT = BASE_DIR / &#39;media&#39;</pre><p><strong>2. Serve media files during development</strong>:</p><pre>from django.conf import settings<br>from django.conf.urls.static import static <br><br>if settings.DEBUG:<br>  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><p>This configuration ensures that media files are accessible during development.</p><h3>What is collectstatic in Django?</h3><p>collectstatic is a Django management command that collects all static files from your apps and places them in a single directory specified by the STATIC_ROOT setting.</p><h4>Using collectstatic</h4><ol><li><strong>Configure </strong><strong>settings.py</strong>:</li></ol><pre>STATIC_ROOT = BASE_DIR / &#39;staticfiles&#39;</pre><p><strong>2. Run the command</strong>:</p><pre>python manage.py collectstatic</pre><ul><li>python manage.py collectstatic</li></ul><h4>Serving Static Files in Production</h4><p>In production, you’ll need a web server like Nginx to serve static files. Configure your web server to serve files from the STATIC_ROOT directory.</p><h3>Foreign Keys in Django</h3><p>A <strong>Foreign Key</strong> is a field that creates a many-to-one relationship between models. It is used to link one model to another.</p><h4>Defining a Foreign Key</h4><pre>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=200)<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE)</pre><p>In this example, each Book is linked to an Author.</p><h4>Querying with Foreign Keys</h4><pre>books_by_author = Book.objects.filter(author__name=&#39;Author Name&#39;)</pre><p>This query retrieves all books written by a specific author.</p><h3>One-to-One Field in Django</h3><p>A <strong>One-to-One Field</strong> creates a one-to-one relationship between models. This is similar to a foreign key with a unique constraint.</p><h4>Defining a One-to-One Field</h4><pre>class Profile(models.Model):<br>    user = models.OneToOneField(User, on_delete=models.CASCADE)<br>    bio = models.TextField()</pre><p>Each Profile is associated with a single User.</p><h3>Many-to-Many Field in Django</h3><p>A <strong>Many-to-Many Field</strong> creates a many-to-many relationship between models, allowing each instance of one model to be associated with multiple instances of another model.</p><h4>Defining a Many-to-Many Field</h4><pre>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br><br>class Course(models.Model):<br>    title = models.CharField(max_length=200)<br>    students = models.ManyToManyField(Student)</pre><p>Each Course can have multiple Students, and each Student can enroll in multiple Courses.</p><h3>Character Field Attributes in Django</h3><h4>Common Attributes for Character Fields</h4><ul><li><strong>max_length</strong>: Defines the maximum length of the field.</li><li><strong>default</strong>: Sets a default value for the field.</li><li><strong>null</strong>: Allows NULL values in the database.</li><li><strong>blank</strong>: Allows the field to be blank in forms.</li></ul><h4>Example</h4><pre>class Author(models.Model):<br>    name = models.CharField(max_length=100, default=&#39;Anonymous&#39;)</pre><p>This example creates a name field with a maximum length of 100 characters and a default value of &#39;Anonymous&#39;.</p><h3>Basic Database Queries in Django</h3><h4>Creating Objects</h4><pre>author = Author.objects.create(name=&#39;John Doe&#39;)</pre><p>This command creates a new Author object and saves it to the database.</p><h4>Retrieving All Objects</h4><pre>authors = Author.objects.all()</pre><p>This query retrieves all Author objects from the database.</p><h4>Retrieving a Single Object</h4><pre>author = Author.objects.get(id=1)</pre><p>This query retrieves the Author object with the specified ID.</p><h4>Filtering Objects</h4><pre>young_authors = Author.objects.filter(age__lt=30)</pre><p>This query retrieves all authors who are younger than 30 years old.</p><h3>Querying a Single Element from a Database Table</h3><h4>Example</h4><pre>author = Author.objects.get(id=1)</pre><h4>Handling DoesNotExist Exception</h4><pre>from django.core.exceptions import ObjectDoesNotExist<br><br>try:<br>    author = Author.objects.get(id=1)<br>except ObjectDoesNotExist:<br>    print(&quot;Author not found&quot;)</pre><p>This ensures your application handles cases where the queried object does not exist.</p><h3>Filtering Items by Multiple Attributes</h3><h4>Example</h4><pre>authors = Author.objects.filter(age__lt=30, name__icontains=&#39;john&#39;)</pre><p>This query retrieves authors who are younger than 30 years old and whose name contains ‘john’.</p><h3>Model Sets and Their Usage</h3><p>A <strong>QuerySet</strong> is a collection of database queries. It allows you to read data from the database, filter it, and order it.</p><h4>Example</h4><pre>authors = Author.objects.filter(age__lt=30).order_by(&#39;name&#39;)</pre><p>This QuerySet retrieves authors younger than 30 and orders them by name.</p><h3>Querying Upwards in a Model Relationship</h3><h4>Example</h4><pre>books = Book.objects.filter(author__name=&#39;John Doe&#39;)</pre><p>This query retrieves all books written by the author named ‘John Doe’.</p><h3>CSRF Tokens and Their Usage</h3><p>CSRF (Cross-Site Request Forgery) tokens are used to protect forms from CSRF attacks, ensuring that the form submission is coming from the authenticated user.</p><h4>Using CSRF Tokens</h4><pre>&lt;form method=&quot;post&quot;&gt;<br>    {% csrf_token %}<br>    &lt;!-- form fields --&gt;<br>&lt;/form&gt;</pre><p>This adds a hidden field with a CSRF token to the form.</p><h3>Model Forms in Django</h3><p>Model forms allow you to create forms directly from your models, ensuring that the form fields match the model fields.</p><h4>Creating a Model Form</h4><pre>from django import forms<br>from .models import Author<br><br>class AuthorForm(forms.ModelForm):<br>    class Meta:<br>        model = Author<br>        fields = [&#39;name&#39;, &#39;age&#39;]</pre><p>This form can be used to create or update Author instances.</p><h3>Django REST Framework (DRF) and Its Importance</h3><p>Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. It simplifies the process of building RESTful APIs, offering a wide range of features out of the box.</p><h4>Why Use DRF?</h4><ul><li><strong>Flexibility</strong>: Provides a customizable and modular approach to building APIs.</li><li><strong>Serialization</strong>: Converts complex data types, such as querysets and model instances, into native Python data types.</li><li><strong>Authentication</strong>: Supports various authentication methods, including token-based authentication and OAuth.</li><li><strong>Pagination</strong>: Easily add pagination to API responses.</li><li><strong>Browsable API</strong>: Automatically generates a web-based interface for your API.</li></ul><h3>Signals in Django</h3><p>Signals allow you to execute some code when certain events occur. They provide a way to decouple different parts of your application.</p><h4>Example: Post-Save Signal</h4><pre>from django.db.models.signals import post_save<br>from django.dispatch import receiver<br>from .models import Author<br><br>@receiver(post_save, sender=Author)<br>def author_saved(sender, instance, **kwargs):<br>    print(f&#39;Author {instance.name} saved.&#39;)</pre><p>This signal is triggered every time an Author instance is saved, printing a message to the console.</p><h3>Preventing Unauthorized Users from Viewing Certain Pages</h3><h4>Using the login_required Decorator</h4><pre>from django.contrib.auth.decorators import login_required<br><br>@login_required<br>def my_view(request):<br>    return HttpResponse(&quot;Hello, authenticated user!&quot;)</pre><p>This decorator restricts access to the view, ensuring that only authenticated users can access it.</p><h3>Serializers in Django REST Framework</h3><p>Serializers convert complex data types, such as querysets and model instances, into native Python data types that can be rendered into JSON, XML, or other content types.</p><h4>Example</h4><pre>from rest_framework import serializers<br>from .models import Author<br><br>class AuthorSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Author<br>        fields = [&#39;id&#39;, &#39;name&#39;, &#39;age&#39;]</pre><p>This serializer converts Author instances to a JSON representation and vice versa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a8398c94a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/django-essentials-step-by-step-learning-42a8398c94a8">Django Essentials: Step-by-Step Learning</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices in Scikit-learn]]></title>
            <link>https://medium.com/@tommanzur/best-practices-in-scikit-learn-6b606b384ee1?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b606b384ee1</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[good-practices]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Tue, 14 May 2024 21:02:07 GMT</pubDate>
            <atom:updated>2024-05-14T21:02:07.729Z</atom:updated>
            <content:encoded><![CDATA[<p>Scikit-learn is a powerful and widely-used Python library for machine learning, providing simple and efficient tools for data analysis and modeling. To maximize the effectiveness of your machine learning projects, it’s essential to follow best practices in Scikit-learn. This guide covers various aspects from data preprocessing to model evaluation and deployment, ensuring you get the most out of this versatile library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YSCn9AZ5pMQI3LcYJ3AYg.png" /></figure><h4>Efficient Data Handling</h4><p><strong>🔄 Use Pandas for Data Preprocessing:</strong></p><p>Before feeding data into Scikit-learn models, use Pandas for data manipulation. Pandas’ DataFrame is ideal for handling and cleaning your dataset.</p><pre>import pandas as pd<br><br># Load your data<br>df = pd.read_csv(&#39;data.csv&#39;)<br><br># Preprocess your data<br>df[&#39;column&#39;] = df[&#39;column&#39;].fillna(df[&#39;column&#39;].mean())  # Handle missing values</pre><p><strong>🔄 Utilize Feature Engineering:</strong></p><p>Feature engineering is crucial for improving model performance. Create new features or transform existing ones to better capture underlying patterns.</p><pre>df[&#39;new_feature&#39;] = df[&#39;feature1&#39;] * df[&#39;feature2&#39;]  # Create interaction terms<br>df[&#39;log_feature&#39;] = np.log(df[&#39;feature&#39;] + 1)  # Apply logarithmic transformation</pre><p><strong>🔄 Normalize or Standardize Features:</strong></p><p>Scaling your features is vital, especially for algorithms sensitive to feature scales, such as SVM or k-NN.</p><pre>from sklearn.preprocessing import StandardScaler<br><br>scaler = StandardScaler()<br>scaled_features = scaler.fit_transform(df[[&#39;feature1&#39;, &#39;feature2&#39;]])</pre><h4>Model Selection and Training</h4><p><strong>🔄 Choose the Right Model:</strong></p><p>Different problems require different algorithms. Understand the strengths and weaknesses of various models to select the appropriate one for your task.</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier<br><br># Logistic Regression for binary classification<br>model = LogisticRegression()<br><br># Random Forest for more complex patterns<br>model = RandomForestClassifier()</pre><p><strong>🔄 Use Pipelines to Streamline Workflow:</strong></p><p>Scikit-learn’s Pipeline class helps streamline preprocessing and modeling steps, making your code cleaner and less error-prone.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.ensemble import RandomForestClassifier<br><br>pipeline = Pipeline([<br>    (&#39;scaler&#39;, StandardScaler()),<br>    (&#39;classifier&#39;, RandomForestClassifier())<br>])<br><br>pipeline.fit(X_train, y_train)</pre><p><strong>🔄 Hyperparameter Tuning:</strong></p><p>Optimize your model’s performance by tuning hyperparameters using techniques like grid search or randomized search.</p><pre>from sklearn.model_selection import GridSearchCV<br><br>param_grid = {<br>    &#39;classifier__n_estimators&#39;: [50, 100, 200],<br>    &#39;classifier__max_depth&#39;: [None, 10, 20, 30]<br>}<br><br>grid_search = GridSearchCV(pipeline, param_grid, cv=5)<br>grid_search.fit(X_train, y_train)</pre><h4>Model Evaluation</h4><p><strong>🔄 Use Cross-Validation:</strong></p><p>Ensure your model’s performance is robust by using cross-validation, which provides a better estimate of model performance than a single train-test split.</p><pre>from sklearn.model_selection import cross_val_score<br><br>scores = cross_val_score(model, X, y, cv=5)<br>print(f&#39;Cross-validation scores: {scores}&#39;)</pre><p><strong>🔄 Evaluate with Appropriate Metrics:</strong></p><p>Choose evaluation metrics that align with your problem. For classification tasks, consider accuracy, precision, recall, F1 score, and ROC-AUC.</p><pre>from sklearn.metrics import classification_report, roc_auc_score<br><br>y_pred = model.predict(X_test)<br>print(classification_report(y_test, y_pred))<br><br>y_proba = model.predict_proba(X_test)[:, 1]<br>roc_auc = roc_auc_score(y_test, y_proba)<br>print(f&#39;ROC-AUC Score: {roc_auc}&#39;)</pre><p><strong>🔄 Avoid Data Leakage:</strong></p><p>Ensure that no information from the test set is used to train the model. Split your data into training and testing sets before any preprocessing.</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><h4>Model Interpretation</h4><p><strong>🔄 Understand Feature Importance:</strong></p><p>Many models, like tree-based algorithms, allow you to inspect feature importance, helping you understand which features drive the predictions.</p><pre>importances = model.feature_importances_<br>feature_names = df.columns<br>feature_importance_df = pd.DataFrame({&#39;feature&#39;: feature_names, &#39;importance&#39;: importances})<br>print(feature_importance_df.sort_values(by=&#39;importance&#39;, ascending=False))</pre><p><strong>🔄 Use SHAP or LIME for Model Interpretation:</strong></p><p>For complex models like neural networks or ensembles, use tools like SHAP or LIME to interpret individual predictions.</p><pre>import shap<br><br>explainer = shap.TreeExplainer(model)<br>shap_values = explainer.shap_values(X_test)<br>shap.summary_plot(shap_values, X_test)</pre><h4>Model Deployment</h4><p><strong>🔄 Save and Load Models:</strong></p><p>Use joblib to save and load your trained models, making it easier to deploy them into production.</p><pre>import joblib<br><br># Save the model<br>joblib.dump(model, &#39;model.pkl&#39;)<br><br># Load the model<br>model = joblib.load(&#39;model.pkl&#39;)</pre><p><strong>🔄 Create REST APIs for Model Serving:</strong></p><p>Use frameworks like Flask to create REST APIs, allowing you to serve your model predictions in a web application.</p><pre>from flask import Flask, request, jsonify<br>import joblib<br><br>app = Flask(__name__)<br>model = joblib.load(&#39;model.pkl&#39;)<br><br>@app.route(&#39;/predict&#39;, methods=[&#39;POST&#39;])<br>def predict():<br>    data = request.json<br>    prediction = model.predict([data[&#39;features&#39;]])<br>    return jsonify({&#39;prediction&#39;: prediction.tolist()})<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p><strong>🔄 Monitor Model Performance:</strong></p><p>Continuously monitor your model’s performance in production to ensure it performs well on new data. Use tools like Prometheus and Grafana for monitoring and alerting.</p><h3>Conclusion</h3><p>Following these best practices in Scikit-learn can help you build robust, efficient, and interpretable machine learning models. From data preprocessing to model deployment, each step is crucial in ensuring your model’s success and reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b606b384ee1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good Practices in Apache Beam]]></title>
            <link>https://medium.com/@tommanzur/good-practices-in-apache-beam-86e123193a27?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/86e123193a27</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[good-practices]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Tue, 14 May 2024 17:45:12 GMT</pubDate>
            <atom:updated>2024-05-14T17:45:12.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Beam is a powerful unified programming model for defining and executing data processing pipelines. To make the most out of Apache Beam, it’s essential to follow best practices to ensure efficiency, readability, and maintainability. Here are some key tips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43XxfseWj0pzTe1XcfMrrg.png" /></figure><h4>Why Efficient Pipeline Handling Matters</h4><p>Using Apache Beam effectively can significantly impact your data processing performance and scalability. Here are some best practices to keep in mind:</p><p><strong>🔄 Understand Beam’s Model:</strong></p><p>Before diving into coding, familiarize yourself with Apache Beam’s core concepts, including PCollections, PTransforms, and ParDo. Understanding the execution model helps in writing efficient pipelines.</p><p><strong>🔄 Use </strong><strong>ParDo for Complex Transformations:</strong></p><p>When you need to perform complex transformations, use ParDo with DoFn. It provides the flexibility needed for custom operations.</p><pre>class SplitWords(beam.DoFn):<br>    def process(self, element):<br>        return element.split()<br><br># Usage<br>p | &#39;Split Words&#39; &gt;&gt; beam.ParDo(SplitWords())</pre><p><strong>🔄 Avoid Global State:</strong></p><p>Beam’s distributed nature means global state can lead to issues. Instead, use side inputs or stateful processing if you need to share data across multiple elements.</p><p><strong>🔄 Use Windowing and Triggers:</strong></p><p>For streaming data, leverage windowing and triggers to control how data is grouped and when results are emitted.</p><pre>p | &#39;Window into Fixed Intervals&#39; &gt;&gt; beam.WindowInto(<br>    beam.window.FixedWindows(60), <br>    trigger=beam.trigger.AfterWatermark(),<br>    accumulation_mode=beam.trigger.AccumulationMode.DISCARDING<br>)</pre><p><strong>🔄 Combine Data Efficiently:</strong></p><p>Use CombineFn for custom aggregations to ensure efficient processing.</p><pre>class AverageFn(beam.CombineFn):<br>    def create_accumulator(self):<br>        return (0.0, 0)<br><br>    def add_input(self, accumulator, input):<br>        (sum, count) = accumulator<br>        return sum + input, count + 1<br><br>    def merge_accumulators(self, accumulators):<br>        sums, counts = zip(*accumulators)<br>        return sum(sums), sum(counts)<br><br>    def extract_output(self, accumulator):<br>        (sum, count) = accumulator<br>        return sum / count if count else float(&#39;NaN&#39;)<br><br># Usage<br>p | &#39;Compute Average&#39; &gt;&gt; beam.CombineGlobally(AverageFn())</pre><p><strong>🔄 Handle Exceptions Gracefully:</strong></p><p>Implement proper error handling within your transforms to ensure robustness.</p><pre>class SafeDivide(beam.DoFn):<br>    def process(self, element):<br>        try:<br>            result = element[&#39;numerator&#39;] / element[&#39;denominator&#39;]<br>        except ZeroDivisionError:<br>            result = None<br>        yield result<br><br># Usage<br>p | &#39;Safe Divide&#39; &gt;&gt; beam.ParDo(SafeDivide())</pre><h4>Additional Best Practices</h4><p><strong>🔄 Optimize Resource Usage:</strong></p><p>Tune your pipeline’s resource settings to balance between performance and cost. This includes adjusting worker types, autoscaling settings, and parallelism.</p><p><strong>🔄 Use Metrics for Monitoring:</strong></p><p>Leverage Beam’s built-in metrics to monitor your pipeline’s performance and catch issues early.</p><pre>class ComputeMetrics(beam.DoFn):<br>    def __init__(self):<br>        self.counter = beam.metrics.Metrics.counter(&#39;namespace&#39;, &#39;elements_processed&#39;)<br><br>    def process(self, element):<br>        self.counter.inc()<br>        yield element<br><br># Usage<br>p | &#39;Compute Metrics&#39; &gt;&gt; beam.ParDo(ComputeMetrics())</pre><p><strong>🔄 Minimize Data Shuffling:</strong></p><p>Design your pipeline to minimize data shuffling, which can be expensive. Use partitioning strategies and combiners effectively.</p><p><strong>🔄 Test Your Pipelines:</strong></p><p>Write unit tests for your transforms and end-to-end tests for your pipelines to ensure they work correctly.</p><pre>def test_my_transform():<br>    input = TestPipeline()<br>    result = (input <br>              | beam.Create([1, 2, 3, 4])<br>              | &#39;Multiply by 2&#39; &gt;&gt; beam.Map(lambda x: x * 2))<br><br>    assert_that(result, equal_to([2, 4, 6, 8]))<br><br>if __name__ == &#39;__main__&#39;:<br>    test_my_transform()</pre><p><strong>🔄 Use Templated Pipelines:</strong></p><p>For reusable and parameterized pipelines, leverage templates to simplify deployment and management.</p><pre>pipeline_options = PipelineOptions(flags=[&#39;--input&#39;, &#39;--output&#39;]) <br>input = pipeline_options.input <br>output = pipeline_options.output <br><br>with beam.Pipeline(options=pipeline_options) as p:<br>    (p <br>     | &#39;Read Input&#39; &gt;&gt; beam.io.ReadFromText(input)<br>     | &#39;Process Data&#39; &gt;&gt; beam.ParDo(ProcessFn())<br>     | &#39;Write Output&#39; &gt;&gt; beam.io.WriteToText(output))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86e123193a27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas: Why Efficient DataFrame Handling Matters]]></title>
            <link>https://medium.com/@tommanzur/why-efficient-dataframe-handling-matters-db917ac31883?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/db917ac31883</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Tue, 14 May 2024 16:31:45 GMT</pubDate>
            <atom:updated>2024-12-04T14:25:52.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*b_lfh5MTItmbwS2RfpP2Rw.png" /></figure><p>Using Pandas effectively is crucial for data manipulation and analysis. Here are some best practices to keep in mind:</p><p><strong>📏 Avoid </strong><strong>apply When Possible:</strong></p><p>Using vectorized operations is generally faster than apply. Functions like .sum(), .mean(), and .max() are optimized in Pandas and should be preferred.</p><pre># Instead of this: <br>df[&#39;new_column&#39;] = df.apply(lambda row: row[&#39;col1&#39;] + row[&#39;col2&#39;], axis=1) <br><br># Do this: <br>df[&#39;new_column&#39;] = df[&#39;col1&#39;] + df[&#39;col2&#39;]</pre><p><strong>🧹 Use In-Place Operations:</strong></p><p>When modifying DataFrames, using in-place operations can save memory.</p><pre># Instead of this: <br>df = df.drop(columns=[&#39;unnecessary_column&#39;]) <br><br># Do this:<br>df.drop(columns=[&#39;unnecessary_column&#39;], inplace=True)</pre><p><strong>🔄 Chain Methods:</strong></p><p>Chaining methods can make your code more readable and concise. Use parentheses to improve readability.</p><pre># Instead of this: <br>df = df.dropna() <br>df = df.rename(columns={&#39;old_name&#39;: &#39;new_name&#39;}) <br>df = df.sort_values(by=&#39;new_name&#39;) <br><br># Do this: <br>df = (df.dropna()<br>        .rename(columns={&#39;old_name&#39;: &#39;new_name&#39;})<br>        .sort_values(by=&#39;new_name&#39;))</pre><p><strong>🔍 Use </strong><strong>.loc and </strong><strong>.iloc for Indexing:</strong></p><p>These methods are faster and more explicit than regular indexing.</p><pre># Instead of this: <br>subset = df[df[&#39;column&#39;] &gt; value] <br><br># Do this: <br>subset = df.loc[df[&#39;column&#39;] &gt; value]</pre><p><strong>📊 Efficient Data Types:</strong></p><p>Use the correct data types to save memory and improve performance.</p><pre># Convert object columns to category if they have a few unique values<br>df[&#39;category_column&#39;] = df[&#39;category_column&#39;].astype(&#39;category&#39;)</pre><p><strong>🧠 Understand Your Data:</strong></p><p>Before performing operations, understand the shape, types, and structure of your DataFrame. Use .info() and .describe().</p><pre>print(df.info())<br>print(df.describe())</pre><p><strong>📝 Document Your Code:</strong></p><p>Comment your code and use meaningful variable names to make your code understandable to others and your future self.</p><pre># Calculate the mean of the column &#39;age&#39; <br>average_age = df[&#39;age&#39;].mean()</pre><h4>Additional Best Practices</h4><p><strong>🔄 Avoid Chained Indexing:</strong></p><p>Chained indexing can lead to unpredictable results and is generally slower. Use single-step indexing instead.</p><pre># Instead of this: <br>value = df[df[&#39;column&#39;] &gt; value][&#39;another_column&#39;] <br><br># Do this: <br>value = df.loc[df[&#39;column&#39;] &gt; value, &#39;another_column&#39;]</pre><p><strong>🔄 Use </strong><strong>merge for Joins:</strong></p><p>When combining DataFrames, use the merge method instead of concatenation or manual joins to ensure efficient and accurate merging.</p><pre># Instead of this: <br>combined = df1.join(df2, on=&#39;key&#39;) <br><br># Do this: <br>combined = df1.merge(df2, on=&#39;key&#39;)</pre><p><strong>🔄 Use </strong><strong>query for Complex Filtering:</strong></p><p>The query method can make complex filtering more readable and efficient.</p><pre># Instead of this: <br>filtered = df[(df[&#39;column1&#39;] &gt; value1) &amp; (df[&#39;column2&#39;] &lt; value2)] <br><br># Do this: <br>filtered = df.query(&#39;column1 &gt; @value1 and column2 &lt; @value2&#39;)</pre><p><strong>🔄 Leverage GroupBy Aggregations:</strong></p><p>Use groupby for aggregating data efficiently.</p><pre># Example: <br>grouped = df.groupby(&#39;column&#39;).agg({&#39;value_column&#39;: &#39;sum&#39;})</pre><p><strong>🔄 Profile Your Data:</strong></p><p>Use libraries like pandas_profiling to quickly get insights into your DataFrame.</p><pre>from pandas_profiling import ProfileReport<br><br>profile = ProfileReport(df, title=&quot;Pandas Profiling Report&quot;)<br>profile.to_notebook_iframe()</pre><p><strong>🔄 Optimize Memory Usage:</strong></p><p>Convert data types to more memory-efficient formats.</p><pre># Example: <br>df[&#39;int_column&#39;] = df[&#39;int_column&#39;].astype(&#39;int32&#39;) <br>df[&#39;float_column&#39;] = df[&#39;float_column&#39;].astype(&#39;float32&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db917ac31883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating AI Language Models with Graph Databases for Retrieval Augmented Generation]]></title>
            <link>https://medium.com/@tommanzur/integrating-ai-language-models-with-graph-databases-for-retrieval-augmented-generation-992ef92e6a0b?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/992ef92e6a0b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 22:11:51 GMT</pubDate>
            <atom:updated>2024-02-01T22:11:51.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating AI Language Models with Graph Databases for Enhanced Data Retrieval</h3><h3>Introduction</h3><h4>Background</h4><p>In recent years, two groundbreaking technologies have been making waves in the world of data management and analysis: Artificial Intelligence (AI) language models and graph databases. AI language models, such as OpenAI’s GPT series, have revolutionized the way we interact with and process natural language data. On the other hand, graph databases, like Neo4j and Amazon Neptune, offer a novel approach to storing and querying data, focusing on the relationships between data points.</p><h4>Article Overview</h4><p>The article delves into the basics of graph databases, their uses, and contrasts them with other database types. It then explores the concept of Retrieval-Augmented Generation (RAG) systems, detailing how AI language models can complement graph databases. Furthermore, it discusses the benefits of this integration, particularly for complex data retrieval tasks, and concludes with thoughts on future applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwVzvO84-OgvfcToQ4kAYg.png" /></figure><h3>Understanding Graph Databases</h3><h4>Definition and Basics</h4><p>Graph databases represent a paradigm shift in database technology, fundamentally altering how data is stored, accessed, and analyzed. Unlike traditional databases that store data in rows, columns, or unstructured formats, graph databases use graph theory to store data in nodes (entities) and edges (relationships). This section delves into their intricate structure, contrasting their approach with conventional databases, and discusses their inherent strengths and weaknesses.</p><h4>Structure of Graph Databases</h4><p>Graph databases consist of two primary elements: nodes and edges. Nodes represent entities (such as people, places, or objects) while edges denote the relationships between these entities. Each node and edge can have associated properties, allowing for a rich, detailed representation of data. For example, in a social network graph, nodes could represent users, and edges could signify friendships, with properties like name, age, or date of connection adding depth to the data.</p><h4>Graph Theory Foundations</h4><p>At their core, graph databases are built on graph theory, a field of mathematics focused on studying graphs — structures made up of vertices (or nodes) connected by edges. This theoretical underpinning enables graph databases to efficiently navigate and manage complex networks of relationships, a task that traditional databases struggle with.</p><h4>Differences from Traditional Databases</h4><p>Traditional databases, like relational (SQL) databases, store data in tables, often requiring complex joins to retrieve related data. This can be computationally intensive and less intuitive when dealing with highly interconnected data. In contrast, graph databases are designed to naturally represent relationships, making them inherently more suitable for scenarios where relationships are just as crucial as the data itself.</p><h4>Use Cases</h4><p>Graph databases shine in scenarios where relationships and connections between data points are pivotal. Their unique structure and capabilities enable them to efficiently tackle complex, interconnected datasets.</p><ul><li><strong>Recommendation Systems</strong></li></ul><p>One of the most common applications of graph databases is in building recommendation systems. For instance, e-commerce platforms use them to suggest products based on a user’s browsing history and the purchasing habits of similar users. The ability of graph databases to quickly traverse relationships between users, products, and preferences makes them ideal for this application.</p><ul><li><strong>Social Network Analysis</strong></li></ul><p>Graph databases are extensively used in social network analysis, allowing platforms to map and analyze complex user relationships. They can efficiently query vast networks to find connections, suggest friends or followers, and even detect patterns or communities within the network.</p><ul><li><strong>Fraud Detection</strong></li></ul><p>In finance, graph databases are employed for fraud detection. They can analyze transaction networks to spot unusual patterns, such as circular transactions indicative of money laundering. The ability to trace the flow of transactions through multiple accounts in real-time is a key strength here.</p><h4>Comparison with Other Databases</h4><p>Graph databases are not a one-size-fits-all solution and have their specific niche where they excel. Understanding where they stand in comparison to other databases helps in choosing the right tool for a given application.</p><ul><li><strong>Relational Databases (SQL)</strong></li></ul><p>Relational databases organize data into tables, which can be linked via relationships. They are highly structured and efficient for handling well-defined, tabular data. However, as the complexity and interconnectedness of the data grow, the performance of relational databases can degrade due to the need for multiple table joins and complex queries.</p><ul><li><strong>Document Databases (NoSQL)</strong></li></ul><p>Document databases, a type of NoSQL database, store data in document-like structures (such as JSON). They are flexible and scale well for unstructured data. However, they lack the inherent capability to efficiently manage complex inter-document relationships, often requiring additional processing to infer these connections.</p><ul><li><strong>Graph Databases vs. SQL and NoSQL</strong></li></ul><p>Graph databases are inherently built for connectivity. They excel in scenarios where relationships are key, providing efficient path-finding and traversal capabilities. For complex, interconnected datasets, graph databases offer performance and query simplicity that SQL and NoSQL struggle to match. However, for simpler, less connected datasets, the overhead of a graph database might not be justified, making SQL or NoSQL a more suitable choice.</p><p>In summary, the choice of database technology heavily depends on the nature of the data and the specific requirements of the application. Graph databases stand out for their ability to handle complex networks and relationships, offering significant advantages in scenarios where these aspects are critical.</p><h3>Integration of AI Language Models with Graph Databases Concept of RAG Systems</h3><h4>Retrieval-Augmented Generation (RAG)</h4><p>Retrieval-Augmented Generation (RAG) systems represent an innovative approach in the realm of artificial intelligence, merging the capabilities of retrieval-based and generative AI models. These systems leverage the strengths of both models to enhance the accuracy and relevance of information retrieval and generation. In essence, RAG systems first utilize a retrieval component to fetch relevant data or documents from a vast database. This retrieved information then serves as a knowledge base for the generative component, which synthesizes and presents this information in a coherent, contextually appropriate manner.</p><p>The relevance of RAG systems in data analysis is substantial. By incorporating these systems, the range and depth of data analysis are significantly expanded. For instance, in response to complex queries, RAG systems can provide more nuanced and comprehensive answers by drawing upon a wider array of information sources. This ability to combine retrieval and generation offers a more dynamic and adaptable approach to data analysis, particularly in scenarios where the query involves abstract concepts or requires insights drawn from diverse data sets.</p><h4>AI and Graph Database Synergy</h4><p>The integration of AI language models with graph databases represents a synergistic convergence of technologies, each amplifying the other’s strengths. AI language models, known for their ability to understand and generate human-like text, can greatly enhance the querying capabilities of graph databases. These databases, structured to map relationships and connections between various data points, can be complex and challenging to query using traditional search methods. AI language models, with their advanced natural language processing abilities, can interpret complex queries and translate them into specific, graph-database-friendly requests.</p><p>Furthermore, this synergy allows for more intuitive interaction with graph databases. Users can pose queries in natural language, which the AI model interprets and converts into a format that the graph database can process. This interaction significantly lowers the barrier to entry for users who may not be familiar with the technical query language of graph databases.</p><p>Additionally, AI language models can assist in dynamically updating and maintaining graph databases. As these models process new information, they can identify potential new nodes and relationships, suggesting updates to the database. This ongoing process ensures that the graph database remains current and reflective of the latest data trends and patterns.</p><h4>Extracting Data from Unstructured Sources</h4><p>One of the most significant challenges in data management and analysis is extracting meaningful information from unstructured data sources, such as PDFs, markdown files, and other non-standardized formats. AI language models excel in this domain, offering the capability to process and interpret these unstructured data sources. Through advanced natural language processing techniques, these models can identify entities, relationships, and key information buried within unstructured data.</p><p>This ability transforms the way unstructured data is utilized. Instead of being a cumbersome and often underutilized data source, it becomes a valuable input for graph databases. AI models can extract entities and their relationships from unstructured texts, converting them into nodes and edges that can be directly inputted into a graph database. This process not only expands the breadth of data available in the graph database but also enhances the depth and interconnectedness of the existing data.</p><p>Furthermore, the extraction process facilitated by AI models includes categorizing and tagging the extracted information, which is crucial for maintaining the integrity and navigability of the graph database. As a result, the database becomes a more powerful tool for complex data analysis, capable of providing insights that were previously inaccessible due to the unstructured nature of the data.</p><p>In summary, the integration of AI language models with graph databases offers a groundbreaking approach to data retrieval and analysis. RAG systems bridge the gap between retrieval and generation, providing more nuanced responses to complex queries. The synergy between AI language models and graph databases enhances the accessibility and functionality of these databases, making them more user-friendly and powerful. Lastly, the capability of AI models to extract and categorize data from unstructured sources revolutionizes the way this data is utilized, enriching the graph database’s value as a tool for comprehensive data analysis.Benefits of Using Graph Databases in RAG Applications (Approx. 2000 words)</p><h3>Benefits of Using Graph Databases in RAG Applications</h3><h4>Advantages Over Vector Similarity Searches</h4><p>Vector similarity searches, a common feature in traditional data retrieval systems, have long been the go-to method for finding relevant information in large datasets. These searches typically involve representing documents as vectors in a multidimensional space, where the proximity between vectors is indicative of their similarity. However, this approach often falls short in handling complex queries, particularly when the relationships between data points are as crucial as the data points themselves.</p><p>Graph databases, with their inherent structure, offer a more nuanced approach. In a graph database, data is stored as nodes (representing entities) and edges (representing relationships), which allows for a more holistic view of the data. This structure is especially beneficial in scenarios where the connections between entities are as important as the entities themselves.</p><p>One significant limitation of vector similarity searches is their inability to efficiently handle queries that involve multiple, interconnected entities. For instance, in a recommendation system, a user might not only be interested in items similar to what they’ve liked in the past but also in items liked by similar users. A vector similarity search can struggle with such multi-faceted queries, as it primarily focuses on surface-level similarity.</p><p>Graph databases, by contrast, excel in this area. They can effortlessly traverse relationships between nodes, making it possible to uncover deeper, more meaningful connections. This ability extends beyond simple direct relationships to include complex networks of interconnections, enabling a more comprehensive and context-aware retrieval of information.</p><h4>Multi-hop Searches and Complex Queries</h4><p>The concept of multi-hop searches is another area where graph databases significantly outperform traditional vector-based systems. Multi-hop searches refer to queries that require multiple steps to reach a conclusion or find a piece of information. In a graph database, this is akin to traversing multiple nodes and edges. For instance, finding a connection between two seemingly unrelated pieces of information might involve hopping through a series of related nodes.</p><p>Graph databases are inherently designed for this type of query. They allow for the exploration of connections over several ‘hops’, making it possible to answer complex queries that would be challenging or impossible for traditional search systems. This capability is particularly valuable in fields like research and investigative journalism, where establishing links between various pieces of information is crucial.</p><p>In addition to multi-hop capabilities, graph databases excel in handling complex queries that involve aggregating information from multiple documents. Unlike vector similarity searches, which typically evaluate documents in isolation, graph databases can consider the interconnectedness of various data points. This feature is crucial for applications like knowledge graphs and semantic search engines, where understanding the relationships between different pieces of information is key.</p><p>For example, in a medical research context, a query might involve finding connections between different symptoms, drugs, and diseases. A graph database can easily navigate through these interconnected entities, providing insights that are not readily apparent through simple keyword searches or vector similarity checks.</p><p>Moreover, graph databases can also handle dynamically changing data effectively. In real-time applications, such as social media analysis or fraud detection, data relationships can change rapidly. Graph databases are adept at updating and managing these evolving connections, providing up-to-date and relevant results for complex queries.</p><p>In summary, graph databases offer distinct advantages over vector similarity searches, especially in scenarios involving complex, multi-faceted queries. Their ability to map and traverse intricate networks of data relationships makes them an ideal choice for applications requiring depth and context in data retrieval. This capability is increasingly crucial in a world where data is not just abundant but deeply interconnected. As such, the integration of graph databases in Retrieval-Augmented Generation systems represents a significant step forward in the field of data retrieval and analysis.</p><h3>Conclusion</h3><h4>Summary of Key Points</h4><p>This article has explored the groundbreaking integration of AI language models and graph databases, illuminating a path toward more advanced and efficient data retrieval systems. We have seen how graph databases, with their focus on relationships and connections, provide a more intuitive and effective means of handling complex, interconnected data sets. In contrast to traditional vector similarity searches, which often fall short in complex query scenarios, graph databases excel in traversing intricate relationships and executing multi-hop searches.</p><p>The integration of AI language models brings an additional layer of sophistication to this setup. These models’ ability to process and interpret natural language allows for more user-friendly interaction with graph databases. They can translate complex, natural language queries into specific graph database operations, making these powerful tools accessible to a wider range of users. Moreover, AI models’ capability to process unstructured data sources like PDFs and markdown files is a game-changer. It allows for the extraction and integration of a broader range of data into graph databases, enriching the data sets and enabling more comprehensive analysis.</p><p>The combination of these technologies in Retrieval-Augmented Generation (RAG) systems represents a significant advancement in data analysis and retrieval. RAG systems harness the strengths of both retrieval-based and generative AI models, providing nuanced and contextually appropriate responses to complex queries. This integration is not just a technical achievement but a step towards a more connected and intelligent data processing future.</p><h4>Future Perspectives</h4><p>Looking ahead, the potential applications and impacts of integrating AI language models with graph databases are vast and varied. In healthcare, this technology could revolutionize patient care and medical research. By aggregating and analyzing data from various sources, such as patient records, medical literature, and clinical trials, healthcare providers can gain deeper insights into patient conditions, treatment options, and outcomes.</p><p>In the financial sector, the implications are equally profound. Banks and financial institutions could use these systems for more sophisticated fraud detection, risk assessment, and customer service. By understanding customer behavior and preferences at a deeper level, financial services can be tailored more effectively to individual needs.</p><p>The academic research community also stands to benefit significantly from this integration. Researchers can handle larger and more complex data sets, uncovering connections and insights that were previously obscured. This capability could accelerate discoveries across disciplines, from the humanities to the natural sciences.</p><h4>Closing Thoughts</h4><p>The integration of AI language models with graph databases is more than a technical innovation; it represents a shift in how we approach and handle data. In a world increasingly driven by data, the ability to effectively manage, analyze, and extract insights from vast, interconnected data sets is crucial. This integration brings us closer to realizing the full potential of our data-driven era.</p><p>As we continue to advance in this field, it is essential to remain mindful of the ethical considerations and potential risks. Ensuring data privacy, security, and fairness in AI algorithms are critical challenges that must be addressed. However, with careful management and ethical considerations, the integration of AI language models and graph databases promises to be a cornerstone in the future of data analysis and retrieval, driving innovation and understanding in countless fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=992ef92e6a0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Implementing Custom Docker Containers in Google Cloud Dataflow]]></title>
            <link>https://medium.com/@tommanzur/guide-to-implementing-custom-docker-containers-in-google-cloud-dataflow-ced9e2aa7faf?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced9e2aa7faf</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 02:03:17 GMT</pubDate>
            <atom:updated>2024-01-31T02:03:17.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guide to Implementing Custom Docker Containers in Dataflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CScbWhNwBL7WxXGr2GU3jA.png" /></figure><h3>Introduction</h3><p>Efficient data processing is crucial in the modern era of big data. Google Cloud Dataflow, a fully managed service for stream and batch processing, can be optimized using custom Docker containers. This approach significantly accelerates worker startup times and minimizes dependency resolution overhead. In this extensive guide, we’ll walk through the detailed process of creating, building, and deploying custom Docker containers for Dataflow, ensuring enhanced performance and scalability of your data pipelines.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have the following:</p><ol><li>Docker Desktop installed on your machine.</li><li>Google Cloud SDK installed and configured.</li><li>Artifact Registry API enabled in your Google Cloud Console.</li></ol><h3>Step-by-Step Implementation</h3><h3>Step 1: Crafting the Dockerfile</h3><p>The foundation of a custom Docker container is the Dockerfile. This file defines the environment, including all necessary dependencies and configurations for your Dataflow job.</p><h4>1.1 Creating the Dockerfile</h4><p>The Dockerfile is designed to create a custom image that includes all necessary dependencies for the Dataflow jobs. Defines Python image and incorporates the Apache Beam SDK:</p><pre>FROM apache/beam_python3.11_sdk:2.53.0 AS beam_python<br>FROM python:3.11-slim<br>COPY requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY --from=beam_python /opt/apache/beam /opt/apache/beam<br>COPY . .<br>ENTRYPOINT [ &quot;/opt/apache/beam/boot&quot; ]</pre><h4>1.2 Understanding the Dockerfile</h4><ul><li>Base Image: We start with python:3.11-slim for a minimal Python environment.</li><li>Apache Beam Installation: Apache Beam SDK is installed with the necessary GCP components.</li><li>Copying SDK Files: Essential files from the official Apache Beam SDK Docker image are copied to ensure compatibility.</li><li>Setting the Entry Point: The Apache Beam SDK launcher is set as the entry point for the container.</li></ul><h3>Step 2: Building the Docker Image</h3><p>With your Dockerfile ready, proceed to build the Docker image. This step compiles and packages your environment into a container image.</p><h4>2.1 Building Command</h4><p>Open a terminal and navigate to the directory containing your Dockerfile. Run the following command to build your Docker image:</p><pre>docker build --platform linux/amd64 -t my_dataflow_image .</pre><h4>2.2 Verifying the Build</h4><p>Ensure that the Docker daemon is active. Upon successful completion, the image my_dataflow_image will be created.</p><h3>Step 3: Pushing the Image to GCP Artifact Registry</h3><p>The next step is to store and manage your Docker image in Google Cloud’s Artifact Registry.</p><h4>3.1 Creating a Repository in Artifact Registry</h4><p>Run the following command to create a new repository:</p><pre>gcloud artifacts repositories create my_dataflow_repository \<br>--repository-format=docker \<br>--location=us-central1 \<br>--description=&quot;Repository for Dataflow worker containers&quot;</pre><h4>3.2 Configuring Docker for GCP Authentication</h4><p>Authenticate Docker with GCP to push images to the Artifact Registry:</p><pre>gcloud auth configure-docker REGION-docker.pkg.dev</pre><h4>3.3 Tagging Your Docker Image</h4><p>Tag your built image for the registry:</p><pre>docker tag my_dataflow_image REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE</pre><h4>3.4 Pushing the Image</h4><p>Finally, upload your image to the Artifact Registry:</p><pre>docker push REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE</pre><h3>Step 4: Running Dataflow Pipelines with the Custom Container</h3><p>To utilize your custom container in Dataflow, you need to modify the pipeline execution command.</p><h4>4.1 Modifying the Pipeline Command</h4><p>Adjust your pipeline’s command as follows:</p><pre>python -m my_pipeline \ <br>--region REGION \ <br>--runner DataflowRunner \ <br>--project PROJECT_ID \ <br>--sdk_container_image REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE \ <br>--sdk_location=container</pre><h4>4.2 Understanding the Command Changes</h4><ul><li>sdk_container_image: Specifies your custom Docker container.</li><li>sdk_location: Set to container to indicate the use of a Docker image.</li></ul><h3>Conclusion</h3><p>Implementing custom Docker containers in Google Cloud Dataflow enhances efficiency, scalability, and control over your data processing environment. By following this comprehensive guide, you have learned to create a Dockerfile with the required environment, build and manage the Docker image in GCP Artifact Registry, and run your Dataflow pipelines using the custom container. This advanced approach ensures optimized performance, particularly beneficial for complex pipelines requiring specific configurations or third-party software integration.</p><p>With these steps, you’re equipped to deploy robust and efficient Dataflow pipelines, harnessing the full potential of Google Cloud’s powerful data processing capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced9e2aa7faf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chatbot basado en RAG para explorar Argumentos Sociotécnicos en la Planificación Territorial: El…]]></title>
            <link>https://medium.com/@tommanzur/chatbot-basado-en-rag-para-explorar-argumentos-sociot%C3%A9cnicos-en-la-planificaci%C3%B3n-territorial-el-22acf82c1474?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/22acf82c1474</guid>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[sociologia]]></category>
            <category><![CDATA[territorio]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 01:30:04 GMT</pubDate>
            <atom:updated>2024-01-23T01:30:04.043Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chatbot basado en RAG para explorar Argumentos Sociotécnicos en la Planificación Territorial: El Caso del PPOT de Mendoza a través de la lente de ArguBot</h3><p>Como parte de mi trayectoria doctoral en la Universidad Nacional de San Martín, Escuela Interdisciplinar de Altos Estudios Sociales, tuve la oportunidad de sumergirme en el complejo mundo de la planificación territorial y sus argumentos sociotécnicos. Mi tesis, titulada “Construcción de Argumentos y Controversias Socio-Técnicas: Análisis del conflicto en la discusión del Plan Provincial de Ordenamiento Territorial de la Provincia de Mendoza”, completada en junio de 2021, fue una puerta hacia la comprensión de las dinámicas complejas de las disputas territoriales y los procesos de argumentación. Esta publicación en Medium es una extensión de ese viaje, proporcionando una puerta interactiva a los hallazgos de la tesis a través de ArguBot, un chatbot diseñado para este propósito.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inu5OpB6t8igZcnvcmbG-g.png" /></figure><h3>ArguBot: Conectando la Investigación Académica y la Tecnología Interactiva</h3><p>ArguBot, nacido de la esencia de mi tesis doctoral, sirve como un puente entre la investigación académica y la tecnología práctica e interactiva. No es solo un chatbot; es una herramienta especializada que incorpora técnicas avanzadas de inteligencia artificial y procesamiento de lenguaje natural para facilitar una comprensión más profunda del PPOT (Plan Provincial de Ordenamiento Territorial) de Mendoza.</p><h4>Características Clave de ArguBot:</h4><ul><li>Embedding Model: Utiliza modelos de código abierto para transformar texto en vectores numéricos, asegurando una comprensión matizada de las consultas de los usuarios.</li><li>Generación Aumentada por Recuperación (RAG): Una combinación de modelos basados en recuperación y generativos, vital para manejar consultas complejas.</li><li>Personalización para el contenido de la Tesis: Diseñado para navegar la investigación sobre la planificación territorial de Mendoza y sus controversias socio-técnicas.</li><li>Privacidad del Usuario y Seguridad de Datos: Un principio central en el diseño e implementación de ArguBot.</li></ul><h4>Modelo Gemini Pro</h4><p>En el corazón de ArguBot yace el modelo Gemini Pro, un sistema avanzado de inteligencia artificial conocido por su competencia en la comprensión y generación de lenguaje. Este modelo es crucial para interpretar las complejas sutilezas de las consultas relacionadas con controversias sociotécnicas y planificación territorial. Los sofisticados algoritmos de Gemini Pro permiten a ArguBot analizar datos textuales extensos, extraer información relevante y sintetizar respuestas que no solo son precisas sino también contextualmente ricas. Esto hace que el chatbot sea excepcionalmente hábil para interactuar con los temas diversos y complicados presentados en mi tesis doctoral.</p><h4>Embeddings de HuggingFace</h4><p>Para mejorar aún más sus capacidades de procesamiento de lenguaje, ArguBot integra embeddings de HuggingFace. Estos embeddings son cruciales para convertir las entradas textuales en vectores numéricos significativos. Al aprovechar los modelos de lenguaje de vanguardia de HuggingFace, ArguBot adquiere una comprensión matizada de las consultas de los usuarios, asegurando que las respuestas no solo sean relevantes sino que también demuestren una profunda comprensión del tema. Estos embeddings permiten al chatbot captar los aspectos más sutiles del lenguaje, haciéndolo excepcionalmente hábil en manejar consultas complejas y variadas relacionadas con el contenido de la tesis.</p><h4>Base de Datos ChromaDB</h4><p>La base de conocimientos de ArguBot está alimentada por ChromaDB, un sistema de base de datos robusto y dinámico. La arquitectura de ChromaDB está específicamente diseñada para manejar grandes volúmenes de datos de manera eficiente, lo que la convierte en una elección ideal para almacenar y gestionar la información exhaustiva abarcada en mi tesis. Esta base de datos juega un papel crítico al proporcionar a ArguBot un acceso rápido y confiable a información detallada sobre el PPOT de Mendoza, asegurando que el chatbot pueda recuperar y referenciar puntos de datos específicos con precisión y rapidez durante las interacciones con los usuarios.</p><h4>Llama-index para la Recuperación de Información</h4><p>Una de las características destacadas de ArguBot es su uso del Llama-index para la recuperación de información. Esta herramienta innovadora es integral para el aspecto de Generación Aumentada por Recuperación (RAG) del chatbot. El Llama-index sobresale en filtrar extensas bases de datos para encontrar la información más relevante en respuesta a las consultas de los usuarios. Cuando se combina con las capacidades generativas de Gemini Pro, permite a ArguBot no solo recuperar información precisa y pertinente sino también generar respuestas coherentes, detalladas y contextualmente apropiadas. Esta capacidad es particularmente crucial para abordar consultas complejas y facilitar una comprensión más profunda de las controversias socio-técnicas y el análisis de argumentación relacionados con el Plan de Planificación Territorial de Mendoza.</p><p>La integración de estas sofisticadas tecnologías — Gemini Pro, embeddings de HuggingFace, base de datos ChromaDB y Llama-index — es lo que distingue a ArguBot. Esta combinación de IA avanzada, procesamiento de lenguaje natural, gestión de datos y técnicas de recuperación permite a ArguBot funcionar no solo como un chatbot, sino como un asistente de investigación inteligente, receptivo y altamente eficiente. Refleja mi compromiso con el uso de tecnología de vanguardia para hacer la investigación académica más accesible e interactiva, mejorando así la comprensión de temas sociotécnicos complejos.</p><h4>Instalación e Interacción con ArguBot:</h4><p>ArguBot está convenientemente integrado en un cuaderno de Google Colab, lo que lo hace accesible y fácil de interactuar. Este enfoque permite a los usuarios interactuar directamente con los conceptos de la tesis y las funcionalidades de ArguBot sin necesidad de procesos de configuración complejos.</p><p>Para interactuar con ArguBot, simplemente sigue este enlace al <a href="https://colab.research.google.com/drive/1BXEyGRjwUqkBhw53mAyZGh9DeD7B0VFi?usp=sharing">cuaderno de Google Colab</a>. El cuaderno contiene instrucciones detalladas para la configuración y el uso, asegurando una experiencia de usuario fluida.</p><h4>Desarrollos Futuros:</h4><p>Aunque actualmente ArguBot es accesible a través de la plataforma Google Colab, se están planificando despliegues de una versión web más amigable del chatbot. Esta futura iteración buscará mejorar la accesibilidad y facilidad de uso, cerrando aún más la brecha entre la investigación académica y la aplicación práctica.</p><h3>La Tesis: Una Inmersión Profunda en las Controversias Sociotécnicas de la Planificación Territorial</h3><p>Mi tesis en la Universidad Nacional de San Martín examinó el PPOT de Mendoza entre 2012 y 2017. Es un estudio de caso que enfatiza el conflicto en torno a una herramienta política para la planificación territorial, donde diversas territorialidades entran en choque. Examinó los conflictos subyacentes en las discusiones de políticas, enfatizando los argumentos movilizados durante el proceso.</p><p>La estrategia cualitativa empleó numerosas fuentes primarias y secundarias para descubrir las relaciones entre los argumentos y las territorialidades en disputa. Esto implicó analizar controversias socio-técnicas durante el desarrollo del Plan, observando la participación de los actores sociales y su posicionamiento en relación con las territorialidades tensionadas. Los hallazgos destacaron el agua como un elemento central en las disputas territoriales, moldeando las actividades sociales y económicas debido a su escasez.</p><p>La tesis diseccionó las construcciones discursivas en torno a la planificación territorial de Mendoza, revelando el papel central del agua como elemento estructurante en la definición de futuros territoriales. También examinó las percepciones de riesgo y las narrativas de cambio ambiental global dentro del discurso de planificación territorial.</p><h4>Componentes Clave de la Tesis:</h4><ul><li>Objetivo: Desentrañar el conflicto subyacente en la planificación territorial de Mendoza, centrándose en la movilización de argumentos durante el proceso.</li><li>Metodología: Un enfoque cualitativo, aprovechando extensas fuentes primarias y secundarias, analizando discursos de partes interesadas, documentos oficiales y registros de audiencias públicas.</li><li>Hallazgos: El papel central del uso del agua en las disputas territoriales, revelando dinámicas de poder e impactos socioeconómicos.</li></ul><h4>Ejemplos de interacciones de usuario con ArguBot</h4><p>ArguBot permite a los usuarios hacer preguntas y recibir respuestas detalladas basadas en el contenido de la tesis. Aquí hay unos ejemplos:</p><ul><li>Comprender los conflictos de planificación territorial</li></ul><blockquote>Usuario: “¿Puedes explicar el principal conflicto en el Plan de Ordenamiento Territorial de Mendoza?”</blockquote><blockquote>ArguBot: “El principal conflicto gira en torno a la gestión de los recursos hídricos…”</blockquote><ul><li>Explorando las controversias sociotécnicas</li></ul><blockquote>Usuario: “¿Cuáles son las controversias sociotécnicas que se discuten en la tesis?”</blockquote><blockquote>ArguBot: “La tesis destaca controversias como el impacto de las políticas de gestión del agua…”</blockquote><ul><li>Consulta sobre metodología y hallazgos específicos</li></ul><blockquote>Usuario: “¿Cómo se aplicó el enfoque de investigación cualitativa en la tesis?”</blockquote><blockquote>ArguBot: “El enfoque cualitativo implicó analizar discursos a partir de entrevistas…”</blockquote><h4>Links de interés</h4><p>Para explorar el espectro completo de mi investigación e interactuar con ArguBot, invito a los lectores a acceder a la tesis y al Notebook en <a href="https://github.com/tommanzur/ArguBot">GitHub</a>: Tomás Manzur’s ArguBot Project.</p><p><a href="https://ri.unsam.edu.ar/handle/123456789/1656">Link de descarga de la tesis Doctoral.</a></p><h4>Pensamientos finales</h4><p>Este esfuerzo es más que una culminación de mi trabajo académico; es un camino para difundir el conocimiento de una manera atractiva e interactiva. ArguBot no es sólo una herramienta sino un compañero en la exploración del complejo mundo de los argumentos sociotécnicos en la planificación territorial, particularmente en el contexto del PPOT de Mendoza. Espero que esta publicación de Medium y ArguBot brinden información valiosa y alienten una mayor exploración en este fascinante campo.</p><p><em>Tomás Manzur, Doctor en Sociología, Universidad Nacional de San Martín</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/008b87be683474ead95d4ce699e272af/href">https://medium.com/media/008b87be683474ead95d4ce699e272af/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22acf82c1474" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A RAG based chatbot for exploring Sociotechnical Arguments in Land Use Planning: The Case of…]]></title>
            <link>https://medium.com/@tommanzur/a-rag-based-chatbot-for-exploring-sociotechnical-arguments-in-land-use-planning-the-case-of-d32ef36e82c7?source=rss-e10e29dab75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d32ef36e82c7</guid>
            <category><![CDATA[sociology]]></category>
            <category><![CDATA[land-use-planning]]></category>
            <category><![CDATA[data-sicence]]></category>
            <category><![CDATA[mendoza]]></category>
            <category><![CDATA[controversy]]></category>
            <dc:creator><![CDATA[Tomás Manzur]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 01:01:50 GMT</pubDate>
            <atom:updated>2024-01-23T01:15:35.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>A RAG based chatbot for exploring Sociotechnical Arguments in Land Use Planning: The Case of Mendoza’s PPOT through the Lens of ArguBot</h3><p>As part of my doctoral journey at the Universidad Nacional de San Martín, Escuela Interdisciplinar de Altos Estudios Sociales, I had the opportunity to delve deep into the intricate world of territorial planning and its sociotechnical arguments. My thesis, titled “Construction of Arguments and Socio-Technical Controversies: Analysis of the conflict in the discussion of the Provincial Territorial Planning Plan of the Province of Mendoza,” completed in June 2021, was a door to understanding the complex dynamics of territorial disputes and argumentation processes. This Medium post is an extension of that journey, providing an interactive gateway to the thesis’s findings through ArguBot, a chatbot designed for this very purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inu5OpB6t8igZcnvcmbG-g.png" /></figure><h3>ArguBot: Bridging Academic Research and Interactive Technology</h3><p>ArguBot, born from the essence of my doctoral thesis, serves as a bridge between academic research and practical, interactive technology. It’s not just a chatbot; it’s a specialized tool incorporating advanced artificial intelligence and natural language processing techniques to facilitate a deeper understanding of the PPOT (Plan Provincial de Ordenamiento Territorial) of Mendoza.</p><h4>Key Features of ArguBot:</h4><ul><li>Embedding Model: Utilizes open-source models to transform text into numerical vectors, ensuring a nuanced understanding of user queries.</li><li>Retrieval-Augmented Generation (RAG): A combination of retrieval-based and generative models, vital for handling complex queries.</li><li>Customization for Thesis Content: Tailored to navigate the intricacies of Mendoza’s territorial planning and its socio-technical controversies.</li><li>User Privacy and Data Security: A core principle in the design and implementation of ArguBot.</li></ul><h4>Gemini Pro Model</h4><p>At the heart of ArguBot lies the Gemini Pro model, an advanced artificial intelligence system renowned for its proficiency in language understanding and generation. This model is pivotal in interpreting the complex nuances of queries related to sociotechnical controversies and territorial planning. Gemini Pro’s sophisticated algorithms enable ArguBot to analyze extensive textual data, extract relevant information, and synthesize responses that are not only accurate but contextually rich. This makes the chatbot exceptionally adept at engaging with the diverse and intricate themes presented in my doctoral thesis.</p><h4>HuggingFace Embeddings</h4><p>To further enhance its language processing capabilities, ArguBot integrates HuggingFace embeddings. These embeddings are crucial for converting textual inputs into meaningful numerical vectors. By leveraging HuggingFace’s state-of-the-art language models, ArguBot gains a nuanced understanding of user queries, ensuring that responses are not only relevant but also exhibit a deep comprehension of the subject matter. These embeddings allow the chatbot to grasp the subtlest aspects of language, making it exceptionally skilled at handling complex and varied inquiries related to the thesis content.</p><h4>ChromaDB Database</h4><p>ArguBot’s knowledge base is powered by ChromaDB, a robust and dynamic database system. ChromaDB’s architecture is specifically designed to handle large volumes of data efficiently, making it an ideal choice for storing and managing the comprehensive information encompassed in my thesis. This database plays a critical role in providing ArguBot with quick and reliable access to detailed information about the PPOT of Mendoza, ensuring that the chatbot can retrieve and reference specific data points accurately and swiftly during user interactions.</p><h4>Llama-Index for Information Retrieval</h4><p>One of the standout features of ArguBot is its use of the llama-index for information retrieval. This innovative tool is integral to the Retrieval-Augmented Generation (RAG) aspect of the chatbot. Llama-index excels in sifting through extensive databases to find the most relevant information in response to user queries. When combined with the generative capabilities of Gemini Pro, it allows ArguBot to not only retrieve accurate and pertinent information but also to generate coherent, detailed, and contextually appropriate responses. This capability is particularly crucial for addressing complex queries and facilitating a deeper understanding of the socio-technical controversies and argumentation analysis related to Mendoza’s Territorial Planning Plan.</p><p>The integration of these sophisticated technologies — Gemini Pro, HuggingFace embeddings, ChromaDB database, and llama-index — is what sets ArguBot apart. This blend of advanced AI, natural language processing, data management, and retrieval techniques enables ArguBot to function not just as a chatbot, but as an intelligent, responsive, and highly efficient research assistant. It reflects my commitment to using cutting-edge technology to make academic research more accessible and interactive, thereby enhancing the understanding of complex sociotechnical issues.</p><h4>Installation and Interaction with ArguBot:</h4><p>ArguBot is conveniently integrated into a Google Colab notebook, making it accessible and easy to interact with. This approach allows users to directly engage with the thesis’s concepts and ArguBot’s functionalities without the need for complex setup processes.</p><p>To interact with ArguBot, simply follow this link to the <a href="https://colab.research.google.com/drive/1BXEyGRjwUqkBhw53mAyZGh9DeD7B0VFi?usp=sharing">Google Colab notebook</a>. The notebook contains detailed instructions for setup and usage, ensuring a smooth user experience.</p><p><strong>Future Developments:</strong></p><p>While currently ArguBot is accessible through the Google Colab platform, plans are underway to deploy a more user-friendly web version of the chatbot. This future iteration will aim to enhance accessibility and ease of use, further bridging the gap between academic research and practical application.</p><h3>The Thesis: A Deep Dive into Sociotechnical Controversies of Territorial Planning</h3><p>My thesis at the Universidad Nacional de San Martín scrutinized the PPOT of Mendoza between 2012 and 2017. It’s a case study emphasizing the conflict around a political tool for territorial planning, where various territorialities clash. It examined the underlying conflicts in policy discussions, emphasizing arguments mobilized during the process.</p><p>The qualitative strategy employed numerous primary and secondary sources to uncover the relationships between arguments and the varying territorialities in dispute. This involved analyzing socio-technical controversies during the Plan’s development, observing social actors’ involvement, and positioning in relation to tensioned territorialities. The findings highlighted water as a central element in territorial disputes, shaping social and economic activities due to its scarcity.</p><p>The thesis dissected the discursive constructions around Mendoza’s territorial planning, revealing the central role of water as a structuring element in defining territorial futures. It also scrutinized the risk perceptions and global environmental change narratives within the territorial planning discourse.</p><h4>Key Components of the Thesis:</h4><ul><li>Objective: Unraveling the underlying conflict in Mendoza’s territorial planning, focusing on the mobilization of arguments during the process.</li><li>Methodology: A qualitative approach, leveraging extensive primary and secondary sources, analyzing stakeholder discourses, official documents, and public hearing records.</li><li>Findings: The central role of water usage in territorial disputes, revealing power dynamics and social-economic impacts.</li></ul><h3>Sample User Interactions with ArguBot</h3><p>ArguBot allows users to ask questions and receive detailed responses based on the thesis content. Here are some examples:</p><ul><li>Understanding Territorial Planning Conflicts</li></ul><blockquote>User: “Can you explain the main conflict in the Mendoza Territorial Planning Plan?”</blockquote><blockquote>ArguBot: “The main conflict revolves around water resource management…”</blockquote><ul><li>Exploring Socio-Technical Controversies</li></ul><blockquote>User: “What are the socio-technical controversies discussed in the thesis?”</blockquote><blockquote>ArguBot: “The thesis highlights controversies such as the impact of water management policies…”</blockquote><ul><li>Inquiry on Methodology and Specific Findings</li></ul><blockquote>User: “How was the qualitative research approach applied in the thesis?”</blockquote><blockquote>ArguBot: “The qualitative approach involved analyzing discourses from interviews…”</blockquote><h3>Further Insights and Access to the Thesis</h3><p>To explore the full spectrum of my research and to interact with ArguBot, I invite readers to access the thesis and the Jupyter Notebook on GitHub: <a href="https://github.com/tommanzur/ArguBot">Tomás Manzur’s ArguBot Project</a>.</p><h3>Final Thoughts</h3><p>This endeavor is more than a culmination of my academic work; it’s a pathway to disseminate knowledge in an engaging, interactive manner. ArguBot is not just a tool but a companion in exploring the complex world of sociotechnical arguments in territorial planning, particularly in the context of Mendoza’s PPOT. I hope this Medium post and ArguBot provide valuable insights and encourage further exploration into this fascinating field.</p><p><em>Tomas Manzur, Doctor in Sociology, Universidad Nacional de San Martín</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/008b87be683474ead95d4ce699e272af/href">https://medium.com/media/008b87be683474ead95d4ce699e272af/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32ef36e82c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>