<?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 Alberto Valdez on Medium]]></title>
        <description><![CDATA[Stories by Alberto Valdez on Medium]]></description>
        <link>https://medium.com/@avq5ac1?source=rss-6c00d18b6b29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QgEBrvQ0RSAcFyhL</url>
            <title>Stories by Alberto Valdez on Medium</title>
            <link>https://medium.com/@avq5ac1?source=rss-6c00d18b6b29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:43:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@avq5ac1/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[Creating Python Models From SQL Tables With Regex]]></title>
            <link>https://medium.com/better-programming/creating-python-models-from-sql-tables-with-regex-1e1bfd95ece6?source=rss-6c00d18b6b29------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1bfd95ece6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[regex]]></category>
            <dc:creator><![CDATA[Alberto Valdez]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 17:01:31 GMT</pubDate>
            <atom:updated>2022-12-01T12:48:21.963Z</atom:updated>
            <content:encoded><![CDATA[<h4>Writing dozens of Python models from SQL tables? You can always use regex</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDifGuphvWOtTSTzgBa36w.jpeg" /><figcaption>Photo by 李进: <a href="https://www.pexels.com/photo/low-angle-photography-of-gray-spiral-building-3172740/">https://www.pexels.com/photo/low-angle-photography-of-gray-spiral-building-3172740/</a></figcaption></figure><p>In this article, we will go over the steps for reading an SQL file and match all the CREATE TABLE statements with a very simple Regex pattern, then write strings of Python classes/models from said tables. Final code <a href="https://github.com/AlbertoV5/psql-to-models">here.</a></p><p>Note that we will use Python 3.10 for this exercise. The results are designed to be used with FastAPI 0.86.0, SQLAlchemy 1.4, and Pydantic 1.10. We are also following <a href="https://github.com/faraday-academy/fast-api-lms">this</a> style of FastAPI, and we are using PostgreSQL 14.5.</p><p>Finally, we will use <a href="https://github.com/MIT-LCP/mimic-code/blob/main/mimic-iii/buildmimic/postgres/postgres_create_tables.sql">this</a> SQL schema as our use case, so we want to convert all 26 tables without partitions to SQLAlchemy/Pydantic models.</p><pre>python --version</pre><pre>Python 3.10.7</pre><h3>Starting at main</h3><p>This will be a retrospective process, so we will start with the main function and then go down from there.</p><p>We want to read a .sql file, then output 2 .py files, one for the SQLAlchemy models and the other for Pydantic models, and include the pattern matching and string processing in between. We are going to come back to the main function once we have the implementation details but for now, let’s take a look at it from the top.</p><pre>def main(argv: Arguments):<br>    &quot;&quot;&quot;Read .sql file with CREATE TABLE queries and store models&quot;&quot;&quot;<br>    with open(Path(argv.input).resolve()) as file:<br>        sql_string = file.read()<br>    # Match pattern<br>    pattern = r&quot;(?:CREATE TABLE )((.|\n*?));&quot;<br>    tables: list[Table] = [<br>        Table.from_string(table[0]) for table in re.findall(patterb, sql_string)<br>    ]<br>    # String processing<br>    alchemy_data = ALCHEMY_HEADER<br>    pydantic_data = PYDANTIC_HEADER<br>    for model, pydantic in generate_strings(tables):<br>        alchemy_data += model<br>        pydantic_data += pydantic<br>    # Output<br>    with open(Path(argv.alchemy).resolve(), &quot;w&quot;) as file:<br>        file.write(alchemy_data)<br>    with open(Path(argv.pydantic).resolve(), &quot;w&quot;) as file:<br>        file.write(pydantic_data)</pre><p>The regex pattern says: “look for CREATE TABLE but don’t include it”, then “include any number of subgroups that are made of anything or a linebreak”, then “repeat that subgroup any number of times in a non-greedy way”, and “end with a semicolon”. The non-greedy part means that it will match as few repetitions as possible, so we stop at “;”.</p><p>Now that we have the big picture, we can step into the specific methods, classes, and constants.</p><h3>The Header Constants</h3><p>We are generating python files that depend on other libraries, so we will create strings that match the imports of our current use case. We need the SQLAlchemy types along with our declarative base for the alchemy file and the Pydantic BaseModel and datetime type for the Pydantic file.</p><pre>ALCHEMY_HEADER = &#39;&#39;&#39;&quot;&quot;&quot;<br>SQLAlchemy Models<br>&quot;&quot;&quot;<br>from sqlalchemy import Column, Integer, String, CHAR, TIMESTAMP, SmallInteger<br>from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION<br>from db.setup import Base<br>&#39;&#39;&#39;<br><br>PYDANTIC_HEADER = &#39;&#39;&#39;&quot;&quot;&quot;<br>Pydantic Models<br>&quot;&quot;&quot;<br>from pydantic import BaseModel<br>from datetime import datetime<br>&#39;&#39;&#39;</pre><h3>Helper Functions</h3><p>Thinking back to our main procedure, the last step before writing the output files is to use the generate_strings function to create both Model strings. This function will iterate over a list of Table objects that represent each SQL table string that we previously matched via Regex, then call the method that creates the Model strings (in Python syntax) and yields them to the main procedure. We use the is_valid function as a “crutch” for our Regex pattern as we don’t mind matching ALL tables and then filtering out the ones that are not needed.</p><pre>BANNED_TABLES = [&quot;chartevents_&quot;]<br><br>def is_valid(table: Table) -&gt; bool:<br>    &quot;&quot;&quot;Whether table is not in banned tables.&quot;&quot;&quot;<br>    for banned in BANNED_TABLES:<br>        if banned in table.name:<br>            return False<br>    return True<br><br><br>def generate_strings(tables: list[Table]) -&gt; Generator[tuple[str, str], None, None]:<br>    &quot;&quot;&quot;Yields SQLAlchemy and Pydantic Models as strings for each table.&quot;&quot;&quot;<br>    for table in tables:<br>        table.get_constraints()<br>        alchemy = f&quot;\n{table.make_alchemy()}&quot; if is_valid(table) else &quot;&quot;<br>        pydantic = f&quot;\n{table.make_pydantic()}&quot; if is_valid(table) else &quot;&quot;<br>        yield alchemy, pydantic</pre><h3>Top and Bottom of main</h3><p>Before taking a look at the implementation of the “Table” class, we will include the imports in the main function and the argument parser to add context to the main file.</p><pre>from typing import Generator, Protocol<br>from argparse import ArgumentParser<br>from pathlib import Path<br>import re<br><br>from .table import Table<br><br><br>class Arguments(Protocol):<br>    input: str<br>    alchemy: str<br>    pydantic: str</pre><p>Our arguments are the locations of the files. The name of this file is __main__.py as we are using this utility as a module we can call from the command line. More info here: <a href="https://github.com/AlbertoV5/psql-to-models">https://github.com/AlbertoV5/psql-to-models</a></p><pre>if __name__ == &quot;__main__&quot;:<br>    default_sql_input = &quot;./schema.sql&quot;<br>    default_alchemy_output = &quot;./models_alchemy.py&quot;<br>    default_pydantic_output = &quot;./models_pydantic.py&quot;<br>    args = ArgumentParser(<br>        prog=&quot;Convert PostgreSQL schema to SQLAlchemy and Pydantic Models.&quot;,<br>        usage=f&quot;python -m psql-to-models&quot;,<br>        description=&quot;Regex-match the .sql schema file and outputs SQLAlchemy and Pydantic models as .py files.&quot;,<br>    )<br>    args.add_argument(<br>        &quot;-i&quot;,<br>        &quot;--input&quot;,<br>        metavar=&quot;input&quot;,<br>        default=f&quot;{default_sql_input}&quot;,<br>        help=f&quot;PostgreSQL Schema input file. Defaults to {default_sql_input}.&quot;,<br>    )<br>    args.add_argument(<br>        &quot;-a&quot;,<br>        &quot;--alchemy&quot;,<br>        metavar=&quot;output_alchemy&quot;,<br>        default=f&quot;{default_alchemy_output}&quot;,<br>        help=f&quot;SQLAlchemy Models output. Defaults to {default_alchemy_output}&quot;,<br>    )<br>    args.add_argument(<br>        &quot;-p&quot;,<br>        &quot;--pydantic&quot;,<br>        metavar=&quot;output_pydantic&quot;,<br>        default=f&quot;{default_pydantic_output}&quot;,<br>        help=f&quot;Pydantic Models output. Defaults to {default_pydantic_output}&quot;,<br>    )<br>    main(args.parse_args())</pre><h3>The Table Class</h3><p>Now that we have the overall logic of our program, we will go to the “Table” class, which represents the entire SQL table statement and has the methods to process it and create the Model strings.</p><pre>&quot;&quot;&quot;<br>Table representation and processor.<br>Call any get_* functions before calling make_* functions.<br>&quot;&quot;&quot;<br>from dataclasses import dataclass<br>from .column import Column<br><br><br>@dataclass<br>class Table:<br>    name: str<br>    columns: list[Column]<br><br>    @classmethod<br>    def from_string(cls, table: str) -&gt; &quot;Table&quot;:<br>        &quot;&quot;&quot;Create Table from string.&quot;&quot;&quot;<br>        data = table.split(&quot;\n&quot;)<br>        return Table(<br>            name=data[0], columns=[Column.from_string(col) for col in data[2:-1]]<br>        )<br><br>    def get_constraints(self) -&gt; None:<br>        &quot;&quot;&quot;Use the CONSTRAINT columns to modify the rest of the columns.&quot;&quot;&quot;<br>        constraints = [col.params for col in self.columns if col.name == &quot;CONSTRAINT&quot;]<br>        data = [c.replace(&quot;)&quot;, &quot;&quot;).split(&quot;(&quot;) for c in constraints]<br>        data = {k.strip(): v.strip() for v, k in data}<br>        for column in self.columns:<br>            for k in data:<br>                if column.name == k:<br>                    column.primary_key = (<br>                        &quot;primary_key=True&quot; if data[k] == &quot;PRIMARY KEY&quot; else &quot;&quot;<br>                    )<br>                    column.unique = &quot;unique=True&quot; if data[k] == &quot;UNIQUE&quot; else &quot;&quot;<br><br>    def make_alchemy(self) -&gt; str:<br>        &quot;&quot;&quot;Make SQLAlchemy model string from this Table.&quot;&quot;&quot;<br>        cols = &quot;\n    &quot;.join(<br>            col.make_alchemy_column()<br>            for col in self.columns<br>            if col.name != &quot;CONSTRAINT&quot;<br>        )<br>        return (<br>            f&quot;class {self.name.capitalize()}(Base):\n\n&quot;<br>            f&#39;    __tablename__ = &quot;{self.name.lower()}&quot;\n\n&#39;<br>            f&quot;    {cols}\n\n&quot;<br>        )<br><br>    def make_pydantic(self) -&gt; str:<br>        &quot;&quot;&quot;Make Pydantic model string from this Table.&quot;&quot;&quot;<br>        params = &quot;\n    &quot;.join(<br>            col.make_pydantic_column()<br>            for col in self.columns<br>            if col.name != &quot;CONSTRAINT&quot;<br>        )<br>        return (<br>            f&quot;class {self.name.capitalize()}(BaseModel):\n\n&quot;<br>            f&quot;    {params}\n\n&quot;<br>            f&quot;    class Config:\n&quot;<br>            f&quot;        orm_mode = True\n\n&quot;<br>        )</pre><p>Note that the constructor we want to use is a class method. We could have chosen a post-init process, or we could have created it as an external factory function but we chose to keep it as part of the Table class for convenience. The design for the Table class is separating the processing into get methods which process the information in the list of Columns, and make methods which convert the Columns’ data into strings.</p><p>The Column class is similar to Table but specializes in parsing the SQL statement for a column (“column_name INT NOT NULL”) and it has the methods for creating the strings for the Model’s attributes.</p><p>We use get_constraints to look for the CONSTRAINT SQL statements in the list of Columns and then modify the attributes of the actual Columns, this includes the primary_key<strong> </strong>attribute, the unique one, etc.</p><h3>The Column Class</h3><p>We need to split the single SQL statement into different attributes that we can use to describe names or types, as well as express CONSTRAINTS like UNIQUE as “unique” in SQLAlchemy or the absence of NOT NULL as “optional” in Pydantic.</p><p>This class could be named “Statement” as it includes any other SQL statements that may not be a “column”, but we generalize and filter them at the Table level.</p><pre>&quot;&quot;&quot;<br>Column representation and processor.<br>&quot;&quot;&quot;<br>from dataclasses import dataclass<br>from .types import TYPE_LOOKUP<br><br><br>@dataclass<br>class Column:<br>    name: str<br>    type: str<br>    params: str<br>    primary_key: str = &quot;&quot;<br>    unique: str = &quot;&quot;<br><br>    @classmethod<br>    def from_string(cls, col: str) -&gt; &quot;Column&quot;:<br>        &quot;&quot;&quot;Create column from string.&quot;&quot;&quot;<br>        data = col.strip().replace(&quot;,&quot;, &quot;&quot;).split(&quot; &quot;, maxsplit=2)<br>        return Column(<br>            name=data[0], type=data[1], params=data[2] if len(data) &gt; 2 else &quot;&quot;<br>        )<br><br>    def get_type(self, sqlalchemy: bool = True) -&gt; str:<br>        &quot;&quot;&quot;<br>        Lookup types and return either SQLAlchemy&#39;s or Pydantic&#39;s.<br>        &quot;&quot;&quot;<br>        t = self.type.replace(&quot;)&quot;, &quot;&quot;).split(&quot;(&quot;)<br>        index = 0 if sqlalchemy else 1<br>        if len(t) &gt; 1:<br>            return (<br>                f&quot;{TYPE_LOOKUP[t[0]][index]}({t[1]})&quot;<br>                if sqlalchemy<br>                else TYPE_LOOKUP[t[0]][index]<br>            )<br>        return TYPE_LOOKUP[self.type][index]<br><br>    def make_alchemy_column(self) -&gt; str:<br>        &quot;&quot;&quot;Make SQLAlchemy Model column string.&quot;&quot;&quot;<br>        return (<br>            f&quot;{self.name.lower()} = Column(&quot;<br>            f&quot;{self.get_type()}&quot;<br>            f&quot;{&#39;, nullable=False&#39; if &#39;NOT NULL&#39; in self.params else &#39;&#39;}&quot;<br>            f&quot;{&#39;&#39; if self.primary_key == &#39;&#39; else f&#39;, {self.primary_key}&#39;}&quot;<br>            f&quot;{&#39;&#39; if self.unique == &#39;&#39; else f&#39;, {self.unique}&#39;}&quot;<br>            f&quot;)&quot;<br>        )<br><br>    def make_pydantic_column(self) -&gt; str:<br>        &quot;&quot;&quot;Make Pydantic Model column string.&quot;&quot;&quot;<br>        return (<br>            f&quot;{self.name.lower()}: &quot;<br>            f&quot;{self.get_type(sqlalchemy=False)}&quot;<br>            f&quot;{&#39;&#39; if &#39;NOT NULL&#39; in self.params else &#39; | None&#39;}&quot;<br>        )</pre><p>We repeat the “class method as constructor” pattern as well as the<strong> </strong>get then<strong> </strong>make<strong> </strong>pattern from the Table class but this time we include the TYPE_LOOKUP constant which will help us “translate” the SQL types to other types that interest us.</p><p>Note that the Optional pattern is converted to the “new” Python 3.10 syntax, so it should be modified to support “Optional or Union” for previous Python versions.</p><h3>The Type-Lookup-Table</h3><p>The TYPE_LOOKUP dictionary will serve as a lookup table where we can find the Python equivalence of each SQL type (PostgreSQL in this case) and lives in its own types.py file.</p><pre>&quot;&quot;&quot;Define constants for type lookup.&quot;&quot;&quot;<br><br>TYPE_LOOKUP: dict[str, tuple[str, str]] = {<br>    &quot;INT&quot;: (&quot;Integer&quot;, &quot;int&quot;),<br>    &quot;SMALLINT&quot;: (&quot;SmallInteger&quot;, &quot;int&quot;),<br>    &quot;VARCHAR&quot;: (&quot;String&quot;, &quot;str&quot;),<br>    &quot;TIMESTAMP&quot;: (&quot;TIMESTAMP&quot;, &quot;datetime&quot;),<br>    &quot;DOUBLE&quot;: (&quot;DOUBLE_PRECISION&quot;, &quot;float&quot;),<br>    &quot;CHAR&quot;: (&quot;CHAR&quot;, &quot;str&quot;),<br>    &quot;TEXT&quot;: (&quot;String&quot;, &quot;str&quot;),<br>}<br>&quot;&quot;&quot;Values are tuples of SQLAlchemy Model Type and Pydantic/Python Type.&quot;&quot;&quot;</pre><p>This forces us to use a tuple instead of a new level of keys for accessing each value as we assume we are only going to use this tool for two target models, plus any other models can simply be included by extending the tuple.</p><h3>Back to Main</h3><p>Now that we understand the methods used for processing the strings, we can go back and review the main procedure. It can be summarized as:</p><ol><li>Matching the Regex pattern.</li><li>Storing and processing the strings with our data classes.</li><li>Creating a new “Python string” that Python understands as the SQLAlchemy and Pydantic models.</li></ol><pre># Pattern Matching<br>pattern = r&quot;(?:CREATE TABLE )((.|\n)*?);&quot;<br>tables: list[Table] = [<br>    Table.from_string(table[0]) for table in re.findall(pattern, sql_string)<br>]<br># String Processing<br>alchemy_data = ALCHEMY_HEADER<br>pydantic_data = PYDANTIC_HEADER<br>for model, pydantic in generate_strings(tables):<br>    alchemy_data += model<br>    pydantic_data += pydantic</pre><p>The values we need to change in every use case are the HEADER constants and our LOOKUP_TYPE dictionary as we may have different sets of columns and requirements based on the project’s nature.</p><p>In my case, this tool solves the problem I was facing at the time, so I leave it as it is now and share it with the intention of both coming back to it in the future and motivating any other user that may find it useful to adapt it to their needs, so there you go, I hope this was useful in any way.</p><h3>Results</h3><p>You can find the results from this use case <a href="https://github.com/AlbertoV5/psql-to-models/tree/main/example">here</a>.</p><p>Here is a preview:</p><h4>The SQL file</h4><pre>CREATE TABLE DATETIMEEVENTS<br>(<br>  ROW_ID INT NOT NULL,<br> SUBJECT_ID INT NOT NULL,<br> HADM_ID INT,<br> ICUSTAY_ID INT,<br> ITEMID INT NOT NULL,<br> CHARTTIME TIMESTAMP(0) NOT NULL,<br> STORETIME TIMESTAMP(0) NOT NULL,<br> CGID INT NOT NULL,<br> VALUE TIMESTAMP(0),<br> VALUEUOM VARCHAR(50) NOT NULL,<br> WARNING SMALLINT,<br> ERROR SMALLINT,<br> RESULTSTATUS VARCHAR(50),<br> STOPPED VARCHAR(50),<br> CONSTRAINT datetime_rowid_pk PRIMARY KEY (ROW_ID)<br>) ;<br><br>DROP TABLE IF EXISTS DIAGNOSES_ICD CASCADE;<br>CREATE TABLE DIAGNOSES_ICD<br>(<br>  ROW_ID INT NOT NULL,<br> SUBJECT_ID INT NOT NULL,<br> HADM_ID INT NOT NULL,<br> SEQ_NUM INT,<br> ICD9_CODE VARCHAR(10),<br> CONSTRAINT diagnosesicd_rowid_pk PRIMARY KEY (ROW_ID)<br>) ;</pre><h4>The SQLAlchemy Models</h4><pre>class Datetimeevents(Base):<br><br>    __tablename__ = &quot;datetimeevents&quot;<br><br>    row_id = Column(Integer, nullable=False, primary_key=True)<br>    subject_id = Column(Integer, nullable=False)<br>    hadm_id = Column(Integer)<br>    icustay_id = Column(Integer)<br>    itemid = Column(Integer, nullable=False)<br>    charttime = Column(TIMESTAMP(0), nullable=False)<br>    storetime = Column(TIMESTAMP(0), nullable=False)<br>    cgid = Column(Integer, nullable=False)<br>    value = Column(TIMESTAMP(0))<br>    valueuom = Column(String(50), nullable=False)<br>    warning = Column(SmallInteger)<br>    error = Column(SmallInteger)<br>    resultstatus = Column(String(50))<br>    stopped = Column(String(50))<br><br><br>class Diagnoses_icd(Base):<br><br>    __tablename__ = &quot;diagnoses_icd&quot;<br><br>    row_id = Column(Integer, nullable=False, primary_key=True)<br>    subject_id = Column(Integer, nullable=False)<br>    hadm_id = Column(Integer, nullable=False)<br>    seq_num = Column(Integer)<br>    icd9_code = Column(String(10))</pre><h4>The Pydantic Models</h4><pre>class Datetimeevents(BaseModel):<br><br>    row_id: int<br>    subject_id: int<br>    hadm_id: int | None<br>    icustay_id: int | None<br>    itemid: int<br>    charttime: datetime<br>    storetime: datetime<br>    cgid: int<br>    value: datetime | None<br>    valueuom: str<br>    warning: int | None<br>    error: int | None<br>    resultstatus: str | None<br>    stopped: str | None<br><br>    class Config:<br>        orm_mode = True<br><br><br>class Diagnoses_icd(BaseModel):<br><br>    row_id: int<br>    subject_id: int<br>    hadm_id: int<br>    seq_num: int | None<br>    icd9_code: str | None<br><br>    class Config:<br>        orm_mode = True</pre><h3>Footnotes</h3><p><a href="https://stackoverflow.com/questions/766372/python-non-greedy-regexes">https://stackoverflow.com/questions/766372/python-non-greedy-regexes</a></p><p><a href="https://docs.sqlalchemy.org/en/14/orm/mapping_styles.html#orm-declarative-mapping">https://docs.sqlalchemy.org/en/14/orm/mapping_styles.html#orm-declarative-mapping</a></p><p><a href="https://pydantic-docs.helpmanual.io/usage/models/">https://pydantic-docs.helpmanual.io/usage/models/</a></p><p><a href="https://docs.python.org/3/library/dataclasses.html">https://docs.python.org/3/library/dataclasses.html</a></p><p><a href="https://docs.python.org/3/library/typing.html#typing.Optional">https://docs.python.org/3/library/typing.html#typing.Optional</a></p><p><em>Originally published at </em><a href="https://github.com/AlbertoV5/python-blog/blob/main/static/sql-converter.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1bfd95ece6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/creating-python-models-from-sql-tables-with-regex-1e1bfd95ece6">Creating Python Models From SQL Tables With Regex</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Path Glob v.s. OS Walk]]></title>
            <link>https://medium.com/@avq5ac1/path-glob-v-s-os-walk-4278d6add6ac?source=rss-6c00d18b6b29------2</link>
            <guid isPermaLink="false">https://medium.com/p/4278d6add6ac</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Alberto Valdez]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 17:54:24 GMT</pubDate>
            <atom:updated>2022-10-11T17:54:24.969Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparing Python’s ways of traversing a directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zagpuGdaACy231KI.jpg" /><figcaption>Taking a global look.</figcaption></figure><p>This article is a follow-up to <a href="https://medium.com/@avq5ac1/glob-generators-with-python-be9ad86ca682">“Glob generators in Python”</a>, we are going to compare the os.walk to the Path.glob method that we used in the past, both in the context of generators.</p><p>Github markdown <a href="https://github.com/AlbertoV5/python-blog/blob/main/static/glob-compare.md">here</a>. Final code <a href="https://github.com/AlbertoV5/python-blog/blob/main/tests/glob/test_main.py">here</a>.</p><p>The question we are trying to answer is if we want to use Path.glob at all or if it is better to check for specific file extensions instead of using patterns.</p><p>We are going to use cProfile to measure the code execution and snakeviz to visualize the results. We are going to use a few other modules to help us build and evaluate the tests.</p><h3>Mocks</h3><p>We are going to construct a test case before writing the rest of the code. We will do so by creating a few directories and filling them with various file extensions.</p><p>In this scenario we will be searching for the file types: csv, tsv and txt. So we are going to add those extensions to a list that we will use to generate all possible permutations of the the extensions&#39; characters.</p><p>We are going to use set so we make sure we don&#39;t process extra data when doing the permutations and any further processing. However, we want to include extensions with repeated letters in the data we feed to the permutation function, so that data won&#39;t be converted to a set.</p><pre>def create_options(extensions):<br>    data = list(i for e in extensions for i in list(e))<br>    data.append(&quot;&quot;)<br>    return list(set(&quot;&quot;.join(c) for c in permutations(data, 4)))</pre><p>If we print our options, we can see that we have a large number of possible file prefixes we can use for testing.</p><pre>options = create_options([&quot;csv&quot;, &quot;tsv&quot;, &quot;txt&quot;])<br>print(len(options))</pre><p>Result:</p><pre>467</pre><p>Before creating the files in the test directory, we are going to add a few children directories so we can test recursive search too. We are going to create 2 ‘tuneable’ variables, depth and number, which will effectively bring the total amount of directories to depth ** number. Then we are going to create the directories somewhat recursively while adding each one to a directories list.</p><pre>def create_directories(root: str, number: int, depth: int):<br>    root = Path(root).resolve()<br>    if root.is_dir():<br>        shutil.rmtree(root)<br>    Path.mkdir(root, parents=True)<br>    # func<br>    def mk_dirs(parent, data, n, depth):<br>        if depth == 0:<br>            return 0<br>        for i in range(n):<br>            child = parent / f&quot;{i}&quot;<br>            Path.mkdir(child)<br>            data.append(child)<br>            mk_dirs(child, data, n, depth - 1)</pre><pre>directories = []<br>    mk_dirs(root, directories, number, depth)<br>    directories.insert(0, root)<br>    return directories</pre><p>Then we can separate the file extensions in different directories. We end up with = directories if we count the root directory. So we are going to separate our {{{results(=467)}}} into x files per directory.</p><pre>create_directories(&#39;../tests/extensions&#39;, 3, 3)<br>print(len(directories))</pre><h3>Final Mock Function</h3><p>Finally, we create all the files spread across multiple directories and assert that there are at more files than the base number directories in each directory.</p><pre>def test_makefiles(ext = [&quot;csv&quot;, &quot;tsv&quot;, &quot;txt&quot;], number = 3, depth = 3):<br>    options = create_options(ext)<br>    directories = create_directories(&#39;../tests/extensions&#39;, number, depth)<br>    n_opt = len(options)<br>    n_dir = len(directories)<br>    ratio = int(n_opt/n_dir)<br>    for i in range(0, n_dir):<br>        for j in range(i * ratio, (i * ratio) + ratio):<br>            filepath = directories[i] / f&quot;file.{options[j]}&quot;<br>            subprocess.run([&#39;touch&#39;, filepath])<br>        assert len(list(directories[i].glob(&#39;*&#39;))) &gt; number<br>    print(&#39;All files were created.&#39;)</pre><p>Result:</p><pre>All files were created.</pre><h3>Profiler</h3><p>We will create a profiler wrapper function so we can apply it to whichever test function we want and get the profile data into a file with its name.</p><pre>def profile(func):<br>    def wrapper(*args, **kwargs):<br>        with cProfile.Profile() as pr:<br>            path = func(*args, **kwargs)<br>            stats = pstats.Stats(pr)<br>            stats.sort_stats(pstats.SortKey.TIME)<br>            stats.dump_stats(filename=f&quot;{path / func.__name__}.prof&quot;)</pre><pre>return wrapper</pre><h3>Final Test Script</h3><p>We are going to combine all previous functions into a single script and include default values for running the test, which includes generating new extensions and directories. We are also gonna create a logger instance to display all info to the pytest stdout. Finally, we are going to execute each function n number of times for better profiler results.</p><pre>from pathlib import Path<br>from itertools import permutations<br>import subprocess<br>import cProfile<br>import logging<br>import pstats<br>import shutil<br>import os<br><br>def create_options(extensions):<br>    data = list(i for e in extensions for i in list(e))<br>    data.append(&quot;&quot;)<br>    return list(set(&quot;&quot;.join(c) for c in permutations(data, 4)))<br><br>def create_directories(root: str, number: int, depth: int):<br>    root = Path(root).resolve()<br>    if root.is_dir():<br>        shutil.rmtree(root)<br>    Path.mkdir(root, parents=True)<br>    # func<br>    def mk_dirs(parent, data, n, depth):<br>        if depth == 0:<br>            return 0<br>        for i in range(n):<br>            child = parent / f&quot;{i}&quot;<br>            Path.mkdir(child)<br>            data.append(child)<br>            mk_dirs(child, data, n, depth - 1)<br><br>    directories = []<br>    mk_dirs(root, directories, number, depth)<br>    directories.insert(0, root)<br>    return directories<br><br>def test_makefiles(ext = [&quot;csv&quot;, &quot;tsv&quot;, &quot;txt&quot;], number = 3, depth = 3):<br>    options = create_options(ext)<br>    directories = create_directories(&#39;../tests/extensions&#39;, number, depth)<br>    n_opt = len(options)<br>    n_dir = len(directories)<br>    ratio = int(n_opt/n_dir)<br>    for i in range(0, n_dir):<br>        for j in range(i * ratio, (i * ratio) + ratio):<br>            filepath = directories[i] / f&quot;file.{options[j]}&quot;<br>            subprocess.run([&#39;touch&#39;, filepath])<br>        assert len(list(directories[i].glob(&#39;*&#39;))) &gt; number<br>    print(&#39;All files were created.&#39;)<br><br>def profile(func):<br>    def wrapper(*args, **kwargs):<br>        with cProfile.Profile() as pr:<br>            path = func(*args, **kwargs)<br>            stats = pstats.Stats(pr)<br>            stats.sort_stats(pstats.SortKey.TIME)<br>            stats.dump_stats(filename=f&quot;{path / func.__name__}.prof&quot;)<br><br>    return wrapper<br><br><br>@profile<br>def test_main():<br>    log = logging.getLogger(__name__)<br>    log.setLevel(logging.DEBUG)<br>    ext = [&#39;csv&#39;, &#39;tsv&#39;, &#39;txt&#39;]<br>    pattern = &#39;**/*.[ct][sx][vt$]&#39;<br>    rootd = &#39;../tests/extensions&#39;<br>    outcome = {&quot;glob&quot;:[], &quot;os&quot;:[]}<br><br>    # using glob<br>    def use_glob():<br>        for f in Path(rootd).glob(pattern):<br>            yield f<br><br>    def consume_glob():<br>        outcome[&quot;glob&quot;] = list(Path(rootd).glob(pattern))<br><br>    # using os<br>    def use_os_comp():<br>        outcome[&quot;os&quot;] = [<br>            f<br>            for root, dirs, files in os.walk(rootd)<br>            for f in files if f.split(&#39;.&#39;)[1] in ext<br>        ]<br><br>    def use_os():<br>        for root, dirs, files in os.walk(rootd):<br>            path = root.split(os.sep)<br>            for file in files:<br>                if file.split(&quot;.&quot;)[1] in ext:<br>                    outcome[&quot;os&quot;].append(file)<br><br>    def use_os_gen():<br>        for root, dirs, files in os.walk(rootd):<br>            for file in files:<br>                if file.split(&quot;.&quot;)[1] in ext:<br>                    yield file<br>    # process<br>    times = 100<br>    [use_glob() for i in range(times)]<br>    [consume_glob() for i in range(times)]<br>    [use_os() for i in range(times)]<br>    [use_os_comp() for i in range(times)]<br>    [use_os_gen() for i in range(times)]<br><br>    def consume_gen(gen):<br>        for file in gen:<br>            # if file.replace(&quot;file.&quot;, &quot;&quot;) == &quot;csv&quot;:<br>                # break<br>            if file.suffix == &quot;.csv&quot;:<br>                break<br><br>    [consume_gen(use_glob()) for i in range(times)]<br>    log.debug(outcome)<br>    return Path(&#39;tests/prof&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ext = [&#39;csv&#39;, &#39;tsv&#39;, &#39;txt&#39;, &#39;xlsx&#39;, &#39;jpg&#39;, &#39;png&#39;]<br>    test_makefiles(ext, 5, 5)<br>    test_main()</pre><p>You can find the script in GitHub:</p><p><a href="https://github.com/AlbertoV5/python-blog/blob/main/tests/glob/test_main.py">python-blog/test_main.py at main · AlbertoV5/python-blog</a></p><h3>Results</h3><p>We’ll run the test with pytest.</p><pre>pytest --log-cli-level=10</pre><p>Result:</p><pre>pytest --log-cli-level=10</pre><pre>============================= test session starts ============================== platform darwin -- Python 3.10.7, pytest-7.1.3, pluggy-1.0.0 rootdir: /Users/albertovaldez/python-blog plugins: profiling-1.7.0 collected 2 items tests/glob/test_main.py::test_makefiles PASSED [ 50%] tests/glob/test_main.py::test_main -------------------------------- live log call --------------------------------- DEBUG test_main:test_main.py:113 {&#39;glob&#39;: [PosixPath(&#39;../tests/extensions/0/1/1/file.txv&#39;), PosixPath(&#39;../tests/extensions/1/1/2/file.cxt&#39;), PosixPath(&#39;../tests/extensions/1/2/file.tsv&#39;), PosixPath(&#39;../tests/extensions/2/0/0/file.csv&#39;), PosixPath(&#39;../tests/extensions/2/0/1/file.cst&#39;), PosixPath(&#39;../tests/extensions/2/0/1/file.tst&#39;), PosixPath(&#39;../tests/extensions/2/1/file.cxv&#39;)], &#39;os&#39;: [&#39;file.tsv&#39;, &#39;file.csv&#39;]} PASSED [100%] ============================== 2 passed in 2.56s ===============================</pre><p>The first result that we can see from the command line log is that the pattern will find files that overlap with the extensions we are looking for. For example: txv, cxt and tst. This may be enough downside for not considering using only glob patterns.</p><p>Then we are going to read the profiler output with snakeviz.</p><pre>pip install snakeviz<br>snakeviz tests/prof/test_main.prof</pre><p>The first time we ran the test we compared the execution time of the following functions.</p><pre>| function     | ttime (s) |<br>|--------------+-----------|<br>| consume_glob |     0.378 |<br>| use_os       |     0.248 |<br>| use_os_comp  |     0.244 |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jFfnhn_8X3NHXpIo.png" /></figure><p>The os.walk method is faster and more accurate as we get the exact file extensions we are looking for.</p><p>However, if we stop the generator from the glob method once a condition is met, we get a shorter execution time, as well as lesser memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PC5P0rpIQEUJEglz.png" /></figure><p>When using os.walk as a generator, we get a slightly slower execution time when following the previous procedure. This may just be because of how os.walk traverses the tree or because we are making a few additional checks when validating file extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xce1fJwrJFKmpl1y.png" /></figure><p>Generators win no matter what. The results from glob weren&#39;t favorable as we had too many collateral file extensions, mainly because of how our test was set up. This is not enough accuracy for us to support using glob patterns so making our own generator from os.walk may be the best option. We can always combine both modules for better file path information and object-oriented features.</p><pre>def walk_gen(path, extensions):<br>    for root, dirs, files in os.walk(path):<br>        for file in files:<br>            if file.split(&quot;.&quot;)[1] in extensions:<br>                yield Path(root) / file</pre><pre>for f in walk_gen(&quot;../tests&quot;, [&quot;py&quot;, &quot;prof&quot;]):<br>    print(f)</pre><p>Result:</p><pre>../tests/prof/test_main.prof <br>../tests/glob/test_main.py</pre><h3>Footnotes</h3><p><a href="https://docs.python.org/3/library/os.html#os.walk">https://docs.python.org/3/library/os.html#os.walk</a></p><p><a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob">https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob</a></p><p><a href="https://jiffyclub.github.io/snakeviz/">https://jiffyclub.github.io/snakeviz/</a></p><p><em>Originally published at </em><a href="https://github.com/AlbertoV5/python-blog/blob/main/static/glob-compare.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4278d6add6ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Glob Generators With Python]]></title>
            <link>https://medium.com/better-programming/glob-generators-with-python-be9ad86ca682?source=rss-6c00d18b6b29------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9ad86ca682</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alberto Valdez]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 18:27:14 GMT</pubDate>
            <atom:updated>2023-02-09T13:07:57.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>What do Python paths and Git ignore files have in common?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhKS1ASFqlUw4bzc9NIGmQ.jpeg" /><figcaption>Global file searching</figcaption></figure><p>This is an exercise on using <a href="https://en.wikipedia.org/wiki/Glob_(programming)">glob</a> patterns to find all image files in a directory. We are going to use the pathlib Python <a href="https://docs.python.org/3/library/pathlib.html">module</a> which provides the glob method in the Path class.</p><p>Glob patterns are also used in .gitignore <a href="https://git-scm.com/docs/gitignore">files</a> so any pattern that works here probably works in Git ignore files too and vice versa.</p><p>Final code <a href="https://github.com/AlbertoV5/python-blog/blob/main/src/glob/get_imgs.py">here</a>.</p><h3>Choosing a Pattern</h3><p>We are going to start with either one of these patterns.</p><pre>*.[jpJP][npNP][egEG]*</pre><pre>*.[jpJP]*[gG$]</pre><p>Our first pattern means “files with extensions that start with j/J or p/P, then continue with n/N or p/P, then e/E or g/G and continue with any characters or none”. This will effectively match jpg, jpeg, png as well as their versions in caps. However, this will also match something like jpega and pngx.</p><p>If we wanted to make sure we don’t match unintended files, we can use the second pattern which means “files with extensions that start with either j/J or p/P and end with g/G”. This also matches jpg, jpeg and png and it won&#39;t match jpega or pngx, however, it will match patterns like jag or pxg.</p><p>If we combine both patterns we can get a more strict match that makes sure the file format ends in g/G and matches all three of our target extensions.</p><pre>*.[jpJP][npNP]*[gG$]</pre><h3>Glob function</h3><p>We are going to use the PIL <a href="https://pillow.readthedocs.io/en/stable/">module</a> for processing images once we get their paths with pathlib.</p><pre>from pathlib import Path<br>from PIL import Image</pre><p>We will define a function and specify what we want to do before writing the code. In our arguments, we want to receive a string and a few boolean values to modify the behavior of our function.</p><p>When iterating over a directory, the results will come up unordered so we may want to sort them alphabetically using sorted. We also may want to search all directories recursively and we can use rglob for that.</p><p>Finally, we want to make this a generator function so we can stop the procedure at any given iteration, so we are going to yield the file path.</p><pre>def get_imgs(directory: str, sort: bool = True, recursive: bool = True):<br>    &quot;&quot;&quot;Yields all image files in given path.</pre><pre>    Args:</pre><pre>        directory (str): Relative directory name.<br>        sort (bool, optional): If generator is sorted. Default True.<br>        recursive (bool, optional): If glob is recursive. Default True.</pre><pre>    Yields:</pre><pre>        (Path): File path.<br>    &quot;&quot;&quot;</pre><p>Let’s start checking if the given path exists. We are going to use resolve to convert any relative paths to absolute ones and then is_dir to check that the directory exists.</p><pre>path = Path(directory).resolve()<br>if not path.is_dir():<br>    raise ValueError(f&quot;&#39;{path}&#39; is not a directory.&quot;)</pre><p>Our pattern variable will hold the glob pattern, frec will use rglob if we want our search to be recursive and fsort will use sorted if we want to sort the results.</p><pre>pattern = &#39;*.[jpJP][npNP]*[gG$]&#39;<br>frec = lambda p, g: p.rglob(g) if recursive else p.glob(g)<br>fsort = lambda x: sorted(x) if sort else x</pre><p>Finally, we’ll use both lambda functions and yield each file path.</p><pre>for file in fsort(frec(path, pattern)):<br>    yield file</pre><p>This is our function once we put it all together.</p><pre>from pathlib import Path<br>from PIL import Image</pre><pre>def get_imgs(directory: str, sort: bool = True, recursive: bool = True):<br>    &quot;&quot;&quot;Yields all image files in given path.</pre><pre>    Args:</pre><pre>        directory (str): Relative directory name.<br>        sort (bool, optional): If generator is sorted. Default True.<br>        recursive (bool, optional): If glob is recursive. Default True.</pre><pre>    Yields:</pre><pre>        (Path): File path.<br>    &quot;&quot;&quot;<br>    path = Path(directory).resolve()<br>    if not path.is_dir():<br>        raise ValueError(f&quot;&#39;{path}&#39; is not a directory.&quot;)<br>    pattern = &#39;*.[jpJP][npNP]*[gG$]&#39;<br>    frec = lambda p, g: p.rglob(g) if recursive else p.glob(g)<br>    fsort = lambda x: sorted(x) if sort else x<br>    for file in fsort(frec(path, pattern)):<br>        yield file</pre><p>Let’s use it in a script where we simply print all the file paths relative to the root.</p><pre>root = Path(&quot;..&quot;).resolve()<br>for f in get_imgs(&#39;../resources&#39;):<br>    print(f.relative_to(root))</pre><p>Result:</p><pre>resources/data/Screen Shot 2022-09-05 at 12.41.33.png<br>resources/data/Screen Shot 2022-09-05 at 12.41.45.png<br>resources/final/007.jpeg<br>resources/final2/000.jpeg<br>resources/img/008.jpeg<br>resources/img/009.jpg<br>resources/img/Screen Shot 2022-09-29 at 13.20.27.png<br>resources/img/Screen Shot 2022-09-29 at 20.07.04.png<br>resources/img/Screen Shot 2022-09-29 at 20.08.21.png<br>resources/old/002.jpeg<br>resources/old/006.jpg</pre><p>Now let’s move on to processing the files with PIL.</p><h3>Processing the files</h3><p>We want to convert all png files into jpeg, as well as renaming jpg to jpeg and then resizing them all to have a given max width.</p><p>We will use the ImageOps module from PIL to simplify the resizing operation and maintain the aspect ratio. The process is the following: we open the file as an image, convert it to &#39;RGB&#39; if suffix is png, then resize it with ImageOps.contain and save it as jpeg using with_suffix.</p><p>Before writing our main process, we will create a function that will replace the file suffix to jpeg as well as change its parent directory. We&#39;ll also create a root variable for printing purposes.</p><pre>from PIL import ImageOps</pre><pre>max_width = 1280<br>with_path = lambda f: Path(&#39;../converted&#39;).resolve() / f.with_suffix(&#39;.jpeg&#39;).name<br>root = Path(&quot;..&quot;).resolve()<br>for f in get_imgs(&#39;../resources&#39;):<br>    with Image.open(f) as img:<br>        if f.suffix == &#39;.png&#39;:<br>            img = img.convert(&#39;RGB&#39;)<br>        if img.size[0] &gt; max_width:<br>            img = ImageOps.contain(img, (max_width, max_width))<br>        fout = with_path(f)<br>        img.save(fout, quality=80)<br>        print(fout.relative_to(root))</pre><p>Results:</p><pre>converted/Screen Shot 2022-09-05 at 12.41.33.jpeg<br>converted/Screen Shot 2022-09-05 at 12.41.45.jpeg<br>converted/007.jpeg<br>converted/000.jpeg<br>converted/008.jpeg<br>converted/009.jpeg<br>converted/Screen Shot 2022-09-29 at 13.20.27.jpeg<br>converted/Screen Shot 2022-09-29 at 20.07.04.jpeg<br>converted/Screen Shot 2022-09-29 at 20.08.21.jpeg<br>converted/002.jpeg<br>converted/006.jpeg</pre><p>Note that we are placing the results in a parent directory different from the one we use for searching as we are doing so recursively by default. This is because we don’t want to get our results as inputs the second time we run the script.</p><h3>Conclusion</h3><p>Generators in Python are one of the most useful tools for processing data. If we want to automate a few tasks without using bash scripts (for whatever reason), we can start with a glob pattern function that yields the file types we want in an unorganized directory.</p><p>The benefit of using glob is that we don&#39;t have to use Python to check that each file suffix matches a list of file formats so we can scale our process more easily.</p><p>For example, in the following code, we can replace the first comprehension with the second one.</p><pre>[f for f in path.iterdir() if f.suffix in (&#39;.jpeg&#39;, &#39;.jpg&#39;, &#39;.png&#39;, &#39;JPG&#39;, &#39;JPEG&#39;, &#39;PNG&#39;)]</pre><pre>[f for f in path.glob(&#39;*.[jpJP][npNP]*[gG$]&#39;)]</pre><p>We could also do it recursively with rglob or by adding **/ to the beginning of our pattern. The downsides are that we could be matching unintended files if our pattern is not good enough for the job and that globs are not as powerful as regular expressions. As a bonus, we can use the same glob pattern in our .gitignore file.</p><h3>Footnotes</h3><p><a href="https://en.wikipedia.org/wiki/Glob_(programming)">https://en.wikipedia.org/wiki/Glob_(programming)</a></p><p><a href="https://docs.python.org/3/library/pathlib.html">https://docs.python.org/3/library/pathlib.html</a></p><p><a href="https://git-scm.com/docs/gitignore#_pattern_format">https://git-scm.com/docs/gitignore#_pattern_format</a></p><p><a href="https://pillow.readthedocs.io/en/stable/">https://pillow.readthedocs.io/en/stable/</a></p><p><a href="https://unsplash.com/photos/2JIvboGLeho?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink">https://unsplash.com/photos/2JIvboGLeho?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink</a></p><p><em>Originally published at </em><a href="https://github.com/AlbertoV5/python-blog/blob/main/docs/blog.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9ad86ca682" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/glob-generators-with-python-be9ad86ca682">Glob Generators With Python</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>